Compare commits
25 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d2038b7c5a | |||
| de81ba25fd | |||
| 858c65b314 | |||
| f00069be68 | |||
| 7b72406824 | |||
| 49925038fd | |||
| 05ba0339fe | |||
| cdd7f6158b | |||
| 7e0f5b6369 | |||
| 310a9ae4e0 | |||
| c57249481e | |||
| e72d83541a | |||
| 9f8c87ae8c | |||
| f6061f5ec6 | |||
| 12be5d716b | |||
| 1abb901ec2 | |||
| 6a17541713 | |||
| 040a57f56a | |||
| 15d2942aaa | |||
| 59a0653fd4 | |||
| 725c25c966 | |||
| d2fed34a30 | |||
| f12ed8e0b2 | |||
| 508cfbc843 | |||
| 245d681b7d |
@@ -1,5 +1,3 @@
|
|||||||
MODE="development"
|
|
||||||
|
|
||||||
VITE_APP_BACKEND_V2_GET_URL=https://json-dev.excalidraw.com/api/v2/
|
VITE_APP_BACKEND_V2_GET_URL=https://json-dev.excalidraw.com/api/v2/
|
||||||
VITE_APP_BACKEND_V2_POST_URL=https://json-dev.excalidraw.com/api/v2/post/
|
VITE_APP_BACKEND_V2_POST_URL=https://json-dev.excalidraw.com/api/v2/post/
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
MODE="production"
|
|
||||||
|
|
||||||
VITE_APP_BACKEND_V2_GET_URL=https://json.excalidraw.com/api/v2/
|
VITE_APP_BACKEND_V2_GET_URL=https://json.excalidraw.com/api/v2/
|
||||||
VITE_APP_BACKEND_V2_POST_URL=https://json.excalidraw.com/api/v2/post/
|
VITE_APP_BACKEND_V2_POST_URL=https://json.excalidraw.com/api/v2/post/
|
||||||
|
|
||||||
|
|||||||
@@ -32,12 +32,6 @@
|
|||||||
"name": "jotai",
|
"name": "jotai",
|
||||||
"message": "Do not import from \"jotai\" directly. Use our app-specific modules (\"editor-jotai\" or \"app-jotai\")."
|
"message": "Do not import from \"jotai\" directly. Use our app-specific modules (\"editor-jotai\" or \"app-jotai\")."
|
||||||
}
|
}
|
||||||
],
|
|
||||||
"react/jsx-no-target-blank": [
|
|
||||||
"error",
|
|
||||||
{
|
|
||||||
"allowReferrer": true
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,45 +0,0 @@
|
|||||||
# Project coding standards
|
|
||||||
|
|
||||||
## Generic Communication Guidelines
|
|
||||||
|
|
||||||
- Be succint and be aware that expansive generative AI answers are costly and slow
|
|
||||||
- Avoid providing explanations, trying to teach unless asked for, your chat partner is an expert
|
|
||||||
- Stop apologising if corrected, just provide the correct information or code
|
|
||||||
- Prefer code unless asked for explanation
|
|
||||||
- Stop summarizing what you've changed after modifications unless asked for
|
|
||||||
|
|
||||||
## TypeScript Guidelines
|
|
||||||
|
|
||||||
- Use TypeScript for all new code
|
|
||||||
- Where possible, prefer implementations without allocation
|
|
||||||
- When there is an option, opt for more performant solutions and trade RAM usage for less CPU cycles
|
|
||||||
- Prefer immutable data (const, readonly)
|
|
||||||
- Use optional chaining (?.) and nullish coalescing (??) operators
|
|
||||||
|
|
||||||
## React Guidelines
|
|
||||||
|
|
||||||
- Use functional components with hooks
|
|
||||||
- Follow the React hooks rules (no conditional hooks)
|
|
||||||
- Keep components small and focused
|
|
||||||
- Use CSS modules for component styling
|
|
||||||
|
|
||||||
## Naming Conventions
|
|
||||||
|
|
||||||
- Use PascalCase for component names, interfaces, and type aliases
|
|
||||||
- Use camelCase for variables, functions, and methods
|
|
||||||
- Use ALL_CAPS for constants
|
|
||||||
|
|
||||||
## Error Handling
|
|
||||||
|
|
||||||
- Use try/catch blocks for async operations
|
|
||||||
- Implement proper error boundaries in React components
|
|
||||||
- Always log errors with contextual information
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
- Always attempt to fix #problems
|
|
||||||
- Always offer to run `yarn test:app` in the project root after modifications are complete and attempt fixing the issues reported
|
|
||||||
|
|
||||||
## Types
|
|
||||||
|
|
||||||
- Always include `packages/math/src/types.ts` in the context when your write math related code and always use the Point type instead of { x, y}
|
|
||||||
@@ -12,10 +12,10 @@ jobs:
|
|||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
with:
|
with:
|
||||||
fetch-depth: 2
|
fetch-depth: 2
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js 18.x
|
||||||
uses: actions/setup-node@v2
|
uses: actions/setup-node@v2
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 18.x
|
||||||
- name: Set up publish access
|
- name: Set up publish access
|
||||||
run: |
|
run: |
|
||||||
npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
|
npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
|
||||||
@@ -24,4 +24,4 @@ jobs:
|
|||||||
- name: Auto release
|
- name: Auto release
|
||||||
run: |
|
run: |
|
||||||
yarn add @actions/core -W
|
yarn add @actions/core -W
|
||||||
yarn release --tag=next --non-interactive
|
yarn autorelease
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
name: Auto release excalidraw preview
|
||||||
|
on:
|
||||||
|
issue_comment:
|
||||||
|
types: [created, edited]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
Auto-release-excalidraw-preview:
|
||||||
|
name: Auto release preview
|
||||||
|
if: github.event.comment.body == '@excalibot trigger release' && github.event.issue.pull_request
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- name: React to release comment
|
||||||
|
uses: peter-evans/create-or-update-comment@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.PUSH_TRANSLATIONS_COVERAGE_PAT }}
|
||||||
|
comment-id: ${{ github.event.comment.id }}
|
||||||
|
reactions: "+1"
|
||||||
|
- name: Get PR SHA
|
||||||
|
id: sha
|
||||||
|
uses: actions/github-script@v4
|
||||||
|
with:
|
||||||
|
result-encoding: string
|
||||||
|
script: |
|
||||||
|
const { owner, repo, number } = context.issue;
|
||||||
|
const pr = await github.pulls.get({
|
||||||
|
owner,
|
||||||
|
repo,
|
||||||
|
pull_number: number,
|
||||||
|
});
|
||||||
|
return pr.data.head.sha
|
||||||
|
- uses: actions/checkout@v2
|
||||||
|
with:
|
||||||
|
ref: ${{ steps.sha.outputs.result }}
|
||||||
|
fetch-depth: 2
|
||||||
|
- name: Setup Node.js 18.x
|
||||||
|
uses: actions/setup-node@v2
|
||||||
|
with:
|
||||||
|
node-version: 18.x
|
||||||
|
- name: Set up publish access
|
||||||
|
run: |
|
||||||
|
npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
|
||||||
|
env:
|
||||||
|
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||||
|
- name: Auto release preview
|
||||||
|
id: "autorelease"
|
||||||
|
run: |
|
||||||
|
yarn add @actions/core -W
|
||||||
|
yarn autorelease preview ${{ github.event.issue.number }}
|
||||||
|
- name: Post comment post release
|
||||||
|
if: always()
|
||||||
|
uses: peter-evans/create-or-update-comment@v1
|
||||||
|
with:
|
||||||
|
token: ${{ secrets.PUSH_TRANSLATIONS_COVERAGE_PAT }}
|
||||||
|
issue-number: ${{ github.event.issue.number }}
|
||||||
|
body: "@${{ github.event.comment.user.login }} ${{ steps.autorelease.outputs.result }}"
|
||||||
@@ -9,10 +9,10 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js 18.x
|
||||||
uses: actions/setup-node@v2
|
uses: actions/setup-node@v2
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 18.x
|
||||||
|
|
||||||
- name: Install and lint
|
- name: Install and lint
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -14,10 +14,10 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
token: ${{ secrets.PUSH_TRANSLATIONS_COVERAGE_PAT }}
|
token: ${{ secrets.PUSH_TRANSLATIONS_COVERAGE_PAT }}
|
||||||
|
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js 18.x
|
||||||
uses: actions/setup-node@v2
|
uses: actions/setup-node@v2
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 18.x
|
||||||
|
|
||||||
- name: Create report file
|
- name: Create report file
|
||||||
run: |
|
run: |
|
||||||
|
|||||||
@@ -17,14 +17,9 @@ jobs:
|
|||||||
with:
|
with:
|
||||||
username: ${{ secrets.DOCKER_USERNAME }}
|
username: ${{ secrets.DOCKER_USERNAME }}
|
||||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v3
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v3
|
|
||||||
- name: Build and push
|
- name: Build and push
|
||||||
uses: docker/build-push-action@v5
|
uses: docker/build-push-action@v3
|
||||||
with:
|
with:
|
||||||
context: .
|
context: .
|
||||||
push: true
|
push: true
|
||||||
tags: excalidraw/excalidraw:latest
|
tags: excalidraw/excalidraw:latest
|
||||||
platforms: linux/amd64, linux/arm64, linux/arm/v7
|
|
||||||
|
|||||||
@@ -10,10 +10,10 @@ jobs:
|
|||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v2
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js 18.x
|
||||||
uses: actions/setup-node@v2
|
uses: actions/setup-node@v2
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 18.x
|
||||||
- name: Install and build
|
- name: Install and build
|
||||||
run: |
|
run: |
|
||||||
yarn --frozen-lockfile
|
yarn --frozen-lockfile
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ jobs:
|
|||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
- name: Setup Node.js
|
- name: Setup Node.js 18.x
|
||||||
uses: actions/setup-node@v3
|
uses: actions/setup-node@v3
|
||||||
with:
|
with:
|
||||||
node-version: 20.x
|
node-version: 18.x
|
||||||
- name: Install in packages/excalidraw
|
- name: Install in packages/excalidraw
|
||||||
run: yarn
|
run: yarn
|
||||||
working-directory: packages/excalidraw
|
working-directory: packages/excalidraw
|
||||||
|
|||||||
+1
-2
@@ -25,5 +25,4 @@ packages/excalidraw/types
|
|||||||
coverage
|
coverage
|
||||||
dev-dist
|
dev-dist
|
||||||
html
|
html
|
||||||
meta*.json
|
meta*.json
|
||||||
.claude
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
# CLAUDE.md
|
|
||||||
|
|
||||||
## Project Structure
|
|
||||||
|
|
||||||
Excalidraw is a **monorepo** with a clear separation between the core library and the application:
|
|
||||||
|
|
||||||
- **`packages/excalidraw/`** - Main React component library published to npm as `@excalidraw/excalidraw`
|
|
||||||
- **`excalidraw-app/`** - Full-featured web application (excalidraw.com) that uses the library
|
|
||||||
- **`packages/`** - Core packages: `@excalidraw/common`, `@excalidraw/element`, `@excalidraw/math`, `@excalidraw/utils`
|
|
||||||
- **`examples/`** - Integration examples (NextJS, browser script)
|
|
||||||
|
|
||||||
## Development Workflow
|
|
||||||
|
|
||||||
1. **Package Development**: Work in `packages/*` for editor features
|
|
||||||
2. **App Development**: Work in `excalidraw-app/` for app-specific features
|
|
||||||
3. **Testing**: Always run `yarn test:update` before committing
|
|
||||||
4. **Type Safety**: Use `yarn test:typecheck` to verify TypeScript
|
|
||||||
|
|
||||||
## Development Commands
|
|
||||||
|
|
||||||
```bash
|
|
||||||
yarn test:typecheck # TypeScript type checking
|
|
||||||
yarn test:update # Run all tests (with snapshot updates)
|
|
||||||
yarn fix # Auto-fix formatting and linting issues
|
|
||||||
```
|
|
||||||
|
|
||||||
## Architecture Notes
|
|
||||||
|
|
||||||
### Package System
|
|
||||||
|
|
||||||
- Uses Yarn workspaces for monorepo management
|
|
||||||
- Internal packages use path aliases (see `vitest.config.mts`)
|
|
||||||
- Build system uses esbuild for packages, Vite for the app
|
|
||||||
- TypeScript throughout with strict configuration
|
|
||||||
+4
-5
@@ -1,4 +1,4 @@
|
|||||||
FROM --platform=${BUILDPLATFORM} node:18 AS build
|
FROM node:18 AS build
|
||||||
|
|
||||||
WORKDIR /opt/node_app
|
WORKDIR /opt/node_app
|
||||||
|
|
||||||
@@ -6,14 +6,13 @@ COPY . .
|
|||||||
|
|
||||||
# do not ignore optional dependencies:
|
# do not ignore optional dependencies:
|
||||||
# Error: Cannot find module @rollup/rollup-linux-x64-gnu
|
# Error: Cannot find module @rollup/rollup-linux-x64-gnu
|
||||||
RUN --mount=type=cache,target=/root/.cache/yarn \
|
RUN yarn --network-timeout 600000
|
||||||
npm_config_target_arch=${TARGETARCH} yarn --network-timeout 600000
|
|
||||||
|
|
||||||
ARG NODE_ENV=production
|
ARG NODE_ENV=production
|
||||||
|
|
||||||
RUN npm_config_target_arch=${TARGETARCH} yarn build:app:docker
|
RUN yarn build:app:docker
|
||||||
|
|
||||||
FROM --platform=${TARGETPLATFORM} nginx:1.27-alpine
|
FROM nginx:1.27-alpine
|
||||||
|
|
||||||
COPY --from=build /opt/node_app/excalidraw-app/build /usr/share/nginx/html
|
COPY --from=build /opt/node_app/excalidraw-app/build /usr/share/nginx/html
|
||||||
|
|
||||||
|
|||||||
@@ -23,17 +23,20 @@
|
|||||||
<br />
|
<br />
|
||||||
<p align="center">
|
<p align="center">
|
||||||
<a href="https://github.com/excalidraw/excalidraw/blob/master/LICENSE">
|
<a href="https://github.com/excalidraw/excalidraw/blob/master/LICENSE">
|
||||||
<img alt="Excalidraw is released under the MIT license." src="https://img.shields.io/badge/license-MIT-blue.svg" /></a>
|
<img alt="Excalidraw is released under the MIT license." src="https://img.shields.io/badge/license-MIT-blue.svg" />
|
||||||
|
</a>
|
||||||
<a href="https://www.npmjs.com/package/@excalidraw/excalidraw">
|
<a href="https://www.npmjs.com/package/@excalidraw/excalidraw">
|
||||||
<img alt="npm downloads/month" src="https://img.shields.io/npm/dm/@excalidraw/excalidraw" /></a>
|
<img alt="npm downloads/month" src="https://img.shields.io/npm/dm/@excalidraw/excalidraw" />
|
||||||
|
</a>
|
||||||
<a href="https://docs.excalidraw.com/docs/introduction/contributing">
|
<a href="https://docs.excalidraw.com/docs/introduction/contributing">
|
||||||
<img alt="PRs welcome!" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat" /></a>
|
<img alt="PRs welcome!" src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat" />
|
||||||
|
</a>
|
||||||
<a href="https://discord.gg/UexuTaE">
|
<a href="https://discord.gg/UexuTaE">
|
||||||
<img alt="Chat on Discord" src="https://img.shields.io/discord/723672430744174682?color=738ad6&label=Chat%20on%20Discord&logo=discord&logoColor=ffffff&widge=false"/></a>
|
<img alt="Chat on Discord" src="https://img.shields.io/discord/723672430744174682?color=738ad6&label=Chat%20on%20Discord&logo=discord&logoColor=ffffff&widge=false"/>
|
||||||
<a href="https://deepwiki.com/excalidraw/excalidraw">
|
</a>
|
||||||
<img alt="Ask DeepWiki" src="https://deepwiki.com/badge.svg" /></a>
|
|
||||||
<a href="https://twitter.com/excalidraw">
|
<a href="https://twitter.com/excalidraw">
|
||||||
<img alt="Follow Excalidraw on Twitter" src="https://img.shields.io/twitter/follow/excalidraw.svg?label=follow+@excalidraw&style=social&logo=twitter"/></a>
|
<img alt="Follow Excalidraw on Twitter" src="https://img.shields.io/twitter/follow/excalidraw.svg?label=follow+@excalidraw&style=social&logo=twitter"/>
|
||||||
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<div align="center">
|
<div align="center">
|
||||||
@@ -60,7 +63,7 @@ The Excalidraw editor (npm package) supports:
|
|||||||
- 🏗️ Customizable.
|
- 🏗️ Customizable.
|
||||||
- 📷 Image support.
|
- 📷 Image support.
|
||||||
- 😀 Shape libraries support.
|
- 😀 Shape libraries support.
|
||||||
- 🌐 Localization (i18n) support.
|
- 👅 Localization (i18n) support.
|
||||||
- 🖼️ Export to PNG, SVG & clipboard.
|
- 🖼️ Export to PNG, SVG & clipboard.
|
||||||
- 💾 Open format - export drawings as an `.excalidraw` json file.
|
- 💾 Open format - export drawings as an `.excalidraw` json file.
|
||||||
- ⚒️ Wide range of tools - rectangle, circle, diamond, arrow, line, free-draw, eraser...
|
- ⚒️ Wide range of tools - rectangle, circle, diamond, arrow, line, free-draw, eraser...
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ You will need to import the `Footer` component from the package and wrap your co
|
|||||||
```jsx live
|
```jsx live
|
||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
<div style={{ height: "500px" }}>
|
<div style={{ height: "500px"}}>
|
||||||
<Excalidraw>
|
<Excalidraw>
|
||||||
<Footer>
|
<Footer>
|
||||||
<button
|
<button
|
||||||
@@ -27,19 +27,19 @@ function App() {
|
|||||||
|
|
||||||
This will only work for `Desktop` devices.
|
This will only work for `Desktop` devices.
|
||||||
|
|
||||||
For `mobile` you will need to render it inside the [MainMenu](#mainmenu). You can use the [`useEditorInterface`](#useEditorInterface) hook to check the type of device, this will be available only inside the `children` of `Excalidraw` component.
|
For `mobile` you will need to render it inside the [MainMenu](#mainmenu). You can use the [`useDevice`](#useDevice) hook to check the type of device, this will be available only inside the `children` of `Excalidraw` component.
|
||||||
|
|
||||||
Open the `Menu` in the below playground and you will see the `custom footer` rendered.
|
Open the `Menu` in the below playground and you will see the `custom footer` rendered.
|
||||||
|
|
||||||
```jsx live noInline
|
```jsx live noInline
|
||||||
const MobileFooter = ({}) => {
|
const MobileFooter = ({}) => {
|
||||||
const editorInterface = useEditorInterface();
|
const device = useDevice();
|
||||||
if (editorInterface.formFactor === "phone") {
|
if (device.editor.isMobile) {
|
||||||
return (
|
return (
|
||||||
<Footer>
|
<Footer>
|
||||||
<button
|
<button
|
||||||
className="custom-footer"
|
className="custom-footer"
|
||||||
style={{ marginLeft: "20px", height: "2rem" }}
|
style= {{ marginLeft: '20px', height: '2rem'}}
|
||||||
onClick={() => alert("This is custom footer in mobile menu")}
|
onClick={() => alert("This is custom footer in mobile menu")}
|
||||||
>
|
>
|
||||||
custom footer
|
custom footer
|
||||||
|
|||||||
@@ -363,7 +363,13 @@ This API has the below signature. It sets the `tool` passed in param as the acti
|
|||||||
```ts
|
```ts
|
||||||
(
|
(
|
||||||
tool: (
|
tool: (
|
||||||
| { type: ToolType }
|
| (
|
||||||
|
| { type: Exclude<ToolType, "image"> }
|
||||||
|
| {
|
||||||
|
type: Extract<ToolType, "image">;
|
||||||
|
insertOnCanvasDirectly?: boolean;
|
||||||
|
}
|
||||||
|
)
|
||||||
| { type: "custom"; customType: string }
|
| { type: "custom"; customType: string }
|
||||||
) & { locked?: boolean },
|
) & { locked?: boolean },
|
||||||
) => {};
|
) => {};
|
||||||
@@ -371,7 +377,7 @@ This API has the below signature. It sets the `tool` passed in param as the acti
|
|||||||
|
|
||||||
| Name | Type | Default | Description |
|
| Name | Type | Default | Description |
|
||||||
| --- | --- | --- | --- |
|
| --- | --- | --- | --- |
|
||||||
| `type` | [ToolType](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L91) | `selection` | The tool type which should be set as active tool |
|
| `type` | [ToolType](https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L91) | `selection` | The tool type which should be set as active tool. When setting `image` as active tool, the insertion onto canvas when using image tool is disabled by default, so you can enable it by setting `insertOnCanvasDirectly` to `true` |
|
||||||
| `locked` | `boolean` | `false` | Indicates whether the the active tool should be locked. It behaves the same way when using the `lock` tool in the editor interface |
|
| `locked` | `boolean` | `false` | Indicates whether the the active tool should be locked. It behaves the same way when using the `lock` tool in the editor interface |
|
||||||
|
|
||||||
## setCursor
|
## setCursor
|
||||||
|
|||||||
@@ -292,7 +292,7 @@ viewportCoordsToSceneCoords({ clientX: number, clientY: number },<br/> 
|
|||||||
appState: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95">AppState</a><br/>): {x: number, y: number}
|
appState: <a href="https://github.com/excalidraw/excalidraw/blob/master/packages/excalidraw/types.ts#L95">AppState</a><br/>): {x: number, y: number}
|
||||||
</pre>
|
</pre>
|
||||||
|
|
||||||
### useEditorInterface
|
### useDevice
|
||||||
|
|
||||||
This hook can be used to check the type of device which is being used. It can only be used inside the `children` of `Excalidraw` component.
|
This hook can be used to check the type of device which is being used. It can only be used inside the `children` of `Excalidraw` component.
|
||||||
|
|
||||||
@@ -300,8 +300,8 @@ Open the `main menu` in the below example to view the footer.
|
|||||||
|
|
||||||
```jsx live noInline
|
```jsx live noInline
|
||||||
const MobileFooter = ({}) => {
|
const MobileFooter = ({}) => {
|
||||||
const editorInterface = useEditorInterface();
|
const device = useDevice();
|
||||||
if (editorInterface.formFactor === "phone") {
|
if (device.editor.isMobile) {
|
||||||
return (
|
return (
|
||||||
<Footer>
|
<Footer>
|
||||||
<button
|
<button
|
||||||
@@ -336,20 +336,12 @@ render(<App />);
|
|||||||
The `device` has the following `attributes`, some grouped into `viewport` and `editor` objects, per context.
|
The `device` has the following `attributes`, some grouped into `viewport` and `editor` objects, per context.
|
||||||
|
|
||||||
| Name | Type | Description |
|
| Name | Type | Description |
|
||||||
| ---- | ---- | ----------- |
|
| --- | --- | --- |
|
||||||
|
| `viewport.isMobile` | `boolean` | Set to `true` when viewport is in `mobile` breakpoint |
|
||||||
The `EditorInterface` object has the following properties:
|
| `viewport.isLandscape` | `boolean` | Set to `true` when the viewport is in `landscape` mode |
|
||||||
|
| `editor.canFitSidebar` | `boolean` | Set to `true` if there's enough space to fit the `sidebar` |
|
||||||
| Name | Type | Description |
|
| `editor.isMobile` | `boolean` | Set to `true` when editor container is in `mobile` breakpoint |
|
||||||
| --- | --- | --- | --- | --- | --- |
|
| `isTouchScreen` | `boolean` | Set to `true` for `touch` when touch event detected |
|
||||||
| `formFactor` | `'phone' | 'tablet' | 'desktop'` | Indicates the device type based on screen size |
|
|
||||||
| `desktopUIMode` | `'compact' | 'full'` | UI mode for desktop form factor |
|
|
||||||
| `userAgent.raw` | `string` | Raw user agent string |
|
|
||||||
| `userAgent.isMobileDevice` | `boolean` | True if device is mobile |
|
|
||||||
| `userAgent.platform` | `'ios' | 'android' | 'other' | 'unknown'` | Device platform |
|
|
||||||
| `isTouchScreen` | `boolean` | True if touch events are detected |
|
|
||||||
| `canFitSidebar` | `boolean` | True if sidebar can fit in the viewport |
|
|
||||||
| `isLandscape` | `boolean` | True if viewport is in landscape mode |
|
|
||||||
|
|
||||||
### i18n
|
### i18n
|
||||||
|
|
||||||
|
|||||||
@@ -28,12 +28,32 @@ To start the example app using the `@excalidraw/excalidraw` package, follow the
|
|||||||
|
|
||||||
## Releasing
|
## Releasing
|
||||||
|
|
||||||
|
### Create a test release
|
||||||
|
|
||||||
|
You can create a test release by posting the below comment in your pull request:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
@excalibot trigger release
|
||||||
|
```
|
||||||
|
|
||||||
|
Once the version is released `@excalibot` will post a comment with the release version.
|
||||||
|
|
||||||
### Creating a production release
|
### Creating a production release
|
||||||
|
|
||||||
To release the next stable version follow the below steps:
|
To release the next stable version follow the below steps:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
yarn release --tag=latest --version=0.19.0
|
yarn prerelease:excalidraw
|
||||||
```
|
```
|
||||||
|
|
||||||
You will need to pass the `latest` tag with `version` for which you want to create the release. This will make the changes needed before publishing the packages into NPM, like updating dependencies of all `@excalidraw/*` packages, generating new entries in `CHANGELOG.md` and more.
|
You need to pass the `version` for which you want to create the release. This will make the changes needed before making the release like updating `package.json`, `changelog` and more.
|
||||||
|
|
||||||
|
The next step is to run the `release` script:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
yarn release:excalidraw
|
||||||
|
```
|
||||||
|
|
||||||
|
This will publish the package.
|
||||||
|
|
||||||
|
Right now there are two steps to create a production release but once this works fine these scripts will be combined and more automation will be done.
|
||||||
|
|||||||
@@ -38,8 +38,6 @@ If you want to only import `Excalidraw` component you can do :point_down:
|
|||||||
|
|
||||||
```jsx showLineNumbers
|
```jsx showLineNumbers
|
||||||
import dynamic from "next/dynamic";
|
import dynamic from "next/dynamic";
|
||||||
import "@excalidraw/excalidraw/index.css";
|
|
||||||
|
|
||||||
const Excalidraw = dynamic(
|
const Excalidraw = dynamic(
|
||||||
async () => (await import("@excalidraw/excalidraw")).Excalidraw,
|
async () => (await import("@excalidraw/excalidraw")).Excalidraw,
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -33,7 +33,6 @@ const ExcalidrawScope = {
|
|||||||
initialData,
|
initialData,
|
||||||
useI18n: ExcalidrawComp.useI18n,
|
useI18n: ExcalidrawComp.useI18n,
|
||||||
convertToExcalidrawElements: ExcalidrawComp.convertToExcalidrawElements,
|
convertToExcalidrawElements: ExcalidrawComp.convertToExcalidrawElements,
|
||||||
CaptureUpdateAction: ExcalidrawComp.CaptureUpdateAction,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export default ExcalidrawScope;
|
export default ExcalidrawScope;
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
version: "3.8"
|
||||||
|
|
||||||
services:
|
services:
|
||||||
excalidraw:
|
excalidraw:
|
||||||
build:
|
build:
|
||||||
|
|||||||
@@ -3,8 +3,7 @@
|
|||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build:packages": "yarn --cwd ../../ build:packages",
|
"build:workspace": "yarn workspace @excalidraw/excalidraw run build:esm && yarn copy:assets",
|
||||||
"build:workspace": "yarn build:packages && yarn copy:assets",
|
|
||||||
"copy:assets": "cp -r ../../packages/excalidraw/dist/prod/fonts ./public",
|
"copy:assets": "cp -r ../../packages/excalidraw/dist/prod/fonts ./public",
|
||||||
"dev": "yarn build:workspace && next dev -p 3005",
|
"dev": "yarn build:workspace && next dev -p 3005",
|
||||||
"build": "yarn build:workspace && next build",
|
"build": "yarn build:workspace && next build",
|
||||||
|
|||||||
@@ -52,7 +52,7 @@
|
|||||||
transform: none;
|
transform: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.excalidraw .selected-shape-actions {
|
.excalidraw .panelColumn {
|
||||||
text-align: left;
|
text-align: left;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,10 +12,10 @@ const MobileFooter = ({
|
|||||||
excalidrawAPI: ExcalidrawImperativeAPI;
|
excalidrawAPI: ExcalidrawImperativeAPI;
|
||||||
excalidrawLib: typeof TExcalidraw;
|
excalidrawLib: typeof TExcalidraw;
|
||||||
}) => {
|
}) => {
|
||||||
const { useEditorInterface, Footer } = excalidrawLib;
|
const { useDevice, Footer } = excalidrawLib;
|
||||||
|
|
||||||
const editorInterface = useEditorInterface();
|
const device = useDevice();
|
||||||
if (editorInterface.formFactor === "phone") {
|
if (device.editor.isMobile) {
|
||||||
return (
|
return (
|
||||||
<Footer>
|
<Footer>
|
||||||
<CustomFooter
|
<CustomFooter
|
||||||
|
|||||||
@@ -17,6 +17,6 @@
|
|||||||
"build": "vite build",
|
"build": "vite build",
|
||||||
"preview": "vite preview --port 5002",
|
"preview": "vite preview --port 5002",
|
||||||
"build:preview": "yarn build && yarn preview",
|
"build:preview": "yarn build && yarn preview",
|
||||||
"build:packages": "yarn --cwd ../../ build:packages"
|
"build:package": "yarn workspace @excalidraw/excalidraw run build:esm"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"outputDirectory": "dist",
|
"outputDirectory": "dist",
|
||||||
"installCommand": "yarn install",
|
"installCommand": "yarn install",
|
||||||
"buildCommand": "yarn build:packages && yarn build"
|
"buildCommand": "yarn build:package && yarn build"
|
||||||
}
|
}
|
||||||
|
|||||||
+165
-31
@@ -1,10 +1,13 @@
|
|||||||
|
import Slider from "rc-slider";
|
||||||
|
|
||||||
|
import "rc-slider/assets/index.css";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
Excalidraw,
|
Excalidraw,
|
||||||
LiveCollaborationTrigger,
|
LiveCollaborationTrigger,
|
||||||
TTDDialogTrigger,
|
TTDDialogTrigger,
|
||||||
CaptureUpdateAction,
|
CaptureUpdateAction,
|
||||||
reconcileElements,
|
reconcileElements,
|
||||||
useEditorInterface,
|
|
||||||
} from "@excalidraw/excalidraw";
|
} from "@excalidraw/excalidraw";
|
||||||
import { trackEvent } from "@excalidraw/excalidraw/analytics";
|
import { trackEvent } from "@excalidraw/excalidraw/analytics";
|
||||||
import { getDefaultAppState } from "@excalidraw/excalidraw/appState";
|
import { getDefaultAppState } from "@excalidraw/excalidraw/appState";
|
||||||
@@ -21,6 +24,7 @@ import {
|
|||||||
APP_NAME,
|
APP_NAME,
|
||||||
EVENT,
|
EVENT,
|
||||||
THEME,
|
THEME,
|
||||||
|
TITLE_TIMEOUT,
|
||||||
VERSION_TIMEOUT,
|
VERSION_TIMEOUT,
|
||||||
debounce,
|
debounce,
|
||||||
getVersion,
|
getVersion,
|
||||||
@@ -30,6 +34,7 @@ import {
|
|||||||
resolvablePromise,
|
resolvablePromise,
|
||||||
isRunningInIframe,
|
isRunningInIframe,
|
||||||
isDevEnv,
|
isDevEnv,
|
||||||
|
assertNever,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
import polyfill from "@excalidraw/excalidraw/polyfill";
|
import polyfill from "@excalidraw/excalidraw/polyfill";
|
||||||
import { useCallback, useEffect, useRef, useState } from "react";
|
import { useCallback, useEffect, useRef, useState } from "react";
|
||||||
@@ -47,15 +52,16 @@ import {
|
|||||||
share,
|
share,
|
||||||
youtubeIcon,
|
youtubeIcon,
|
||||||
} from "@excalidraw/excalidraw/components/icons";
|
} from "@excalidraw/excalidraw/components/icons";
|
||||||
import { isElementLink } from "@excalidraw/element";
|
import { isElementLink } from "@excalidraw/element/elementLink";
|
||||||
import { restore, restoreAppState } from "@excalidraw/excalidraw/data/restore";
|
import { restore, restoreAppState } from "@excalidraw/excalidraw/data/restore";
|
||||||
import { newElementWith } from "@excalidraw/element";
|
import { newElementWith } from "@excalidraw/element/mutateElement";
|
||||||
import { isInitializedImageElement } from "@excalidraw/element";
|
import { isInitializedImageElement } from "@excalidraw/element/typeChecks";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import {
|
import {
|
||||||
parseLibraryTokensFromUrl,
|
parseLibraryTokensFromUrl,
|
||||||
useHandleLibrary,
|
useHandleLibrary,
|
||||||
} from "@excalidraw/excalidraw/data/library";
|
} from "@excalidraw/excalidraw/data/library";
|
||||||
|
import { StoreDelta, DurableStoreIncrement, EphemeralStoreIncrement, StoreIncrement } from "@excalidraw/excalidraw/store";
|
||||||
|
|
||||||
import type { RemoteExcalidrawElement } from "@excalidraw/excalidraw/data/reconcile";
|
import type { RemoteExcalidrawElement } from "@excalidraw/excalidraw/data/reconcile";
|
||||||
import type { RestoredDataState } from "@excalidraw/excalidraw/data/restore";
|
import type { RestoredDataState } from "@excalidraw/excalidraw/data/restore";
|
||||||
@@ -63,6 +69,7 @@ import type {
|
|||||||
FileId,
|
FileId,
|
||||||
NonDeletedExcalidrawElement,
|
NonDeletedExcalidrawElement,
|
||||||
OrderedExcalidrawElement,
|
OrderedExcalidrawElement,
|
||||||
|
SceneElementsMap,
|
||||||
} from "@excalidraw/element/types";
|
} from "@excalidraw/element/types";
|
||||||
import type {
|
import type {
|
||||||
AppState,
|
AppState,
|
||||||
@@ -92,6 +99,7 @@ import Collab, {
|
|||||||
collabAPIAtom,
|
collabAPIAtom,
|
||||||
isCollaboratingAtom,
|
isCollaboratingAtom,
|
||||||
isOfflineAtom,
|
isOfflineAtom,
|
||||||
|
syncApiAtom,
|
||||||
} from "./collab/Collab";
|
} from "./collab/Collab";
|
||||||
import { AppFooter } from "./components/AppFooter";
|
import { AppFooter } from "./components/AppFooter";
|
||||||
import { AppMainMenu } from "./components/AppMainMenu";
|
import { AppMainMenu } from "./components/AppMainMenu";
|
||||||
@@ -120,7 +128,6 @@ import {
|
|||||||
LibraryIndexedDBAdapter,
|
LibraryIndexedDBAdapter,
|
||||||
LibraryLocalStorageMigrationAdapter,
|
LibraryLocalStorageMigrationAdapter,
|
||||||
LocalData,
|
LocalData,
|
||||||
localStorageQuotaExceededAtom,
|
|
||||||
} from "./data/LocalData";
|
} from "./data/LocalData";
|
||||||
import { isBrowserStorageStateNewer } from "./data/tabSync";
|
import { isBrowserStorageStateNewer } from "./data/tabSync";
|
||||||
import { ShareDialog, shareDialogStateAtom } from "./share/ShareDialog";
|
import { ShareDialog, shareDialogStateAtom } from "./share/ShareDialog";
|
||||||
@@ -138,9 +145,6 @@ import { ExcalidrawPlusIframeExport } from "./ExcalidrawPlusIframeExport";
|
|||||||
|
|
||||||
import "./index.scss";
|
import "./index.scss";
|
||||||
|
|
||||||
import { ExcalidrawPlusPromoBanner } from "./components/ExcalidrawPlusPromoBanner";
|
|
||||||
import { AppSidebar } from "./components/AppSidebar";
|
|
||||||
|
|
||||||
import type { CollabAPI } from "./collab/Collab";
|
import type { CollabAPI } from "./collab/Collab";
|
||||||
|
|
||||||
polyfill();
|
polyfill();
|
||||||
@@ -346,8 +350,6 @@ const ExcalidrawWrapper = () => {
|
|||||||
|
|
||||||
const [langCode, setLangCode] = useAppLangCode();
|
const [langCode, setLangCode] = useAppLangCode();
|
||||||
|
|
||||||
const editorInterface = useEditorInterface();
|
|
||||||
|
|
||||||
// initial state
|
// initial state
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
@@ -374,11 +376,40 @@ const ExcalidrawWrapper = () => {
|
|||||||
|
|
||||||
const [, setShareDialogState] = useAtom(shareDialogStateAtom);
|
const [, setShareDialogState] = useAtom(shareDialogStateAtom);
|
||||||
const [collabAPI] = useAtom(collabAPIAtom);
|
const [collabAPI] = useAtom(collabAPIAtom);
|
||||||
|
const [syncAPI] = useAtom(syncApiAtom);
|
||||||
|
const [sliderVersion, setSliderVersion] = useState(0);
|
||||||
|
const [acknowledgedDeltas, setAcknowledgedDeltas] = useState<StoreDelta[]>(
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
const acknowledgedDeltasRef = useRef<StoreDelta[]>(acknowledgedDeltas);
|
||||||
const [isCollaborating] = useAtomWithInitialValue(isCollaboratingAtom, () => {
|
const [isCollaborating] = useAtomWithInitialValue(isCollaboratingAtom, () => {
|
||||||
return isCollaborationLink(window.location.href);
|
return isCollaborationLink(window.location.href);
|
||||||
});
|
});
|
||||||
const collabError = useAtomValue(collabErrorIndicatorAtom);
|
const collabError = useAtomValue(collabErrorIndicatorAtom);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
acknowledgedDeltasRef.current = acknowledgedDeltas;
|
||||||
|
}, [acknowledgedDeltas]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const interval = setInterval(() => {
|
||||||
|
const deltas = syncAPI?.acknowledgedDeltas ?? [];
|
||||||
|
|
||||||
|
// CFDO: buffer local deltas as well, not only acknowledged ones
|
||||||
|
if (deltas.length > acknowledgedDeltasRef.current.length) {
|
||||||
|
setAcknowledgedDeltas([...deltas]);
|
||||||
|
setSliderVersion(deltas.length);
|
||||||
|
}
|
||||||
|
}, 1000);
|
||||||
|
|
||||||
|
syncAPI?.connect();
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
syncAPI?.disconnect();
|
||||||
|
clearInterval(interval);
|
||||||
|
};
|
||||||
|
}, [syncAPI]);
|
||||||
|
|
||||||
useHandleLibrary({
|
useHandleLibrary({
|
||||||
excalidrawAPI,
|
excalidrawAPI,
|
||||||
adapter: LibraryIndexedDBAdapter,
|
adapter: LibraryIndexedDBAdapter,
|
||||||
@@ -505,6 +536,11 @@ const ExcalidrawWrapper = () => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const titleTimeout = setTimeout(
|
||||||
|
() => (document.title = APP_NAME),
|
||||||
|
TITLE_TIMEOUT,
|
||||||
|
);
|
||||||
|
|
||||||
const syncData = debounce(() => {
|
const syncData = debounce(() => {
|
||||||
if (isTestEnv()) {
|
if (isTestEnv()) {
|
||||||
return;
|
return;
|
||||||
@@ -595,6 +631,7 @@ const ExcalidrawWrapper = () => {
|
|||||||
visibilityChange,
|
visibilityChange,
|
||||||
false,
|
false,
|
||||||
);
|
);
|
||||||
|
clearTimeout(titleTimeout);
|
||||||
};
|
};
|
||||||
}, [isCollabDisabled, collabAPI, excalidrawAPI, setLangCode]);
|
}, [isCollabDisabled, collabAPI, excalidrawAPI, setLangCode]);
|
||||||
|
|
||||||
@@ -669,12 +706,40 @@ const ExcalidrawWrapper = () => {
|
|||||||
debugRenderer(
|
debugRenderer(
|
||||||
debugCanvasRef.current,
|
debugCanvasRef.current,
|
||||||
appState,
|
appState,
|
||||||
elements,
|
|
||||||
window.devicePixelRatio,
|
window.devicePixelRatio,
|
||||||
|
() => forceRefresh((prev) => !prev),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const onIncrement = (
|
||||||
|
increment: DurableStoreIncrement | EphemeralStoreIncrement,
|
||||||
|
) => {
|
||||||
|
try {
|
||||||
|
if (!syncAPI) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StoreIncrement.isDurable(increment)) {
|
||||||
|
// push only if there are element changes
|
||||||
|
if (!increment.delta.elements.isEmpty()) {
|
||||||
|
syncAPI.push(increment.delta);
|
||||||
|
}
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (StoreIncrement.isEphemeral(increment)) {
|
||||||
|
syncAPI.relay(increment.change);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
assertNever(increment, `Unknown increment type`);
|
||||||
|
} catch (e) {
|
||||||
|
console.error("Error during onIncrement handler", e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const [latestShareableLink, setLatestShareableLink] = useState<string | null>(
|
const [latestShareableLink, setLatestShareableLink] = useState<string | null>(
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
@@ -734,8 +799,6 @@ const ExcalidrawWrapper = () => {
|
|||||||
|
|
||||||
const isOffline = useAtomValue(isOfflineAtom);
|
const isOffline = useAtomValue(isOfflineAtom);
|
||||||
|
|
||||||
const localStorageQuotaExceeded = useAtomValue(localStorageQuotaExceededAtom);
|
|
||||||
|
|
||||||
const onCollabDialogOpen = useCallback(
|
const onCollabDialogOpen = useCallback(
|
||||||
() => setShareDialogState({ isOpen: true, type: "collaborationOnly" }),
|
() => setShareDialogState({ isOpen: true, type: "collaborationOnly" }),
|
||||||
[setShareDialogState],
|
[setShareDialogState],
|
||||||
@@ -799,6 +862,57 @@ const ExcalidrawWrapper = () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const debouncedTimeTravel = debounce(
|
||||||
|
(value: number, direction: "forward" | "backward") => {
|
||||||
|
if (!excalidrawAPI) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let nextAppState = excalidrawAPI.getAppState();
|
||||||
|
// CFDO: retrieve the scene map already
|
||||||
|
let nextElements = new Map(
|
||||||
|
excalidrawAPI.getSceneElements().map((x) => [x.id, x]),
|
||||||
|
) as SceneElementsMap;
|
||||||
|
|
||||||
|
let deltas: StoreDelta[] = [];
|
||||||
|
|
||||||
|
// CFDO I: going both in collaborative setting means the (acknowledge) deltas need to have applied latest changes
|
||||||
|
switch (direction) {
|
||||||
|
case "forward": {
|
||||||
|
deltas = acknowledgedDeltas.slice(sliderVersion, value) ?? [];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "backward": {
|
||||||
|
deltas = acknowledgedDeltas
|
||||||
|
.slice(value)
|
||||||
|
.reverse()
|
||||||
|
.map((x) => StoreDelta.inverse(x));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
assertNever(direction, `Unknown direction: ${direction}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const delta of deltas) {
|
||||||
|
[nextElements, nextAppState] = excalidrawAPI.store.applyDeltaTo(
|
||||||
|
delta,
|
||||||
|
nextElements,
|
||||||
|
nextAppState,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
excalidrawAPI?.updateScene({
|
||||||
|
appState: {
|
||||||
|
...nextAppState,
|
||||||
|
viewModeEnabled: value !== acknowledgedDeltas.length,
|
||||||
|
},
|
||||||
|
elements: Array.from(nextElements.values()),
|
||||||
|
captureUpdate: CaptureUpdateAction.NEVER,
|
||||||
|
});
|
||||||
|
},
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
style={{ height: "100%" }}
|
style={{ height: "100%" }}
|
||||||
@@ -806,9 +920,45 @@ const ExcalidrawWrapper = () => {
|
|||||||
"is-collaborating": isCollaborating,
|
"is-collaborating": isCollaborating,
|
||||||
})}
|
})}
|
||||||
>
|
>
|
||||||
|
<Slider
|
||||||
|
style={{
|
||||||
|
position: "fixed",
|
||||||
|
bottom: "25px",
|
||||||
|
zIndex: 999,
|
||||||
|
width: "60%",
|
||||||
|
left: "25%",
|
||||||
|
}}
|
||||||
|
step={1}
|
||||||
|
min={0}
|
||||||
|
max={acknowledgedDeltas.length}
|
||||||
|
value={sliderVersion}
|
||||||
|
onChange={(value) => {
|
||||||
|
const nextSliderVersion = value as number;
|
||||||
|
// CFDO: in safari the whole canvas gets selected when dragging
|
||||||
|
if (nextSliderVersion !== acknowledgedDeltas.length) {
|
||||||
|
// don't listen to updates in the detached mode
|
||||||
|
syncAPI?.disconnect();
|
||||||
|
} else {
|
||||||
|
// reconnect once we're back to the latest version
|
||||||
|
syncAPI?.connect();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (nextSliderVersion === sliderVersion) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
debouncedTimeTravel(
|
||||||
|
nextSliderVersion,
|
||||||
|
nextSliderVersion < sliderVersion ? "backward" : "forward",
|
||||||
|
);
|
||||||
|
|
||||||
|
setSliderVersion(nextSliderVersion);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<Excalidraw
|
<Excalidraw
|
||||||
excalidrawAPI={excalidrawRefCallback}
|
excalidrawAPI={excalidrawRefCallback}
|
||||||
onChange={onChange}
|
onChange={onChange}
|
||||||
|
onIncrement={onIncrement}
|
||||||
initialData={initialStatePromiseRef.current.promise}
|
initialData={initialStatePromiseRef.current.promise}
|
||||||
isCollaborating={isCollaborating}
|
isCollaborating={isCollaborating}
|
||||||
onPointerUpdate={collabAPI?.onPointerUpdate}
|
onPointerUpdate={collabAPI?.onPointerUpdate}
|
||||||
@@ -854,22 +1004,14 @@ const ExcalidrawWrapper = () => {
|
|||||||
if (isMobile || !collabAPI || isCollabDisabled) {
|
if (isMobile || !collabAPI || isCollabDisabled) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="excalidraw-ui-top-right">
|
<div className="top-right-ui">
|
||||||
{excalidrawAPI?.getEditorInterface().formFactor === "desktop" && (
|
|
||||||
<ExcalidrawPlusPromoBanner
|
|
||||||
isSignedIn={isExcalidrawPlusSignedUser}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{collabError.message && <CollabError collabError={collabError} />}
|
{collabError.message && <CollabError collabError={collabError} />}
|
||||||
<LiveCollaborationTrigger
|
<LiveCollaborationTrigger
|
||||||
isCollaborating={isCollaborating}
|
isCollaborating={isCollaborating}
|
||||||
onSelect={() =>
|
onSelect={() =>
|
||||||
setShareDialogState({ isOpen: true, type: "share" })
|
setShareDialogState({ isOpen: true, type: "share" })
|
||||||
}
|
}
|
||||||
editorInterface={editorInterface}
|
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
@@ -895,7 +1037,6 @@ const ExcalidrawWrapper = () => {
|
|||||||
/>
|
/>
|
||||||
<OverwriteConfirmDialog>
|
<OverwriteConfirmDialog>
|
||||||
<OverwriteConfirmDialog.Actions.ExportToImage />
|
<OverwriteConfirmDialog.Actions.ExportToImage />
|
||||||
<OverwriteConfirmDialog.Actions.SaveToDisk />
|
|
||||||
{excalidrawAPI && (
|
{excalidrawAPI && (
|
||||||
<OverwriteConfirmDialog.Action
|
<OverwriteConfirmDialog.Action
|
||||||
title={t("overwriteConfirm.action.excalidrawPlus.title")}
|
title={t("overwriteConfirm.action.excalidrawPlus.title")}
|
||||||
@@ -918,15 +1059,10 @@ const ExcalidrawWrapper = () => {
|
|||||||
|
|
||||||
<TTDDialogTrigger />
|
<TTDDialogTrigger />
|
||||||
{isCollaborating && isOffline && (
|
{isCollaborating && isOffline && (
|
||||||
<div className="alertalert--warning">
|
<div className="collab-offline-warning">
|
||||||
{t("alerts.collabOfflineWarning")}
|
{t("alerts.collabOfflineWarning")}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{localStorageQuotaExceeded && (
|
|
||||||
<div className="alert alert--danger">
|
|
||||||
{t("alerts.localStorageQuotaExceeded")}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
{latestShareableLink && (
|
{latestShareableLink && (
|
||||||
<ShareableLinkDialog
|
<ShareableLinkDialog
|
||||||
link={latestShareableLink}
|
link={latestShareableLink}
|
||||||
@@ -955,8 +1091,6 @@ const ExcalidrawWrapper = () => {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<AppSidebar />
|
|
||||||
|
|
||||||
{errorMessage && (
|
{errorMessage && (
|
||||||
<ErrorDialog onClose={() => setErrorMessage("")}>
|
<ErrorDialog onClose={() => setErrorMessage("")}>
|
||||||
{errorMessage}
|
{errorMessage}
|
||||||
|
|||||||
@@ -8,8 +8,7 @@ export const SYNC_BROWSER_TABS_TIMEOUT = 50;
|
|||||||
export const CURSOR_SYNC_TIMEOUT = 33; // ~30fps
|
export const CURSOR_SYNC_TIMEOUT = 33; // ~30fps
|
||||||
export const DELETED_ELEMENT_TIMEOUT = 24 * 60 * 60 * 1000; // 1 day
|
export const DELETED_ELEMENT_TIMEOUT = 24 * 60 * 60 * 1000; // 1 day
|
||||||
|
|
||||||
// should be aligned with MAX_ALLOWED_FILE_BYTES
|
export const FILE_UPLOAD_MAX_BYTES = 3 * 1024 * 1024; // 3 MiB
|
||||||
export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024; // 4 MiB
|
|
||||||
// 1 year (https://stackoverflow.com/a/25201898/927631)
|
// 1 year (https://stackoverflow.com/a/25201898/927631)
|
||||||
export const FILE_CACHE_MAX_AGE_SEC = 31536000;
|
export const FILE_CACHE_MAX_AGE_SEC = 31536000;
|
||||||
|
|
||||||
@@ -46,6 +45,7 @@ export const STORAGE_KEYS = {
|
|||||||
VERSION_FILES: "version-files",
|
VERSION_FILES: "version-files",
|
||||||
|
|
||||||
IDB_LIBRARY: "excalidraw-library",
|
IDB_LIBRARY: "excalidraw-library",
|
||||||
|
IDB_SYNC: "excalidraw-sync",
|
||||||
|
|
||||||
// do not use apart from migrations
|
// do not use apart from migrations
|
||||||
__LEGACY_LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
__LEGACY_LOCAL_STORAGE_LIBRARY: "excalidraw-library",
|
||||||
|
|||||||
@@ -19,9 +19,12 @@ import {
|
|||||||
throttleRAF,
|
throttleRAF,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
import { decryptData } from "@excalidraw/excalidraw/data/encryption";
|
import { decryptData } from "@excalidraw/excalidraw/data/encryption";
|
||||||
import { getVisibleSceneBounds } from "@excalidraw/element";
|
import { getVisibleSceneBounds } from "@excalidraw/element/bounds";
|
||||||
import { newElementWith } from "@excalidraw/element";
|
import { newElementWith } from "@excalidraw/element/mutateElement";
|
||||||
import { isImageElement, isInitializedImageElement } from "@excalidraw/element";
|
import {
|
||||||
|
isImageElement,
|
||||||
|
isInitializedImageElement,
|
||||||
|
} from "@excalidraw/element/typeChecks";
|
||||||
import { AbortError } from "@excalidraw/excalidraw/errors";
|
import { AbortError } from "@excalidraw/excalidraw/errors";
|
||||||
import { t } from "@excalidraw/excalidraw/i18n";
|
import { t } from "@excalidraw/excalidraw/i18n";
|
||||||
import { withBatchedUpdates } from "@excalidraw/excalidraw/reactUtils";
|
import { withBatchedUpdates } from "@excalidraw/excalidraw/reactUtils";
|
||||||
@@ -70,7 +73,7 @@ import {
|
|||||||
FileManager,
|
FileManager,
|
||||||
updateStaleImageStatuses,
|
updateStaleImageStatuses,
|
||||||
} from "../data/FileManager";
|
} from "../data/FileManager";
|
||||||
import { LocalData } from "../data/LocalData";
|
import { LocalData, SyncIndexedDBAdapter } from "../data/LocalData";
|
||||||
import {
|
import {
|
||||||
isSavedToFirebase,
|
isSavedToFirebase,
|
||||||
loadFilesFromFirebase,
|
loadFilesFromFirebase,
|
||||||
@@ -92,6 +95,7 @@ import type {
|
|||||||
SyncableExcalidrawElement,
|
SyncableExcalidrawElement,
|
||||||
} from "../data";
|
} from "../data";
|
||||||
|
|
||||||
|
export const syncApiAtom = atom<SyncClient | null>(null);
|
||||||
export const collabAPIAtom = atom<CollabAPI | null>(null);
|
export const collabAPIAtom = atom<CollabAPI | null>(null);
|
||||||
export const isCollaboratingAtom = atom(false);
|
export const isCollaboratingAtom = atom(false);
|
||||||
export const isOfflineAtom = atom(false);
|
export const isOfflineAtom = atom(false);
|
||||||
@@ -238,6 +242,12 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
|
|
||||||
appJotaiStore.set(collabAPIAtom, collabAPI);
|
appJotaiStore.set(collabAPIAtom, collabAPI);
|
||||||
|
|
||||||
|
SyncClient.create(this.excalidrawAPI, SyncIndexedDBAdapter).then(
|
||||||
|
(syncAPI) => {
|
||||||
|
appJotaiStore.set(syncApiAtom, syncAPI);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
if (isTestEnv() || isDevEnv()) {
|
if (isTestEnv() || isDevEnv()) {
|
||||||
window.collab = window.collab || ({} as Window["collab"]);
|
window.collab = window.collab || ({} as Window["collab"]);
|
||||||
Object.defineProperties(window, {
|
Object.defineProperties(window, {
|
||||||
@@ -271,6 +281,8 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
window.clearTimeout(this.idleTimeoutId);
|
window.clearTimeout(this.idleTimeoutId);
|
||||||
this.idleTimeoutId = null;
|
this.idleTimeoutId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
appJotaiStore.get(syncApiAtom)?.disconnect();
|
||||||
this.onUmmount?.();
|
this.onUmmount?.();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -441,7 +453,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
};
|
};
|
||||||
|
|
||||||
private decryptPayload = async (
|
private decryptPayload = async (
|
||||||
iv: Uint8Array<ArrayBuffer>,
|
iv: Uint8Array,
|
||||||
encryptedData: ArrayBuffer,
|
encryptedData: ArrayBuffer,
|
||||||
decryptionKey: string,
|
decryptionKey: string,
|
||||||
): Promise<ValueOf<SocketUpdateDataSource>> => {
|
): Promise<ValueOf<SocketUpdateDataSource>> => {
|
||||||
@@ -530,10 +542,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (existingRoomLinkData) {
|
if (!existingRoomLinkData) {
|
||||||
// when joining existing room, don't merge it with current scene data
|
|
||||||
this.excalidrawAPI.resetScene();
|
|
||||||
} else {
|
|
||||||
const elements = this.excalidrawAPI.getSceneElements().map((element) => {
|
const elements = this.excalidrawAPI.getSceneElements().map((element) => {
|
||||||
if (isImageElement(element) && element.status === "saved") {
|
if (isImageElement(element) && element.status === "saved") {
|
||||||
return newElementWith(element, { status: "pending" });
|
return newElementWith(element, { status: "pending" });
|
||||||
@@ -562,7 +571,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
// All socket listeners are moving to Portal
|
// All socket listeners are moving to Portal
|
||||||
this.portal.socket.on(
|
this.portal.socket.on(
|
||||||
"client-broadcast",
|
"client-broadcast",
|
||||||
async (encryptedData: ArrayBuffer, iv: Uint8Array<ArrayBuffer>) => {
|
async (encryptedData: ArrayBuffer, iv: Uint8Array) => {
|
||||||
if (!this.portal.roomKey) {
|
if (!this.portal.roomKey) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -746,10 +755,7 @@ class Collab extends PureComponent<CollabProps, CollabState> {
|
|||||||
): ReconciledExcalidrawElement[] => {
|
): ReconciledExcalidrawElement[] => {
|
||||||
const localElements = this.getSceneElementsIncludingDeleted();
|
const localElements = this.getSceneElementsIncludingDeleted();
|
||||||
const appState = this.excalidrawAPI.getAppState();
|
const appState = this.excalidrawAPI.getAppState();
|
||||||
const restoredRemoteElements = restoreElements(
|
const restoredRemoteElements = restoreElements(remoteElements, null);
|
||||||
remoteElements,
|
|
||||||
this.excalidrawAPI.getSceneElementsMapIncludingDeleted(),
|
|
||||||
);
|
|
||||||
const reconciledElements = reconcileElements(
|
const reconciledElements = reconcileElements(
|
||||||
localElements,
|
localElements,
|
||||||
restoredRemoteElements as RemoteExcalidrawElement[],
|
restoredRemoteElements as RemoteExcalidrawElement[],
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { CaptureUpdateAction } from "@excalidraw/excalidraw";
|
import { CaptureUpdateAction } from "@excalidraw/excalidraw";
|
||||||
import { trackEvent } from "@excalidraw/excalidraw/analytics";
|
import { trackEvent } from "@excalidraw/excalidraw/analytics";
|
||||||
import { encryptData } from "@excalidraw/excalidraw/data/encryption";
|
import { encryptData } from "@excalidraw/excalidraw/data/encryption";
|
||||||
import { newElementWith } from "@excalidraw/element";
|
import { newElementWith } from "@excalidraw/element/mutateElement";
|
||||||
import throttle from "lodash.throttle";
|
import throttle from "lodash.throttle";
|
||||||
|
|
||||||
import type { UserIdleState } from "@excalidraw/common";
|
import type { UserIdleState } from "@excalidraw/common";
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export const AIComponents = ({
|
|||||||
</br>
|
</br>
|
||||||
<div>You can also try <a href="${
|
<div>You can also try <a href="${
|
||||||
import.meta.env.VITE_APP_PLUS_LP
|
import.meta.env.VITE_APP_PLUS_LP
|
||||||
}/plus?utm_source=excalidraw&utm_medium=app&utm_content=d2c" target="_blank" rel="noopener">Excalidraw+</a> to get more requests.</div>
|
}/plus?utm_source=excalidraw&utm_medium=app&utm_content=d2c" target="_blank" rel="noreferrer noopener">Excalidraw+</a> to get more requests.</div>
|
||||||
</div>
|
</div>
|
||||||
</body>
|
</body>
|
||||||
</html>`,
|
</html>`,
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import { isExcalidrawPlusSignedUser } from "../app_constants";
|
|||||||
|
|
||||||
import { DebugFooter, isVisualDebuggerEnabled } from "./DebugCanvas";
|
import { DebugFooter, isVisualDebuggerEnabled } from "./DebugCanvas";
|
||||||
import { EncryptedIcon } from "./EncryptedIcon";
|
import { EncryptedIcon } from "./EncryptedIcon";
|
||||||
|
import { ExcalidrawPlusAppLink } from "./ExcalidrawPlusAppLink";
|
||||||
|
|
||||||
export const AppFooter = React.memo(
|
export const AppFooter = React.memo(
|
||||||
({ onChange }: { onChange: () => void }) => {
|
({ onChange }: { onChange: () => void }) => {
|
||||||
@@ -18,7 +19,11 @@ export const AppFooter = React.memo(
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{isVisualDebuggerEnabled() && <DebugFooter onChange={onChange} />}
|
{isVisualDebuggerEnabled() && <DebugFooter onChange={onChange} />}
|
||||||
{!isExcalidrawPlusSignedUser && <EncryptedIcon />}
|
{isExcalidrawPlusSignedUser ? (
|
||||||
|
<ExcalidrawPlusAppLink />
|
||||||
|
) : (
|
||||||
|
<EncryptedIcon />
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</Footer>
|
</Footer>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,36 +0,0 @@
|
|||||||
.excalidraw {
|
|
||||||
.app-sidebar-promo-container {
|
|
||||||
padding: 0.75rem;
|
|
||||||
display: flex;
|
|
||||||
flex-direction: column;
|
|
||||||
text-align: center;
|
|
||||||
gap: 1rem;
|
|
||||||
flex: 1 1 auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.app-sidebar-promo-image {
|
|
||||||
margin: 1rem 0;
|
|
||||||
|
|
||||||
height: 16.25rem;
|
|
||||||
background-size: contain;
|
|
||||||
background-position: center;
|
|
||||||
background-repeat: no-repeat;
|
|
||||||
|
|
||||||
background-image: radial-gradient(
|
|
||||||
circle,
|
|
||||||
transparent 60%,
|
|
||||||
var(--sidebar-bg-color) 100%
|
|
||||||
),
|
|
||||||
var(--image-source);
|
|
||||||
|
|
||||||
display: flex;
|
|
||||||
}
|
|
||||||
|
|
||||||
.app-sidebar-promo-text {
|
|
||||||
padding: 0 2rem;
|
|
||||||
}
|
|
||||||
|
|
||||||
.link-button {
|
|
||||||
margin: 0 auto;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import { DefaultSidebar, Sidebar, THEME } from "@excalidraw/excalidraw";
|
|
||||||
import {
|
|
||||||
messageCircleIcon,
|
|
||||||
presentationIcon,
|
|
||||||
} from "@excalidraw/excalidraw/components/icons";
|
|
||||||
import { LinkButton } from "@excalidraw/excalidraw/components/LinkButton";
|
|
||||||
import { useUIAppState } from "@excalidraw/excalidraw/context/ui-appState";
|
|
||||||
|
|
||||||
import "./AppSidebar.scss";
|
|
||||||
|
|
||||||
export const AppSidebar = () => {
|
|
||||||
const { theme, openSidebar } = useUIAppState();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<DefaultSidebar>
|
|
||||||
<DefaultSidebar.TabTriggers>
|
|
||||||
<Sidebar.TabTrigger
|
|
||||||
tab="comments"
|
|
||||||
style={{ opacity: openSidebar?.tab === "comments" ? 1 : 0.4 }}
|
|
||||||
>
|
|
||||||
{messageCircleIcon}
|
|
||||||
</Sidebar.TabTrigger>
|
|
||||||
<Sidebar.TabTrigger
|
|
||||||
tab="presentation"
|
|
||||||
style={{ opacity: openSidebar?.tab === "presentation" ? 1 : 0.4 }}
|
|
||||||
>
|
|
||||||
{presentationIcon}
|
|
||||||
</Sidebar.TabTrigger>
|
|
||||||
</DefaultSidebar.TabTriggers>
|
|
||||||
<Sidebar.Tab tab="comments">
|
|
||||||
<div className="app-sidebar-promo-container">
|
|
||||||
<div
|
|
||||||
className="app-sidebar-promo-image"
|
|
||||||
style={{
|
|
||||||
["--image-source" as any]: `url(/oss_promo_comments_${
|
|
||||||
theme === THEME.DARK ? "dark" : "light"
|
|
||||||
}.jpg)`,
|
|
||||||
opacity: 0.7,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div className="app-sidebar-promo-text">
|
|
||||||
Make comments with Excalidraw+
|
|
||||||
</div>
|
|
||||||
<LinkButton
|
|
||||||
href={`${
|
|
||||||
import.meta.env.VITE_APP_PLUS_LP
|
|
||||||
}/plus?utm_source=excalidraw&utm_medium=app&utm_content=comments_promo#excalidraw-redirect`}
|
|
||||||
>
|
|
||||||
Sign up now
|
|
||||||
</LinkButton>
|
|
||||||
</div>
|
|
||||||
</Sidebar.Tab>
|
|
||||||
<Sidebar.Tab tab="presentation" className="px-3">
|
|
||||||
<div className="app-sidebar-promo-container">
|
|
||||||
<div
|
|
||||||
className="app-sidebar-promo-image"
|
|
||||||
style={{
|
|
||||||
["--image-source" as any]: `url(/oss_promo_presentations_${
|
|
||||||
theme === THEME.DARK ? "dark" : "light"
|
|
||||||
}.svg)`,
|
|
||||||
backgroundSize: "60%",
|
|
||||||
opacity: 0.4,
|
|
||||||
}}
|
|
||||||
/>
|
|
||||||
<div className="app-sidebar-promo-text">
|
|
||||||
Create presentations with Excalidraw+
|
|
||||||
</div>
|
|
||||||
<LinkButton
|
|
||||||
href={`${
|
|
||||||
import.meta.env.VITE_APP_PLUS_LP
|
|
||||||
}/plus?utm_source=excalidraw&utm_medium=app&utm_content=presentations_promo#excalidraw-redirect`}
|
|
||||||
>
|
|
||||||
Sign up now
|
|
||||||
</LinkButton>
|
|
||||||
</div>
|
|
||||||
</Sidebar.Tab>
|
|
||||||
</DefaultSidebar>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -8,14 +8,8 @@ import {
|
|||||||
getNormalizedCanvasDimensions,
|
getNormalizedCanvasDimensions,
|
||||||
} from "@excalidraw/excalidraw/renderer/helpers";
|
} from "@excalidraw/excalidraw/renderer/helpers";
|
||||||
import { type AppState } from "@excalidraw/excalidraw/types";
|
import { type AppState } from "@excalidraw/excalidraw/types";
|
||||||
import { arrayToMap, throttleRAF } from "@excalidraw/common";
|
import { throttleRAF } from "@excalidraw/common";
|
||||||
import { useCallback } from "react";
|
import { useCallback, useImperativeHandle, useRef } from "react";
|
||||||
|
|
||||||
import {
|
|
||||||
getGlobalFixedPointForBindableElement,
|
|
||||||
isArrowElement,
|
|
||||||
isBindableElement,
|
|
||||||
} from "@excalidraw/element";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
isLineSegment,
|
isLineSegment,
|
||||||
@@ -24,17 +18,9 @@ import {
|
|||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
import { isCurve } from "@excalidraw/math/curve";
|
import { isCurve } from "@excalidraw/math/curve";
|
||||||
|
|
||||||
import React from "react";
|
import type { DebugElement } from "@excalidraw/excalidraw/visualdebug";
|
||||||
|
|
||||||
import type { Curve } from "@excalidraw/math";
|
import type { Curve } from "@excalidraw/math";
|
||||||
import type { DebugElement } from "@excalidraw/common";
|
|
||||||
import type {
|
|
||||||
ElementsMap,
|
|
||||||
ExcalidrawArrowElement,
|
|
||||||
ExcalidrawBindableElement,
|
|
||||||
FixedPointBinding,
|
|
||||||
OrderedExcalidrawElement,
|
|
||||||
} from "@excalidraw/element/types";
|
|
||||||
|
|
||||||
import { STORAGE_KEYS } from "../app_constants";
|
import { STORAGE_KEYS } from "../app_constants";
|
||||||
|
|
||||||
@@ -87,176 +73,6 @@ const renderOrigin = (context: CanvasRenderingContext2D, zoom: number) => {
|
|||||||
context.save();
|
context.save();
|
||||||
};
|
};
|
||||||
|
|
||||||
const _renderBinding = (
|
|
||||||
context: CanvasRenderingContext2D,
|
|
||||||
binding: FixedPointBinding,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
zoom: number,
|
|
||||||
width: number,
|
|
||||||
height: number,
|
|
||||||
color: string,
|
|
||||||
) => {
|
|
||||||
if (!binding.fixedPoint) {
|
|
||||||
console.warn("Binding must have a fixedPoint");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const bindable = elementsMap.get(
|
|
||||||
binding.elementId,
|
|
||||||
) as ExcalidrawBindableElement;
|
|
||||||
const [x, y] = getGlobalFixedPointForBindableElement(
|
|
||||||
binding.fixedPoint,
|
|
||||||
bindable,
|
|
||||||
elementsMap,
|
|
||||||
);
|
|
||||||
|
|
||||||
context.save();
|
|
||||||
context.strokeStyle = color;
|
|
||||||
context.lineWidth = 1;
|
|
||||||
context.beginPath();
|
|
||||||
context.moveTo(x * zoom, y * zoom);
|
|
||||||
context.bezierCurveTo(
|
|
||||||
x * zoom - width,
|
|
||||||
y * zoom - height,
|
|
||||||
x * zoom - width,
|
|
||||||
y * zoom + height,
|
|
||||||
x * zoom,
|
|
||||||
y * zoom,
|
|
||||||
);
|
|
||||||
context.stroke();
|
|
||||||
context.restore();
|
|
||||||
};
|
|
||||||
|
|
||||||
const _renderBindableBinding = (
|
|
||||||
binding: FixedPointBinding,
|
|
||||||
context: CanvasRenderingContext2D,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
zoom: number,
|
|
||||||
width: number,
|
|
||||||
height: number,
|
|
||||||
color: string,
|
|
||||||
) => {
|
|
||||||
const bindable = elementsMap.get(
|
|
||||||
binding.elementId,
|
|
||||||
) as ExcalidrawBindableElement;
|
|
||||||
if (!binding.fixedPoint) {
|
|
||||||
console.warn("Binding must have a fixedPoint");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const [x, y] = getGlobalFixedPointForBindableElement(
|
|
||||||
binding.fixedPoint,
|
|
||||||
bindable,
|
|
||||||
elementsMap,
|
|
||||||
);
|
|
||||||
|
|
||||||
context.save();
|
|
||||||
context.strokeStyle = color;
|
|
||||||
context.lineWidth = 1;
|
|
||||||
context.beginPath();
|
|
||||||
context.moveTo(x * zoom, y * zoom);
|
|
||||||
context.bezierCurveTo(
|
|
||||||
x * zoom + width,
|
|
||||||
y * zoom + height,
|
|
||||||
x * zoom + width,
|
|
||||||
y * zoom - height,
|
|
||||||
x * zoom,
|
|
||||||
y * zoom,
|
|
||||||
);
|
|
||||||
context.stroke();
|
|
||||||
context.restore();
|
|
||||||
};
|
|
||||||
|
|
||||||
const renderBindings = (
|
|
||||||
context: CanvasRenderingContext2D,
|
|
||||||
elements: readonly OrderedExcalidrawElement[],
|
|
||||||
zoom: number,
|
|
||||||
) => {
|
|
||||||
const elementsMap = arrayToMap(elements);
|
|
||||||
const dim = 16;
|
|
||||||
elements.forEach((element) => {
|
|
||||||
if (element.isDeleted) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isArrowElement(element)) {
|
|
||||||
if (element.startBinding) {
|
|
||||||
if (
|
|
||||||
!elementsMap
|
|
||||||
.get(element.startBinding.elementId)
|
|
||||||
?.boundElements?.find((e) => e.id === element.id)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
_renderBinding(
|
|
||||||
context,
|
|
||||||
element.startBinding,
|
|
||||||
elementsMap,
|
|
||||||
zoom,
|
|
||||||
dim,
|
|
||||||
dim,
|
|
||||||
element.startBinding?.mode === "orbit" ? "red" : "black",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (element.endBinding) {
|
|
||||||
if (
|
|
||||||
!elementsMap
|
|
||||||
.get(element.endBinding.elementId)
|
|
||||||
?.boundElements?.find((e) => e.id === element.id)
|
|
||||||
) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
_renderBinding(
|
|
||||||
context,
|
|
||||||
element.endBinding,
|
|
||||||
elementsMap,
|
|
||||||
zoom,
|
|
||||||
dim,
|
|
||||||
dim,
|
|
||||||
element.endBinding?.mode === "orbit" ? "red" : "black",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isBindableElement(element) && element.boundElements?.length) {
|
|
||||||
element.boundElements.forEach((boundElement) => {
|
|
||||||
if (boundElement.type !== "arrow") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const arrow = elementsMap.get(
|
|
||||||
boundElement.id,
|
|
||||||
) as ExcalidrawArrowElement;
|
|
||||||
|
|
||||||
if (arrow && arrow.startBinding?.elementId === element.id) {
|
|
||||||
_renderBindableBinding(
|
|
||||||
arrow.startBinding,
|
|
||||||
context,
|
|
||||||
elementsMap,
|
|
||||||
zoom,
|
|
||||||
dim,
|
|
||||||
dim,
|
|
||||||
"green",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (arrow && arrow.endBinding?.elementId === element.id) {
|
|
||||||
_renderBindableBinding(
|
|
||||||
arrow.endBinding,
|
|
||||||
context,
|
|
||||||
elementsMap,
|
|
||||||
zoom,
|
|
||||||
dim,
|
|
||||||
dim,
|
|
||||||
"green",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const render = (
|
const render = (
|
||||||
frame: DebugElement[],
|
frame: DebugElement[],
|
||||||
context: CanvasRenderingContext2D,
|
context: CanvasRenderingContext2D,
|
||||||
@@ -289,14 +105,18 @@ const render = (
|
|||||||
const _debugRenderer = (
|
const _debugRenderer = (
|
||||||
canvas: HTMLCanvasElement,
|
canvas: HTMLCanvasElement,
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
elements: readonly OrderedExcalidrawElement[],
|
|
||||||
scale: number,
|
scale: number,
|
||||||
|
refresh: () => void,
|
||||||
) => {
|
) => {
|
||||||
const [normalizedWidth, normalizedHeight] = getNormalizedCanvasDimensions(
|
const [normalizedWidth, normalizedHeight] = getNormalizedCanvasDimensions(
|
||||||
canvas,
|
canvas,
|
||||||
scale,
|
scale,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
if (appState.height !== canvas.height || appState.width !== canvas.width) {
|
||||||
|
refresh();
|
||||||
|
}
|
||||||
|
|
||||||
const context = bootstrapCanvas({
|
const context = bootstrapCanvas({
|
||||||
canvas,
|
canvas,
|
||||||
scale,
|
scale,
|
||||||
@@ -313,7 +133,6 @@ const _debugRenderer = (
|
|||||||
);
|
);
|
||||||
|
|
||||||
renderOrigin(context, appState.zoom.value);
|
renderOrigin(context, appState.zoom.value);
|
||||||
renderBindings(context, elements, appState.zoom.value);
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
window.visualDebug?.currentFrame &&
|
window.visualDebug?.currentFrame &&
|
||||||
@@ -365,10 +184,10 @@ export const debugRenderer = throttleRAF(
|
|||||||
(
|
(
|
||||||
canvas: HTMLCanvasElement,
|
canvas: HTMLCanvasElement,
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
elements: readonly OrderedExcalidrawElement[],
|
|
||||||
scale: number,
|
scale: number,
|
||||||
|
refresh: () => void,
|
||||||
) => {
|
) => {
|
||||||
_debugRenderer(canvas, appState, elements, scale);
|
_debugRenderer(canvas, appState, scale, refresh);
|
||||||
},
|
},
|
||||||
{ trailing: true },
|
{ trailing: true },
|
||||||
);
|
);
|
||||||
@@ -495,29 +314,35 @@ export const DebugFooter = ({ onChange }: { onChange: () => void }) => {
|
|||||||
interface DebugCanvasProps {
|
interface DebugCanvasProps {
|
||||||
appState: AppState;
|
appState: AppState;
|
||||||
scale: number;
|
scale: number;
|
||||||
|
ref?: React.Ref<HTMLCanvasElement>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DebugCanvas = React.forwardRef<HTMLCanvasElement, DebugCanvasProps>(
|
const DebugCanvas = ({ appState, scale, ref }: DebugCanvasProps) => {
|
||||||
({ appState, scale }, ref) => {
|
const { width, height } = appState;
|
||||||
const { width, height } = appState;
|
|
||||||
|
|
||||||
return (
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
<canvas
|
useImperativeHandle<HTMLCanvasElement | null, HTMLCanvasElement | null>(
|
||||||
style={{
|
ref,
|
||||||
width,
|
() => canvasRef.current,
|
||||||
height,
|
[canvasRef],
|
||||||
position: "absolute",
|
);
|
||||||
zIndex: 2,
|
|
||||||
pointerEvents: "none",
|
return (
|
||||||
}}
|
<canvas
|
||||||
width={width * scale}
|
style={{
|
||||||
height={height * scale}
|
width,
|
||||||
ref={ref}
|
height,
|
||||||
>
|
position: "absolute",
|
||||||
Debug Canvas
|
zIndex: 2,
|
||||||
</canvas>
|
pointerEvents: "none",
|
||||||
);
|
}}
|
||||||
},
|
width={width * scale}
|
||||||
);
|
height={height * scale}
|
||||||
|
ref={canvasRef}
|
||||||
|
>
|
||||||
|
Debug Canvas
|
||||||
|
</canvas>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
export default DebugCanvas;
|
export default DebugCanvas;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export const EncryptedIcon = () => {
|
|||||||
className="encrypted-icon tooltip"
|
className="encrypted-icon tooltip"
|
||||||
href="https://plus.excalidraw.com/blog/end-to-end-encryption"
|
href="https://plus.excalidraw.com/blog/end-to-end-encryption"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener"
|
rel="noopener noreferrer"
|
||||||
aria-label={t("encrypted.link")}
|
aria-label={t("encrypted.link")}
|
||||||
>
|
>
|
||||||
<Tooltip label={t("encrypted.tooltip")} long={true}>
|
<Tooltip label={t("encrypted.tooltip")} long={true}>
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import { isExcalidrawPlusSignedUser } from "../app_constants";
|
||||||
|
|
||||||
|
export const ExcalidrawPlusAppLink = () => {
|
||||||
|
if (!isExcalidrawPlusSignedUser) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<a
|
||||||
|
href={`${
|
||||||
|
import.meta.env.VITE_APP_PLUS_APP
|
||||||
|
}?utm_source=excalidraw&utm_medium=app&utm_content=signedInUserRedirectButton#excalidraw-redirect`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noreferrer"
|
||||||
|
className="plus-button"
|
||||||
|
>
|
||||||
|
Go to Excalidraw+
|
||||||
|
</a>
|
||||||
|
);
|
||||||
|
};
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
export const ExcalidrawPlusPromoBanner = ({
|
|
||||||
isSignedIn,
|
|
||||||
}: {
|
|
||||||
isSignedIn: boolean;
|
|
||||||
}) => {
|
|
||||||
return (
|
|
||||||
<a
|
|
||||||
href={
|
|
||||||
isSignedIn
|
|
||||||
? import.meta.env.VITE_APP_PLUS_APP
|
|
||||||
: `${
|
|
||||||
import.meta.env.VITE_APP_PLUS_LP
|
|
||||||
}/plus?utm_source=excalidraw&utm_medium=app&utm_content=guestBanner#excalidraw-redirect`
|
|
||||||
}
|
|
||||||
target="_blank"
|
|
||||||
rel="noopener"
|
|
||||||
className="plus-banner"
|
|
||||||
>
|
|
||||||
Excalidraw+
|
|
||||||
</a>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
generateEncryptionKey,
|
generateEncryptionKey,
|
||||||
} from "@excalidraw/excalidraw/data/encryption";
|
} from "@excalidraw/excalidraw/data/encryption";
|
||||||
import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";
|
import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";
|
||||||
import { isInitializedImageElement } from "@excalidraw/element";
|
import { isInitializedImageElement } from "@excalidraw/element/typeChecks";
|
||||||
import { useI18n } from "@excalidraw/excalidraw/i18n";
|
import { useI18n } from "@excalidraw/excalidraw/i18n";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import { CaptureUpdateAction } from "@excalidraw/excalidraw";
|
import { CaptureUpdateAction } from "@excalidraw/excalidraw";
|
||||||
import { compressData } from "@excalidraw/excalidraw/data/encode";
|
import { compressData } from "@excalidraw/excalidraw/data/encode";
|
||||||
import { newElementWith } from "@excalidraw/element";
|
import { newElementWith } from "@excalidraw/element/mutateElement";
|
||||||
import { isInitializedImageElement } from "@excalidraw/element";
|
import { isInitializedImageElement } from "@excalidraw/element/typeChecks";
|
||||||
import { t } from "@excalidraw/excalidraw/i18n";
|
import { t } from "@excalidraw/excalidraw/i18n";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
DEFAULT_SIDEBAR,
|
DEFAULT_SIDEBAR,
|
||||||
debounce,
|
debounce,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
import { clearElementsForLocalStorage } from "@excalidraw/element";
|
||||||
import {
|
import {
|
||||||
createStore,
|
createStore,
|
||||||
entries,
|
entries,
|
||||||
@@ -26,8 +27,7 @@ import {
|
|||||||
get,
|
get,
|
||||||
} from "idb-keyval";
|
} from "idb-keyval";
|
||||||
|
|
||||||
import { appJotaiStore, atom } from "excalidraw-app/app-jotai";
|
import { StoreDelta } from "@excalidraw/excalidraw/store";
|
||||||
import { getNonDeletedElements } from "@excalidraw/element";
|
|
||||||
|
|
||||||
import type { LibraryPersistedData } from "@excalidraw/excalidraw/data/library";
|
import type { LibraryPersistedData } from "@excalidraw/excalidraw/data/library";
|
||||||
import type { ImportedDataState } from "@excalidraw/excalidraw/data/types";
|
import type { ImportedDataState } from "@excalidraw/excalidraw/data/types";
|
||||||
@@ -37,7 +37,7 @@ import type {
|
|||||||
BinaryFileData,
|
BinaryFileData,
|
||||||
BinaryFiles,
|
BinaryFiles,
|
||||||
} from "@excalidraw/excalidraw/types";
|
} from "@excalidraw/excalidraw/types";
|
||||||
import type { MaybePromise } from "@excalidraw/common/utility-types";
|
import type { DTO, MaybePromise } from "@excalidraw/common/utility-types";
|
||||||
|
|
||||||
import { SAVE_TO_LOCAL_STORAGE_TIMEOUT, STORAGE_KEYS } from "../app_constants";
|
import { SAVE_TO_LOCAL_STORAGE_TIMEOUT, STORAGE_KEYS } from "../app_constants";
|
||||||
|
|
||||||
@@ -47,8 +47,6 @@ import { updateBrowserStateVersion } from "./tabSync";
|
|||||||
|
|
||||||
const filesStore = createStore("files-db", "files-store");
|
const filesStore = createStore("files-db", "files-store");
|
||||||
|
|
||||||
export const localStorageQuotaExceededAtom = atom(false);
|
|
||||||
|
|
||||||
class LocalFileManager extends FileManager {
|
class LocalFileManager extends FileManager {
|
||||||
clearObsoleteFiles = async (opts: { currentFileIds: FileId[] }) => {
|
clearObsoleteFiles = async (opts: { currentFileIds: FileId[] }) => {
|
||||||
await entries(filesStore).then((entries) => {
|
await entries(filesStore).then((entries) => {
|
||||||
@@ -73,9 +71,6 @@ const saveDataStateToLocalStorage = (
|
|||||||
elements: readonly ExcalidrawElement[],
|
elements: readonly ExcalidrawElement[],
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
) => {
|
) => {
|
||||||
const localStorageQuotaExceeded = appJotaiStore.get(
|
|
||||||
localStorageQuotaExceededAtom,
|
|
||||||
);
|
|
||||||
try {
|
try {
|
||||||
const _appState = clearAppStateForLocalStorage(appState);
|
const _appState = clearAppStateForLocalStorage(appState);
|
||||||
|
|
||||||
@@ -88,29 +83,19 @@ const saveDataStateToLocalStorage = (
|
|||||||
|
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS,
|
STORAGE_KEYS.LOCAL_STORAGE_ELEMENTS,
|
||||||
JSON.stringify(getNonDeletedElements(elements)),
|
JSON.stringify(clearElementsForLocalStorage(elements)),
|
||||||
);
|
);
|
||||||
localStorage.setItem(
|
localStorage.setItem(
|
||||||
STORAGE_KEYS.LOCAL_STORAGE_APP_STATE,
|
STORAGE_KEYS.LOCAL_STORAGE_APP_STATE,
|
||||||
JSON.stringify(_appState),
|
JSON.stringify(_appState),
|
||||||
);
|
);
|
||||||
updateBrowserStateVersion(STORAGE_KEYS.VERSION_DATA_STATE);
|
updateBrowserStateVersion(STORAGE_KEYS.VERSION_DATA_STATE);
|
||||||
if (localStorageQuotaExceeded) {
|
|
||||||
appJotaiStore.set(localStorageQuotaExceededAtom, false);
|
|
||||||
}
|
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
// Unable to access window.localStorage
|
// Unable to access window.localStorage
|
||||||
console.error(error);
|
console.error(error);
|
||||||
if (isQuotaExceededError(error) && !localStorageQuotaExceeded) {
|
|
||||||
appJotaiStore.set(localStorageQuotaExceededAtom, true);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const isQuotaExceededError = (error: any) => {
|
|
||||||
return error instanceof DOMException && error.name === "QuotaExceededError";
|
|
||||||
};
|
|
||||||
|
|
||||||
type SavingLockTypes = "collaboration";
|
type SavingLockTypes = "collaboration";
|
||||||
|
|
||||||
export class LocalData {
|
export class LocalData {
|
||||||
@@ -121,13 +106,12 @@ export class LocalData {
|
|||||||
files: BinaryFiles,
|
files: BinaryFiles,
|
||||||
onFilesSaved: () => void,
|
onFilesSaved: () => void,
|
||||||
) => {
|
) => {
|
||||||
saveDataStateToLocalStorage(elements, appState);
|
// saveDataStateToLocalStorage(elements, appState);
|
||||||
|
// await this.fileStorage.saveFiles({
|
||||||
await this.fileStorage.saveFiles({
|
// elements,
|
||||||
elements,
|
// files,
|
||||||
files,
|
// });
|
||||||
});
|
// onFilesSaved();
|
||||||
onFilesSaved();
|
|
||||||
},
|
},
|
||||||
SAVE_TO_LOCAL_STORAGE_TIMEOUT,
|
SAVE_TO_LOCAL_STORAGE_TIMEOUT,
|
||||||
);
|
);
|
||||||
@@ -273,3 +257,60 @@ export class LibraryLocalStorageMigrationAdapter {
|
|||||||
localStorage.removeItem(STORAGE_KEYS.__LEGACY_LOCAL_STORAGE_LIBRARY);
|
localStorage.removeItem(STORAGE_KEYS.__LEGACY_LOCAL_STORAGE_LIBRARY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SyncDeltaPersistedData = DTO<StoreDelta>[];
|
||||||
|
|
||||||
|
type SyncMetaPersistedData = {
|
||||||
|
lastAcknowledgedVersion: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
export class SyncIndexedDBAdapter {
|
||||||
|
/** IndexedDB database and store name */
|
||||||
|
private static idb_name = STORAGE_KEYS.IDB_SYNC;
|
||||||
|
/** library data store keys */
|
||||||
|
private static deltasKey = "deltas";
|
||||||
|
private static metadataKey = "metadata";
|
||||||
|
|
||||||
|
private static store = createStore(
|
||||||
|
`${SyncIndexedDBAdapter.idb_name}-db`,
|
||||||
|
`${SyncIndexedDBAdapter.idb_name}-store`,
|
||||||
|
);
|
||||||
|
|
||||||
|
static async loadDeltas() {
|
||||||
|
const deltas = await get<SyncDeltaPersistedData>(
|
||||||
|
SyncIndexedDBAdapter.deltasKey,
|
||||||
|
SyncIndexedDBAdapter.store,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (deltas?.length) {
|
||||||
|
return deltas.map((storeDeltaDTO) => StoreDelta.restore(storeDeltaDTO));
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async saveDeltas(data: SyncDeltaPersistedData): Promise<void> {
|
||||||
|
return set(
|
||||||
|
SyncIndexedDBAdapter.deltasKey,
|
||||||
|
data,
|
||||||
|
SyncIndexedDBAdapter.store,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
static async loadMetadata() {
|
||||||
|
const metadata = await get<SyncMetaPersistedData>(
|
||||||
|
SyncIndexedDBAdapter.metadataKey,
|
||||||
|
SyncIndexedDBAdapter.store,
|
||||||
|
);
|
||||||
|
|
||||||
|
return metadata || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
static async saveMetadata(data: SyncMetaPersistedData): Promise<void> {
|
||||||
|
return set(
|
||||||
|
SyncIndexedDBAdapter.metadataKey,
|
||||||
|
data,
|
||||||
|
SyncIndexedDBAdapter.store,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -105,8 +105,8 @@ const decryptElements = async (
|
|||||||
data: FirebaseStoredScene,
|
data: FirebaseStoredScene,
|
||||||
roomKey: string,
|
roomKey: string,
|
||||||
): Promise<readonly ExcalidrawElement[]> => {
|
): Promise<readonly ExcalidrawElement[]> => {
|
||||||
const ciphertext = data.ciphertext.toUint8Array() as Uint8Array<ArrayBuffer>;
|
const ciphertext = data.ciphertext.toUint8Array();
|
||||||
const iv = data.iv.toUint8Array() as Uint8Array<ArrayBuffer>;
|
const iv = data.iv.toUint8Array();
|
||||||
|
|
||||||
const decrypted = await decryptData(iv, ciphertext, roomKey);
|
const decrypted = await decryptData(iv, ciphertext, roomKey);
|
||||||
const decodedData = new TextDecoder("utf-8").decode(
|
const decodedData = new TextDecoder("utf-8").decode(
|
||||||
@@ -259,9 +259,7 @@ export const loadFromFirebase = async (
|
|||||||
}
|
}
|
||||||
const storedScene = docSnap.data() as FirebaseStoredScene;
|
const storedScene = docSnap.data() as FirebaseStoredScene;
|
||||||
const elements = getSyncableElements(
|
const elements = getSyncableElements(
|
||||||
restoreElements(await decryptElements(storedScene, roomKey), null, {
|
restoreElements(await decryptElements(storedScene, roomKey), null),
|
||||||
deleteInvisibleElements: true,
|
|
||||||
}),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
if (socket) {
|
if (socket) {
|
||||||
|
|||||||
@@ -9,14 +9,14 @@ import {
|
|||||||
} from "@excalidraw/excalidraw/data/encryption";
|
} from "@excalidraw/excalidraw/data/encryption";
|
||||||
import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";
|
import { serializeAsJSON } from "@excalidraw/excalidraw/data/json";
|
||||||
import { restore } from "@excalidraw/excalidraw/data/restore";
|
import { restore } from "@excalidraw/excalidraw/data/restore";
|
||||||
import { isInvisiblySmallElement } from "@excalidraw/element";
|
import { isInvisiblySmallElement } from "@excalidraw/element/sizeHelpers";
|
||||||
import { isInitializedImageElement } from "@excalidraw/element";
|
import { isInitializedImageElement } from "@excalidraw/element/typeChecks";
|
||||||
import { t } from "@excalidraw/excalidraw/i18n";
|
import { t } from "@excalidraw/excalidraw/i18n";
|
||||||
import { bytesToHexString } from "@excalidraw/common";
|
import { bytesToHexString } from "@excalidraw/common";
|
||||||
|
|
||||||
import type { UserIdleState } from "@excalidraw/common";
|
import type { UserIdleState } from "@excalidraw/common";
|
||||||
import type { ImportedDataState } from "@excalidraw/excalidraw/data/types";
|
import type { ImportedDataState } from "@excalidraw/excalidraw/data/types";
|
||||||
import type { SceneBounds } from "@excalidraw/element";
|
import type { SceneBounds } from "@excalidraw/element/bounds";
|
||||||
import type {
|
import type {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
FileId,
|
FileId,
|
||||||
@@ -258,16 +258,11 @@ export const loadScene = async (
|
|||||||
await importFromBackend(id, privateKey),
|
await importFromBackend(id, privateKey),
|
||||||
localDataState?.appState,
|
localDataState?.appState,
|
||||||
localDataState?.elements,
|
localDataState?.elements,
|
||||||
{
|
{ repairBindings: true, refreshDimensions: false },
|
||||||
repairBindings: true,
|
|
||||||
refreshDimensions: false,
|
|
||||||
deleteInvisibleElements: true,
|
|
||||||
},
|
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
data = restore(localDataState || null, null, null, {
|
data = restore(localDataState || null, null, null, {
|
||||||
repairBindings: true,
|
repairBindings: true,
|
||||||
deleteInvisibleElements: true,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import {
|
|||||||
clearAppStateForLocalStorage,
|
clearAppStateForLocalStorage,
|
||||||
getDefaultAppState,
|
getDefaultAppState,
|
||||||
} from "@excalidraw/excalidraw/appState";
|
} from "@excalidraw/excalidraw/appState";
|
||||||
|
import { clearElementsForLocalStorage } from "@excalidraw/element";
|
||||||
|
|
||||||
import type { ExcalidrawElement } from "@excalidraw/element/types";
|
import type { ExcalidrawElement } from "@excalidraw/element/types";
|
||||||
import type { AppState } from "@excalidraw/excalidraw/types";
|
import type { AppState } from "@excalidraw/excalidraw/types";
|
||||||
@@ -49,7 +50,7 @@ export const importFromLocalStorage = () => {
|
|||||||
let elements: ExcalidrawElement[] = [];
|
let elements: ExcalidrawElement[] = [];
|
||||||
if (savedElements) {
|
if (savedElements) {
|
||||||
try {
|
try {
|
||||||
elements = JSON.parse(savedElements);
|
elements = clearElementsForLocalStorage(JSON.parse(savedElements));
|
||||||
} catch (error: any) {
|
} catch (error: any) {
|
||||||
console.error(error);
|
console.error(error);
|
||||||
// Do nothing because elements array is already empty
|
// Do nothing because elements array is already empty
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
<html lang="en">
|
<html lang="en">
|
||||||
<head>
|
<head>
|
||||||
<meta charset="utf-8" />
|
<meta charset="utf-8" />
|
||||||
<title>Excalidraw Whiteboard</title>
|
<title>Excalidraw | Hand-drawn look & feel • Collaborative • Secure</title>
|
||||||
<meta
|
<meta
|
||||||
name="viewport"
|
name="viewport"
|
||||||
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover, shrink-to-fit=no"
|
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no, viewport-fit=cover, shrink-to-fit=no"
|
||||||
@@ -14,7 +14,7 @@
|
|||||||
<!-- Primary Meta Tags -->
|
<!-- Primary Meta Tags -->
|
||||||
<meta
|
<meta
|
||||||
name="title"
|
name="title"
|
||||||
content="Free, collaborative whiteboard • Hand-drawn look & feel | Excalidraw"
|
content="Excalidraw — Collaborative whiteboarding made easy"
|
||||||
/>
|
/>
|
||||||
<meta
|
<meta
|
||||||
name="description"
|
name="description"
|
||||||
|
|||||||
+14
-27
@@ -1,5 +1,3 @@
|
|||||||
@import "../packages/excalidraw/css/variables.module.scss";
|
|
||||||
|
|
||||||
.excalidraw {
|
.excalidraw {
|
||||||
--color-primary-contrast-offset: #625ee0; // to offset Chubb illusion
|
--color-primary-contrast-offset: #625ee0; // to offset Chubb illusion
|
||||||
|
|
||||||
@@ -7,6 +5,12 @@
|
|||||||
--color-primary-contrast-offset: #726dff; // to offset Chubb illusion
|
--color-primary-contrast-offset: #726dff; // to offset Chubb illusion
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.top-right-ui {
|
||||||
|
display: flex;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: flex-start;
|
||||||
|
}
|
||||||
|
|
||||||
.footer-center {
|
.footer-center {
|
||||||
justify-content: flex-end;
|
justify-content: flex-end;
|
||||||
margin-top: auto;
|
margin-top: auto;
|
||||||
@@ -54,7 +58,7 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.alert {
|
.collab-offline-warning {
|
||||||
pointer-events: none;
|
pointer-events: none;
|
||||||
position: absolute;
|
position: absolute;
|
||||||
top: 6.5rem;
|
top: 6.5rem;
|
||||||
@@ -65,18 +69,10 @@
|
|||||||
text-align: center;
|
text-align: center;
|
||||||
line-height: 1.5;
|
line-height: 1.5;
|
||||||
border-radius: var(--border-radius-md);
|
border-radius: var(--border-radius-md);
|
||||||
|
background-color: var(--color-warning);
|
||||||
|
color: var(--color-text-warning);
|
||||||
z-index: 6;
|
z-index: 6;
|
||||||
white-space: pre;
|
white-space: pre;
|
||||||
|
|
||||||
&--warning {
|
|
||||||
background-color: var(--color-warning);
|
|
||||||
color: var(--color-text-warning);
|
|
||||||
}
|
|
||||||
|
|
||||||
&--danger {
|
|
||||||
background-color: var(--color-danger-dark);
|
|
||||||
color: var(--color-danger-text);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,31 +82,22 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
.plus-banner {
|
.plus-button {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
border: 1px solid var(--color-primary);
|
border: 1px solid var(--color-primary);
|
||||||
padding: 0.5rem 0.875rem;
|
padding: 0.5rem 0.75rem;
|
||||||
border-radius: var(--border-radius-lg);
|
border-radius: var(--border-radius-lg);
|
||||||
background-color: var(--island-bg-color);
|
background-color: var(--island-bg-color);
|
||||||
|
color: var(--color-primary) !important;
|
||||||
text-decoration: none !important;
|
text-decoration: none !important;
|
||||||
|
|
||||||
font-family: var(--ui-font);
|
font-size: 0.75rem;
|
||||||
font-size: 0.8333rem;
|
|
||||||
box-sizing: border-box;
|
box-sizing: border-box;
|
||||||
height: var(--lg-button-size);
|
height: var(--lg-button-size);
|
||||||
|
|
||||||
border: none;
|
|
||||||
box-shadow: 0 0 0 1px var(--color-surface-lowest);
|
|
||||||
background-color: var(--color-surface-low);
|
|
||||||
color: var(--button-color, var(--color-on-surface)) !important;
|
|
||||||
|
|
||||||
&:active {
|
|
||||||
box-shadow: 0 0 0 1px var(--color-brand-active);
|
|
||||||
}
|
|
||||||
|
|
||||||
&:hover {
|
&:hover {
|
||||||
background-color: var(--color-primary);
|
background-color: var(--color-primary);
|
||||||
color: white !important;
|
color: white !important;
|
||||||
@@ -122,7 +109,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.theme--dark {
|
.theme--dark {
|
||||||
.plus-banner {
|
.plus-button {
|
||||||
&:hover {
|
&:hover {
|
||||||
color: black !important;
|
color: black !important;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -23,7 +23,7 @@
|
|||||||
]
|
]
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.0.0"
|
"node": "18.0.0 - 22.x.x"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@excalidraw/random-username": "1.0.0",
|
"@excalidraw/random-username": "1.0.0",
|
||||||
@@ -33,6 +33,7 @@
|
|||||||
"i18next-browser-languagedetector": "6.1.4",
|
"i18next-browser-languagedetector": "6.1.4",
|
||||||
"idb-keyval": "6.0.3",
|
"idb-keyval": "6.0.3",
|
||||||
"jotai": "2.11.0",
|
"jotai": "2.11.0",
|
||||||
|
"rc-slider": "11.1.7",
|
||||||
"react": "19.0.0",
|
"react": "19.0.0",
|
||||||
"react-dom": "19.0.0",
|
"react-dom": "19.0.0",
|
||||||
"socket.io-client": "4.7.2",
|
"socket.io-client": "4.7.2",
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { getFeatureFlag } from "@excalidraw/common";
|
|
||||||
import * as Sentry from "@sentry/browser";
|
import * as Sentry from "@sentry/browser";
|
||||||
import callsites from "callsites";
|
import callsites from "callsites";
|
||||||
|
|
||||||
@@ -34,7 +33,6 @@ Sentry.init({
|
|||||||
Sentry.captureConsoleIntegration({
|
Sentry.captureConsoleIntegration({
|
||||||
levels: ["error"],
|
levels: ["error"],
|
||||||
}),
|
}),
|
||||||
Sentry.featureFlagsIntegration(),
|
|
||||||
],
|
],
|
||||||
beforeSend(event) {
|
beforeSend(event) {
|
||||||
if (event.request?.url) {
|
if (event.request?.url) {
|
||||||
@@ -81,14 +79,3 @@ Sentry.init({
|
|||||||
return event;
|
return event;
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const flagsIntegration =
|
|
||||||
Sentry.getClient()?.getIntegrationByName<Sentry.FeatureFlagsIntegration>(
|
|
||||||
"FeatureFlags",
|
|
||||||
);
|
|
||||||
if (flagsIntegration) {
|
|
||||||
flagsIntegration.addFeatureFlag(
|
|
||||||
"COMPLEX_BINDINGS",
|
|
||||||
getFeatureFlag("COMPLEX_BINDINGS"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -17,15 +17,30 @@ describe("Test MobileMenu", () => {
|
|||||||
|
|
||||||
beforeEach(async () => {
|
beforeEach(async () => {
|
||||||
await render(<ExcalidrawApp />);
|
await render(<ExcalidrawApp />);
|
||||||
h.app.refreshEditorInterface();
|
// @ts-ignore
|
||||||
|
h.app.refreshViewportBreakpoints();
|
||||||
|
// @ts-ignore
|
||||||
|
h.app.refreshEditorBreakpoints();
|
||||||
});
|
});
|
||||||
|
|
||||||
afterAll(() => {
|
afterAll(() => {
|
||||||
restoreOriginalGetBoundingClientRect();
|
restoreOriginalGetBoundingClientRect();
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should set editor interface correctly", () => {
|
it("should set device correctly", () => {
|
||||||
expect(h.app.editorInterface.formFactor).toBe("phone");
|
expect(h.app.device).toMatchInlineSnapshot(`
|
||||||
|
{
|
||||||
|
"editor": {
|
||||||
|
"canFitSidebar": false,
|
||||||
|
"isMobile": true,
|
||||||
|
},
|
||||||
|
"isTouchScreen": false,
|
||||||
|
"viewport": {
|
||||||
|
"isLandscape": false,
|
||||||
|
"isMobile": true,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it("should initialize with welcome screen and hide once user interacts", async () => {
|
it("should initialize with welcome screen and hide once user interacts", async () => {
|
||||||
|
|||||||
@@ -198,7 +198,7 @@ exports[`Test MobileMenu > should initialize with welcome screen and hide once u
|
|||||||
<a
|
<a
|
||||||
class="welcome-screen-menu-item "
|
class="welcome-screen-menu-item "
|
||||||
href="undefined/plus?utm_source=excalidraw&utm_medium=app&utm_content=welcomeScreenGuest"
|
href="undefined/plus?utm_source=excalidraw&utm_medium=app&utm_content=welcomeScreenGuest"
|
||||||
rel="noopener"
|
rel="noreferrer"
|
||||||
target="_blank"
|
target="_blank"
|
||||||
>
|
>
|
||||||
<div
|
<div
|
||||||
|
|||||||
@@ -3,15 +3,11 @@ import {
|
|||||||
createRedoAction,
|
createRedoAction,
|
||||||
createUndoAction,
|
createUndoAction,
|
||||||
} from "@excalidraw/excalidraw/actions/actionHistory";
|
} from "@excalidraw/excalidraw/actions/actionHistory";
|
||||||
import { syncInvalidIndices } from "@excalidraw/element";
|
import { syncInvalidIndices } from "@excalidraw/element/fractionalIndex";
|
||||||
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
|
import { API } from "@excalidraw/excalidraw/tests/helpers/api";
|
||||||
import { act, render, waitFor } from "@excalidraw/excalidraw/tests/test-utils";
|
import { act, render, waitFor } from "@excalidraw/excalidraw/tests/test-utils";
|
||||||
import { vi } from "vitest";
|
import { vi } from "vitest";
|
||||||
|
|
||||||
import { StoreIncrement } from "@excalidraw/element";
|
|
||||||
|
|
||||||
import type { DurableIncrement, EphemeralIncrement } from "@excalidraw/element";
|
|
||||||
|
|
||||||
import ExcalidrawApp from "../App";
|
import ExcalidrawApp from "../App";
|
||||||
|
|
||||||
const { h } = window;
|
const { h } = window;
|
||||||
@@ -69,79 +65,6 @@ vi.mock("socket.io-client", () => {
|
|||||||
* i.e. multiplayer history tests could be a good first candidate, as we could test both history stacks simultaneously.
|
* i.e. multiplayer history tests could be a good first candidate, as we could test both history stacks simultaneously.
|
||||||
*/
|
*/
|
||||||
describe("collaboration", () => {
|
describe("collaboration", () => {
|
||||||
it("should emit two ephemeral increments even though updates get batched", async () => {
|
|
||||||
const durableIncrements: DurableIncrement[] = [];
|
|
||||||
const ephemeralIncrements: EphemeralIncrement[] = [];
|
|
||||||
|
|
||||||
await render(<ExcalidrawApp />);
|
|
||||||
|
|
||||||
h.store.onStoreIncrementEmitter.on((increment) => {
|
|
||||||
if (StoreIncrement.isDurable(increment)) {
|
|
||||||
durableIncrements.push(increment);
|
|
||||||
} else {
|
|
||||||
ephemeralIncrements.push(increment);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// eslint-disable-next-line dot-notation
|
|
||||||
expect(h.store["scheduledMicroActions"].length).toBe(0);
|
|
||||||
expect(durableIncrements.length).toBe(0);
|
|
||||||
expect(ephemeralIncrements.length).toBe(0);
|
|
||||||
|
|
||||||
const rectProps = {
|
|
||||||
type: "rectangle",
|
|
||||||
id: "A",
|
|
||||||
height: 200,
|
|
||||||
width: 100,
|
|
||||||
x: 0,
|
|
||||||
y: 0,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
const rect = API.createElement({ ...rectProps });
|
|
||||||
|
|
||||||
API.updateScene({
|
|
||||||
elements: [rect],
|
|
||||||
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
// expect(commitSpy).toHaveBeenCalledTimes(1);
|
|
||||||
expect(durableIncrements.length).toBe(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
// simulate two batched remote updates
|
|
||||||
act(() => {
|
|
||||||
h.app.updateScene({
|
|
||||||
elements: [newElementWith(h.elements[0], { x: 100 })],
|
|
||||||
captureUpdate: CaptureUpdateAction.NEVER,
|
|
||||||
});
|
|
||||||
h.app.updateScene({
|
|
||||||
elements: [newElementWith(h.elements[0], { x: 200 })],
|
|
||||||
captureUpdate: CaptureUpdateAction.NEVER,
|
|
||||||
});
|
|
||||||
|
|
||||||
// we scheduled two micro actions,
|
|
||||||
// which confirms they are going to be executed as part of one batched component update
|
|
||||||
// eslint-disable-next-line dot-notation
|
|
||||||
expect(h.store["scheduledMicroActions"].length).toBe(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
await waitFor(() => {
|
|
||||||
// altough the updates get batched,
|
|
||||||
// we expect two ephemeral increments for each update,
|
|
||||||
// and each such update should have the expected change
|
|
||||||
expect(ephemeralIncrements.length).toBe(2);
|
|
||||||
expect(ephemeralIncrements[0].change.elements.A).toEqual(
|
|
||||||
expect.objectContaining({ x: 100 }),
|
|
||||||
);
|
|
||||||
expect(ephemeralIncrements[1].change.elements.A).toEqual(
|
|
||||||
expect.objectContaining({ x: 200 }),
|
|
||||||
);
|
|
||||||
// eslint-disable-next-line dot-notation
|
|
||||||
expect(h.store["scheduledMicroActions"].length).toBe(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should allow to undo / redo even on force-deleted elements", async () => {
|
it("should allow to undo / redo even on force-deleted elements", async () => {
|
||||||
await render(<ExcalidrawApp />);
|
await render(<ExcalidrawApp />);
|
||||||
const rect1Props = {
|
const rect1Props = {
|
||||||
@@ -205,7 +128,6 @@ describe("collaboration", () => {
|
|||||||
// with explicit undo (as addition) we expect our item to be restored from the snapshot!
|
// with explicit undo (as addition) we expect our item to be restored from the snapshot!
|
||||||
await waitFor(() => {
|
await waitFor(() => {
|
||||||
expect(API.getUndoStack().length).toBe(1);
|
expect(API.getUndoStack().length).toBe(1);
|
||||||
expect(API.getRedoStack().length).toBe(1);
|
|
||||||
expect(API.getSnapshot()).toEqual([
|
expect(API.getSnapshot()).toEqual([
|
||||||
expect.objectContaining(rect1Props),
|
expect.objectContaining(rect1Props),
|
||||||
expect.objectContaining({ ...rect2Props, isDeleted: false }),
|
expect.objectContaining({ ...rect2Props, isDeleted: false }),
|
||||||
@@ -248,5 +170,79 @@ describe("collaboration", () => {
|
|||||||
expect.objectContaining({ ...rect2Props, isDeleted: true }),
|
expect.objectContaining({ ...rect2Props, isDeleted: true }),
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
act(() => h.app.actionManager.executeAction(undoAction));
|
||||||
|
|
||||||
|
// simulate local update
|
||||||
|
API.updateScene({
|
||||||
|
elements: syncInvalidIndices([
|
||||||
|
h.elements[0],
|
||||||
|
newElementWith(h.elements[1], { x: 100 }),
|
||||||
|
]),
|
||||||
|
captureUpdate: CaptureUpdateAction.IMMEDIATELY,
|
||||||
|
});
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(API.getUndoStack().length).toBe(2);
|
||||||
|
expect(API.getRedoStack().length).toBe(0);
|
||||||
|
expect(API.getSnapshot()).toEqual([
|
||||||
|
expect.objectContaining(rect1Props),
|
||||||
|
expect.objectContaining({ ...rect2Props, isDeleted: false, x: 100 }),
|
||||||
|
]);
|
||||||
|
expect(h.elements).toEqual([
|
||||||
|
expect.objectContaining(rect1Props),
|
||||||
|
expect.objectContaining({ ...rect2Props, isDeleted: false, x: 100 }),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => h.app.actionManager.executeAction(undoAction));
|
||||||
|
|
||||||
|
// we expect to iterate the stack to the first visible change
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(API.getUndoStack().length).toBe(1);
|
||||||
|
expect(API.getRedoStack().length).toBe(1);
|
||||||
|
expect(API.getSnapshot()).toEqual([
|
||||||
|
expect.objectContaining(rect1Props),
|
||||||
|
expect.objectContaining({ ...rect2Props, isDeleted: false, x: 0 }),
|
||||||
|
]);
|
||||||
|
expect(h.elements).toEqual([
|
||||||
|
expect.objectContaining(rect1Props),
|
||||||
|
expect.objectContaining({ ...rect2Props, isDeleted: false, x: 0 }),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// simulate force deleting the element remotely
|
||||||
|
API.updateScene({
|
||||||
|
elements: syncInvalidIndices([rect1]),
|
||||||
|
captureUpdate: CaptureUpdateAction.NEVER,
|
||||||
|
});
|
||||||
|
|
||||||
|
// snapshot was correctly updated and marked the element as deleted
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(API.getUndoStack().length).toBe(1);
|
||||||
|
expect(API.getRedoStack().length).toBe(1);
|
||||||
|
expect(API.getSnapshot()).toEqual([
|
||||||
|
expect.objectContaining(rect1Props),
|
||||||
|
expect.objectContaining({ ...rect2Props, isDeleted: true, x: 0 }),
|
||||||
|
]);
|
||||||
|
expect(h.elements).toEqual([expect.objectContaining(rect1Props)]);
|
||||||
|
});
|
||||||
|
|
||||||
|
act(() => h.app.actionManager.executeAction(redoAction));
|
||||||
|
|
||||||
|
// with explicit redo (as update) we again restored the element from the snapshot!
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(API.getUndoStack().length).toBe(2);
|
||||||
|
expect(API.getRedoStack().length).toBe(0);
|
||||||
|
expect(API.getSnapshot()).toEqual([
|
||||||
|
expect.objectContaining({ id: "A", isDeleted: false }),
|
||||||
|
expect.objectContaining({ id: "B", isDeleted: true, x: 100 }),
|
||||||
|
]);
|
||||||
|
expect(h.history.isRedoStackEmpty).toBeTruthy();
|
||||||
|
expect(h.elements).toEqual([
|
||||||
|
expect.objectContaining({ id: "A", isDeleted: false }),
|
||||||
|
expect.objectContaining({ id: "B", isDeleted: true, x: 100 }),
|
||||||
|
]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+9
-15
@@ -33,8 +33,7 @@
|
|||||||
"pepjs": "0.5.3",
|
"pepjs": "0.5.3",
|
||||||
"prettier": "2.6.2",
|
"prettier": "2.6.2",
|
||||||
"rewire": "6.0.0",
|
"rewire": "6.0.0",
|
||||||
"rimraf": "^5.0.0",
|
"typescript": "4.9.4",
|
||||||
"typescript": "5.9.3",
|
|
||||||
"vite": "5.0.12",
|
"vite": "5.0.12",
|
||||||
"vite-plugin-checker": "0.7.2",
|
"vite-plugin-checker": "0.7.2",
|
||||||
"vite-plugin-ejs": "1.7.0",
|
"vite-plugin-ejs": "1.7.0",
|
||||||
@@ -44,7 +43,7 @@
|
|||||||
"vitest-canvas-mock": "0.3.3"
|
"vitest-canvas-mock": "0.3.3"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.0.0"
|
"node": "18.0.0 - 22.x.x"
|
||||||
},
|
},
|
||||||
"homepage": ".",
|
"homepage": ".",
|
||||||
"prettier": "@excalidraw/prettier-config",
|
"prettier": "@excalidraw/prettier-config",
|
||||||
@@ -52,17 +51,13 @@
|
|||||||
"build-node": "node ./scripts/build-node.js",
|
"build-node": "node ./scripts/build-node.js",
|
||||||
"build:app:docker": "yarn --cwd ./excalidraw-app build:app:docker",
|
"build:app:docker": "yarn --cwd ./excalidraw-app build:app:docker",
|
||||||
"build:app": "yarn --cwd ./excalidraw-app build:app",
|
"build:app": "yarn --cwd ./excalidraw-app build:app",
|
||||||
"build:common": "yarn --cwd ./packages/common build:esm",
|
"build:package": "yarn --cwd ./packages/excalidraw build:esm",
|
||||||
"build:element": "yarn --cwd ./packages/element build:esm",
|
|
||||||
"build:excalidraw": "yarn --cwd ./packages/excalidraw build:esm",
|
|
||||||
"build:math": "yarn --cwd ./packages/math build:esm",
|
|
||||||
"build:packages": "yarn build:common && yarn build:math && yarn build:element && yarn build:excalidraw",
|
|
||||||
"build:version": "yarn --cwd ./excalidraw-app build:version",
|
"build:version": "yarn --cwd ./excalidraw-app build:version",
|
||||||
"build": "yarn --cwd ./excalidraw-app build",
|
"build": "yarn --cwd ./excalidraw-app build",
|
||||||
"build:preview": "yarn --cwd ./excalidraw-app build:preview",
|
"build:preview": "yarn --cwd ./excalidraw-app build:preview",
|
||||||
"start": "yarn --cwd ./excalidraw-app start",
|
"start": "yarn --cwd ./excalidraw-app start",
|
||||||
"start:production": "yarn --cwd ./excalidraw-app start:production",
|
"start:production": "yarn --cwd ./excalidraw-app start:production",
|
||||||
"start:example": "yarn build:packages && yarn --cwd ./examples/with-script-in-browser start",
|
"start:example": "yarn build:package && yarn --cwd ./examples/with-script-in-browser start",
|
||||||
"test:all": "yarn test:typecheck && yarn test:code && yarn test:other && yarn test:app --watch=false",
|
"test:all": "yarn test:typecheck && yarn test:code && yarn test:other && yarn test:app --watch=false",
|
||||||
"test:app": "vitest",
|
"test:app": "vitest",
|
||||||
"test:code": "eslint --max-warnings=0 --ext .js,.ts,.tsx .",
|
"test:code": "eslint --max-warnings=0 --ext .js,.ts,.tsx .",
|
||||||
@@ -80,12 +75,11 @@
|
|||||||
"locales-coverage:description": "node scripts/locales-coverage-description.js",
|
"locales-coverage:description": "node scripts/locales-coverage-description.js",
|
||||||
"prepare": "husky install",
|
"prepare": "husky install",
|
||||||
"prettier": "prettier \"**/*.{css,scss,json,md,html,yml}\" --ignore-path=.eslintignore",
|
"prettier": "prettier \"**/*.{css,scss,json,md,html,yml}\" --ignore-path=.eslintignore",
|
||||||
"release": "node scripts/release.js",
|
"autorelease": "node scripts/autorelease.js",
|
||||||
"release:test": "node scripts/release.js --tag=test",
|
"prerelease:excalidraw": "node scripts/prerelease.js",
|
||||||
"release:next": "node scripts/release.js --tag=next",
|
"release:excalidraw": "node scripts/release.js",
|
||||||
"release:latest": "node scripts/release.js --tag=latest",
|
"rm:build": "rm -rf excalidraw-app/{build,dist,dev-dist} && rm -rf packages/*/{dist,build} && rm -rf examples/*/{build,dist}",
|
||||||
"rm:build": "rimraf --glob excalidraw-app/build excalidraw-app/dist excalidraw-app/dev-dist packages/*/dist packages/*/build examples/*/build examples/*/dist",
|
"rm:node_modules": "rm -rf node_modules && rm -rf excalidraw-app/node_modules && rm -rf packages/*/node_modules",
|
||||||
"rm:node_modules": "rimraf --glob node_modules excalidraw-app/node_modules packages/*/node_modules",
|
|
||||||
"clean-install": "yarn rm:node_modules && yarn install"
|
"clean-install": "yarn rm:node_modules && yarn install"
|
||||||
},
|
},
|
||||||
"resolutions": {
|
"resolutions": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@excalidraw/common",
|
"name": "@excalidraw/common",
|
||||||
"version": "0.18.0",
|
"version": "0.1.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"types": "./dist/types/common/src/index.d.ts",
|
"types": "./dist/types/common/src/index.d.ts",
|
||||||
"main": "./dist/prod/index.js",
|
"main": "./dist/prod/index.js",
|
||||||
@@ -13,10 +13,7 @@
|
|||||||
"default": "./dist/prod/index.js"
|
"default": "./dist/prod/index.js"
|
||||||
},
|
},
|
||||||
"./*": {
|
"./*": {
|
||||||
"types": "./dist/types/common/src/*.d.ts",
|
"types": "./../common/dist/types/common/src/*.d.ts"
|
||||||
"development": "./dist/dev/index.js",
|
|
||||||
"production": "./dist/prod/index.js",
|
|
||||||
"default": "./dist/prod/index.js"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
@@ -53,7 +50,7 @@
|
|||||||
"bugs": "https://github.com/excalidraw/excalidraw/issues",
|
"bugs": "https://github.com/excalidraw/excalidraw/issues",
|
||||||
"repository": "https://github.com/excalidraw/excalidraw",
|
"repository": "https://github.com/excalidraw/excalidraw",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"gen:types": "rimraf types && tsc",
|
"gen:types": "rm -rf types && tsc",
|
||||||
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
|
"build:esm": "rm -rf dist && node ../../scripts/buildBase.js && yarn gen:types"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,18 +5,17 @@ export class BinaryHeap<T> {
|
|||||||
|
|
||||||
sinkDown(idx: number) {
|
sinkDown(idx: number) {
|
||||||
const node = this.content[idx];
|
const node = this.content[idx];
|
||||||
const nodeScore = this.scoreFunction(node);
|
|
||||||
while (idx > 0) {
|
while (idx > 0) {
|
||||||
const parentN = ((idx + 1) >> 1) - 1;
|
const parentN = ((idx + 1) >> 1) - 1;
|
||||||
const parent = this.content[parentN];
|
const parent = this.content[parentN];
|
||||||
if (nodeScore < this.scoreFunction(parent)) {
|
if (this.scoreFunction(node) < this.scoreFunction(parent)) {
|
||||||
|
this.content[parentN] = node;
|
||||||
this.content[idx] = parent;
|
this.content[idx] = parent;
|
||||||
idx = parentN; // TODO: Optimize
|
idx = parentN; // TODO: Optimize
|
||||||
} else {
|
} else {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.content[idx] = node;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bubbleUp(idx: number) {
|
bubbleUp(idx: number) {
|
||||||
@@ -25,39 +24,35 @@ export class BinaryHeap<T> {
|
|||||||
const score = this.scoreFunction(node);
|
const score = this.scoreFunction(node);
|
||||||
|
|
||||||
while (true) {
|
while (true) {
|
||||||
const child1N = ((idx + 1) << 1) - 1;
|
const child2N = (idx + 1) << 1;
|
||||||
const child2N = child1N + 1;
|
const child1N = child2N - 1;
|
||||||
let smallestIdx = idx;
|
let swap = null;
|
||||||
let smallestScore = score;
|
let child1Score = 0;
|
||||||
|
|
||||||
// Check left child
|
|
||||||
if (child1N < length) {
|
if (child1N < length) {
|
||||||
const child1Score = this.scoreFunction(this.content[child1N]);
|
const child1 = this.content[child1N];
|
||||||
if (child1Score < smallestScore) {
|
child1Score = this.scoreFunction(child1);
|
||||||
smallestIdx = child1N;
|
if (child1Score < score) {
|
||||||
smallestScore = child1Score;
|
swap = child1N;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check right child
|
|
||||||
if (child2N < length) {
|
if (child2N < length) {
|
||||||
const child2Score = this.scoreFunction(this.content[child2N]);
|
const child2 = this.content[child2N];
|
||||||
if (child2Score < smallestScore) {
|
const child2Score = this.scoreFunction(child2);
|
||||||
smallestIdx = child2N;
|
if (child2Score < (swap === null ? score : child1Score)) {
|
||||||
|
swap = child2N;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (smallestIdx === idx) {
|
if (swap !== null) {
|
||||||
|
this.content[idx] = this.content[swap];
|
||||||
|
this.content[swap] = node;
|
||||||
|
idx = swap; // TODO: Optimize
|
||||||
|
} else {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Move the smaller child up, continue finding position for node
|
|
||||||
this.content[idx] = this.content[smallestIdx];
|
|
||||||
idx = smallestIdx;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Place node in its final position
|
|
||||||
this.content[idx] = node;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
push(node: T) {
|
push(node: T) {
|
||||||
|
|||||||
@@ -1,17 +0,0 @@
|
|||||||
/**
|
|
||||||
* x and y position of top left corner, x and y position of bottom right corner
|
|
||||||
*/
|
|
||||||
export type Bounds = readonly [
|
|
||||||
minX: number,
|
|
||||||
minY: number,
|
|
||||||
maxX: number,
|
|
||||||
maxY: number,
|
|
||||||
];
|
|
||||||
|
|
||||||
export const isBounds = (box: unknown): box is Bounds =>
|
|
||||||
Array.isArray(box) &&
|
|
||||||
box.length === 4 &&
|
|
||||||
typeof box[0] === "number" &&
|
|
||||||
typeof box[1] === "number" &&
|
|
||||||
typeof box[2] === "number" &&
|
|
||||||
typeof box[3] === "number";
|
|
||||||
@@ -6,6 +6,24 @@ import type { AppProps, AppState } from "@excalidraw/excalidraw/types";
|
|||||||
|
|
||||||
import { COLOR_PALETTE } from "./colors";
|
import { COLOR_PALETTE } from "./colors";
|
||||||
|
|
||||||
|
export const isDarwin = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
|
||||||
|
export const isWindows = /^Win/.test(navigator.platform);
|
||||||
|
export const isAndroid = /\b(android)\b/i.test(navigator.userAgent);
|
||||||
|
export const isFirefox =
|
||||||
|
"netscape" in window &&
|
||||||
|
navigator.userAgent.indexOf("rv:") > 1 &&
|
||||||
|
navigator.userAgent.indexOf("Gecko") > 1;
|
||||||
|
export const isChrome = navigator.userAgent.indexOf("Chrome") !== -1;
|
||||||
|
export const isSafari =
|
||||||
|
!isChrome && navigator.userAgent.indexOf("Safari") !== -1;
|
||||||
|
export const isIOS =
|
||||||
|
/iPad|iPhone/.test(navigator.platform) ||
|
||||||
|
// iPadOS 13+
|
||||||
|
(navigator.userAgent.includes("Mac") && "ontouchend" in document);
|
||||||
|
// keeping function so it can be mocked in test
|
||||||
|
export const isBrave = () =>
|
||||||
|
(navigator as any).brave?.isBrave?.name === "isBrave";
|
||||||
|
|
||||||
export const supportsResizeObserver =
|
export const supportsResizeObserver =
|
||||||
typeof window !== "undefined" && "ResizeObserver" in window;
|
typeof window !== "undefined" && "ResizeObserver" in window;
|
||||||
|
|
||||||
@@ -17,7 +35,6 @@ export const APP_NAME = "Excalidraw";
|
|||||||
// (happens a lot with fast clicks with the text tool)
|
// (happens a lot with fast clicks with the text tool)
|
||||||
export const TEXT_AUTOWRAP_THRESHOLD = 36; // px
|
export const TEXT_AUTOWRAP_THRESHOLD = 36; // px
|
||||||
export const DRAGGING_THRESHOLD = 10; // px
|
export const DRAGGING_THRESHOLD = 10; // px
|
||||||
export const MINIMUM_ARROW_SIZE = 20; // px
|
|
||||||
export const LINE_CONFIRM_THRESHOLD = 8; // px
|
export const LINE_CONFIRM_THRESHOLD = 8; // px
|
||||||
export const ELEMENT_SHIFT_TRANSLATE_AMOUNT = 5;
|
export const ELEMENT_SHIFT_TRANSLATE_AMOUNT = 5;
|
||||||
export const ELEMENT_TRANSLATE_AMOUNT = 1;
|
export const ELEMENT_TRANSLATE_AMOUNT = 1;
|
||||||
@@ -99,22 +116,11 @@ export const ENV = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const CLASSES = {
|
export const CLASSES = {
|
||||||
SIDEBAR: "sidebar",
|
|
||||||
SHAPE_ACTIONS_MENU: "App-menu__left",
|
SHAPE_ACTIONS_MENU: "App-menu__left",
|
||||||
ZOOM_ACTIONS: "zoom-actions",
|
ZOOM_ACTIONS: "zoom-actions",
|
||||||
SEARCH_MENU_INPUT_WRAPPER: "layer-ui__search-inputWrapper",
|
SEARCH_MENU_INPUT_WRAPPER: "layer-ui__search-inputWrapper",
|
||||||
CONVERT_ELEMENT_TYPE_POPUP: "ConvertElementTypePopup",
|
|
||||||
SHAPE_ACTIONS_THEME_SCOPE: "shape-actions-theme-scope",
|
|
||||||
FRAME_NAME: "frame-name",
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const FONT_SIZES = {
|
|
||||||
sm: 16,
|
|
||||||
md: 20,
|
|
||||||
lg: 28,
|
|
||||||
xl: 36,
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export const CJK_HAND_DRAWN_FALLBACK_FONT = "Xiaolai";
|
export const CJK_HAND_DRAWN_FALLBACK_FONT = "Xiaolai";
|
||||||
export const WINDOWS_EMOJI_FALLBACK_FONT = "Segoe UI Emoji";
|
export const WINDOWS_EMOJI_FALLBACK_FONT = "Segoe UI Emoji";
|
||||||
|
|
||||||
@@ -136,52 +142,21 @@ export const FONT_FAMILY = {
|
|||||||
"Lilita One": 7,
|
"Lilita One": 7,
|
||||||
"Comic Shanns": 8,
|
"Comic Shanns": 8,
|
||||||
"Liberation Sans": 9,
|
"Liberation Sans": 9,
|
||||||
Assistant: 10,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Segoe UI Emoji fails to properly fallback for some glyphs: ∞, ∫, ≠
|
|
||||||
// so we need to have generic font fallback before it
|
|
||||||
export const SANS_SERIF_GENERIC_FONT = "sans-serif";
|
|
||||||
export const MONOSPACE_GENERIC_FONT = "monospace";
|
|
||||||
|
|
||||||
export const FONT_FAMILY_GENERIC_FALLBACKS = {
|
|
||||||
[SANS_SERIF_GENERIC_FONT]: 998,
|
|
||||||
[MONOSPACE_GENERIC_FONT]: 999,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const FONT_FAMILY_FALLBACKS = {
|
export const FONT_FAMILY_FALLBACKS = {
|
||||||
[CJK_HAND_DRAWN_FALLBACK_FONT]: 100,
|
[CJK_HAND_DRAWN_FALLBACK_FONT]: 100,
|
||||||
...FONT_FAMILY_GENERIC_FALLBACKS,
|
|
||||||
[WINDOWS_EMOJI_FALLBACK_FONT]: 1000,
|
[WINDOWS_EMOJI_FALLBACK_FONT]: 1000,
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getGenericFontFamilyFallback(
|
|
||||||
fontFamily: number,
|
|
||||||
): keyof typeof FONT_FAMILY_GENERIC_FALLBACKS {
|
|
||||||
switch (fontFamily) {
|
|
||||||
case FONT_FAMILY.Cascadia:
|
|
||||||
case FONT_FAMILY["Comic Shanns"]:
|
|
||||||
return MONOSPACE_GENERIC_FONT;
|
|
||||||
|
|
||||||
default:
|
|
||||||
return SANS_SERIF_GENERIC_FONT;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export const getFontFamilyFallbacks = (
|
export const getFontFamilyFallbacks = (
|
||||||
fontFamily: number,
|
fontFamily: number,
|
||||||
): Array<keyof typeof FONT_FAMILY_FALLBACKS> => {
|
): Array<keyof typeof FONT_FAMILY_FALLBACKS> => {
|
||||||
const genericFallbackFont = getGenericFontFamilyFallback(fontFamily);
|
|
||||||
|
|
||||||
switch (fontFamily) {
|
switch (fontFamily) {
|
||||||
case FONT_FAMILY.Excalifont:
|
case FONT_FAMILY.Excalifont:
|
||||||
return [
|
return [CJK_HAND_DRAWN_FALLBACK_FONT, WINDOWS_EMOJI_FALLBACK_FONT];
|
||||||
CJK_HAND_DRAWN_FALLBACK_FONT,
|
|
||||||
genericFallbackFont,
|
|
||||||
WINDOWS_EMOJI_FALLBACK_FONT,
|
|
||||||
];
|
|
||||||
default:
|
default:
|
||||||
return [genericFallbackFont, WINDOWS_EMOJI_FALLBACK_FONT];
|
return [WINDOWS_EMOJI_FALLBACK_FONT];
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -243,20 +218,13 @@ export const IMAGE_MIME_TYPES = {
|
|||||||
jfif: "image/jfif",
|
jfif: "image/jfif",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export const STRING_MIME_TYPES = {
|
export const MIME_TYPES = {
|
||||||
text: "text/plain",
|
text: "text/plain",
|
||||||
html: "text/html",
|
html: "text/html",
|
||||||
json: "application/json",
|
json: "application/json",
|
||||||
// excalidraw data
|
// excalidraw data
|
||||||
excalidraw: "application/vnd.excalidraw+json",
|
excalidraw: "application/vnd.excalidraw+json",
|
||||||
// LEGACY: fully-qualified library JSON data
|
|
||||||
excalidrawlib: "application/vnd.excalidrawlib+json",
|
excalidrawlib: "application/vnd.excalidrawlib+json",
|
||||||
// list of excalidraw library item ids
|
|
||||||
excalidrawlibIds: "application/vnd.excalidrawlib.ids+json",
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
export const MIME_TYPES = {
|
|
||||||
...STRING_MIME_TYPES,
|
|
||||||
// image-encoded excalidraw data
|
// image-encoded excalidraw data
|
||||||
"excalidraw.svg": "image/svg+xml",
|
"excalidraw.svg": "image/svg+xml",
|
||||||
"excalidraw.png": "image/png",
|
"excalidraw.png": "image/png",
|
||||||
@@ -285,7 +253,7 @@ export const EXPORT_DATA_TYPES = {
|
|||||||
excalidrawClipboardWithAPI: "excalidraw-api/clipboard",
|
excalidrawClipboardWithAPI: "excalidraw-api/clipboard",
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export const getExportSource = () =>
|
export const EXPORT_SOURCE =
|
||||||
window.EXCALIDRAW_EXPORT_SOURCE || window.location.origin;
|
window.EXCALIDRAW_EXPORT_SOURCE || window.location.origin;
|
||||||
|
|
||||||
// time in milliseconds
|
// time in milliseconds
|
||||||
@@ -331,6 +299,16 @@ export const DEFAULT_UI_OPTIONS: AppProps["UIOptions"] = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// breakpoints
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
// md screen
|
||||||
|
export const MQ_MAX_WIDTH_PORTRAIT = 730;
|
||||||
|
export const MQ_MAX_WIDTH_LANDSCAPE = 1000;
|
||||||
|
export const MQ_MAX_HEIGHT_LANDSCAPE = 500;
|
||||||
|
// sidebar
|
||||||
|
export const MQ_RIGHT_SIDEBAR_MIN_WIDTH = 1229;
|
||||||
|
// -----------------------------------------------------------------------------
|
||||||
|
|
||||||
export const MAX_DECIMALS_FOR_SVG_EXPORT = 2;
|
export const MAX_DECIMALS_FOR_SVG_EXPORT = 2;
|
||||||
|
|
||||||
export const EXPORT_SCALES = [1, 2, 3];
|
export const EXPORT_SCALES = [1, 2, 3];
|
||||||
@@ -496,19 +474,3 @@ export enum UserIdleState {
|
|||||||
AWAY = "away",
|
AWAY = "away",
|
||||||
IDLE = "idle",
|
IDLE = "idle",
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* distance at which we merge points instead of adding a new merge-point
|
|
||||||
* when converting a line to a polygon (merge currently means overlaping
|
|
||||||
* the start and end points)
|
|
||||||
*/
|
|
||||||
export const LINE_POLYGON_POINT_MERGE_DISTANCE = 20;
|
|
||||||
|
|
||||||
export const DOUBLE_TAP_POSITION_THRESHOLD = 35;
|
|
||||||
|
|
||||||
export const BIND_MODE_TIMEOUT = 700; // ms
|
|
||||||
|
|
||||||
// glass background for mobile action buttons
|
|
||||||
export const MOBILE_ACTION_BUTTON_BG = {
|
|
||||||
background: "var(--mobile-action-button-bg)",
|
|
||||||
} as const;
|
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
export type StylesPanelMode = "compact" | "full" | "mobile";
|
|
||||||
|
|
||||||
export type EditorInterface = Readonly<{
|
|
||||||
formFactor: "phone" | "tablet" | "desktop";
|
|
||||||
desktopUIMode: "compact" | "full";
|
|
||||||
userAgent: Readonly<{
|
|
||||||
isMobileDevice: boolean;
|
|
||||||
platform: "ios" | "android" | "other" | "unknown";
|
|
||||||
}>;
|
|
||||||
isTouchScreen: boolean;
|
|
||||||
canFitSidebar: boolean;
|
|
||||||
isLandscape: boolean;
|
|
||||||
}>;
|
|
||||||
|
|
||||||
// storage key
|
|
||||||
const DESKTOP_UI_MODE_STORAGE_KEY = "excalidraw.desktopUIMode";
|
|
||||||
|
|
||||||
// breakpoints
|
|
||||||
// mobile: up to 699px
|
|
||||||
export const MQ_MAX_MOBILE = 599;
|
|
||||||
|
|
||||||
export const MQ_MAX_WIDTH_LANDSCAPE = 1000;
|
|
||||||
export const MQ_MAX_HEIGHT_LANDSCAPE = 500;
|
|
||||||
|
|
||||||
// tablets
|
|
||||||
export const MQ_MIN_TABLET = MQ_MAX_MOBILE + 1; // lower bound (excludes phones)
|
|
||||||
export const MQ_MAX_TABLET = 1400; // upper bound (excludes laptops/desktops)
|
|
||||||
|
|
||||||
// desktop/laptop
|
|
||||||
export const MQ_MIN_WIDTH_DESKTOP = 1440;
|
|
||||||
|
|
||||||
// sidebar
|
|
||||||
export const MQ_RIGHT_SIDEBAR_MIN_WIDTH = 1229;
|
|
||||||
|
|
||||||
// -----------------------------------------------------------------------------
|
|
||||||
|
|
||||||
// user agent detections
|
|
||||||
export const isDarwin = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
|
|
||||||
export const isWindows = /^Win/.test(navigator.platform);
|
|
||||||
export const isAndroid = /\b(android)\b/i.test(navigator.userAgent);
|
|
||||||
export const isFirefox =
|
|
||||||
typeof window !== "undefined" &&
|
|
||||||
"netscape" in window &&
|
|
||||||
navigator.userAgent.indexOf("rv:") > 1 &&
|
|
||||||
navigator.userAgent.indexOf("Gecko") > 1;
|
|
||||||
export const isChrome = navigator.userAgent.indexOf("Chrome") !== -1;
|
|
||||||
export const isSafari =
|
|
||||||
!isChrome && navigator.userAgent.indexOf("Safari") !== -1;
|
|
||||||
export const isIOS =
|
|
||||||
/iPad|iPhone/i.test(navigator.platform) ||
|
|
||||||
// iPadOS 13+
|
|
||||||
(navigator.userAgent.includes("Mac") && "ontouchend" in document);
|
|
||||||
// keeping function so it can be mocked in test
|
|
||||||
export const isBrave = () =>
|
|
||||||
(navigator as any).brave?.isBrave?.name === "isBrave";
|
|
||||||
|
|
||||||
// export const isMobile =
|
|
||||||
// isIOS ||
|
|
||||||
// /android|webos|ipod|blackberry|iemobile|opera mini/i.test(
|
|
||||||
// navigator.userAgent,
|
|
||||||
// ) ||
|
|
||||||
// /android|ios|ipod|blackberry|windows phone/i.test(navigator.platform);
|
|
||||||
|
|
||||||
// utilities
|
|
||||||
export const isMobileBreakpoint = (width: number, height: number) => {
|
|
||||||
return (
|
|
||||||
width <= MQ_MAX_MOBILE ||
|
|
||||||
(height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE)
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isTabletBreakpoint = (
|
|
||||||
editorWidth: number,
|
|
||||||
editorHeight: number,
|
|
||||||
) => {
|
|
||||||
const minSide = Math.min(editorWidth, editorHeight);
|
|
||||||
const maxSide = Math.max(editorWidth, editorHeight);
|
|
||||||
|
|
||||||
return minSide >= MQ_MIN_TABLET && maxSide <= MQ_MAX_TABLET;
|
|
||||||
};
|
|
||||||
|
|
||||||
const isMobileOrTablet = (): boolean => {
|
|
||||||
const ua = navigator.userAgent || "";
|
|
||||||
const platform = navigator.platform || "";
|
|
||||||
const uaData = (navigator as any).userAgentData as
|
|
||||||
| { mobile?: boolean; platform?: string }
|
|
||||||
| undefined;
|
|
||||||
|
|
||||||
// --- 1) chromium: prefer ua client hints -------------------------------
|
|
||||||
if (uaData) {
|
|
||||||
const plat = (uaData.platform || "").toLowerCase();
|
|
||||||
const isDesktopOS =
|
|
||||||
plat === "windows" ||
|
|
||||||
plat === "macos" ||
|
|
||||||
plat === "linux" ||
|
|
||||||
plat === "chrome os";
|
|
||||||
if (uaData.mobile === true) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
if (uaData.mobile === false && plat === "android") {
|
|
||||||
const looksTouchTablet =
|
|
||||||
matchMedia?.("(hover: none)").matches &&
|
|
||||||
matchMedia?.("(pointer: coarse)").matches;
|
|
||||||
return looksTouchTablet;
|
|
||||||
}
|
|
||||||
if (isDesktopOS) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 2) ios (includes ipad) --------------------------------------------
|
|
||||||
if (isIOS) {
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 3) android legacy ua fallback -------------------------------------
|
|
||||||
if (isAndroid) {
|
|
||||||
const isAndroidPhone = /Mobile/i.test(ua);
|
|
||||||
const isAndroidTablet = !isAndroidPhone;
|
|
||||||
if (isAndroidPhone || isAndroidTablet) {
|
|
||||||
const looksTouchTablet =
|
|
||||||
matchMedia?.("(hover: none)").matches &&
|
|
||||||
matchMedia?.("(pointer: coarse)").matches;
|
|
||||||
return looksTouchTablet;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// --- 4) last resort desktop exclusion ----------------------------------
|
|
||||||
const looksDesktopPlatform =
|
|
||||||
/Win|Linux|CrOS|Mac/.test(platform) ||
|
|
||||||
/Windows NT|X11|CrOS|Macintosh/.test(ua);
|
|
||||||
if (looksDesktopPlatform) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFormFactor = (
|
|
||||||
editorWidth: number,
|
|
||||||
editorHeight: number,
|
|
||||||
): EditorInterface["formFactor"] => {
|
|
||||||
if (isMobileBreakpoint(editorWidth, editorHeight)) {
|
|
||||||
return "phone";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isTabletBreakpoint(editorWidth, editorHeight)) {
|
|
||||||
return "tablet";
|
|
||||||
}
|
|
||||||
|
|
||||||
return "desktop";
|
|
||||||
};
|
|
||||||
|
|
||||||
export const deriveStylesPanelMode = (
|
|
||||||
editorInterface: EditorInterface,
|
|
||||||
): StylesPanelMode => {
|
|
||||||
if (editorInterface.formFactor === "phone") {
|
|
||||||
return "mobile";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (editorInterface.formFactor === "tablet") {
|
|
||||||
return "compact";
|
|
||||||
}
|
|
||||||
|
|
||||||
return editorInterface.desktopUIMode;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const createUserAgentDescriptor = (
|
|
||||||
userAgentString: string,
|
|
||||||
): EditorInterface["userAgent"] => {
|
|
||||||
const normalizedUA = userAgentString ?? "";
|
|
||||||
let platform: EditorInterface["userAgent"]["platform"] = "unknown";
|
|
||||||
|
|
||||||
if (isIOS) {
|
|
||||||
platform = "ios";
|
|
||||||
} else if (isAndroid) {
|
|
||||||
platform = "android";
|
|
||||||
} else if (normalizedUA) {
|
|
||||||
platform = "other";
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
isMobileDevice: isMobileOrTablet(),
|
|
||||||
platform,
|
|
||||||
} as const;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const loadDesktopUIModePreference = () => {
|
|
||||||
if (typeof window === "undefined") {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const stored = window.localStorage.getItem(DESKTOP_UI_MODE_STORAGE_KEY);
|
|
||||||
if (stored === "compact" || stored === "full") {
|
|
||||||
return stored as EditorInterface["desktopUIMode"];
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
// ignore storage access issues (e.g., Safari private mode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const persistDesktopUIMode = (mode: EditorInterface["desktopUIMode"]) => {
|
|
||||||
if (typeof window === "undefined") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
window.localStorage.setItem(DESKTOP_UI_MODE_STORAGE_KEY, mode);
|
|
||||||
} catch (error) {
|
|
||||||
// ignore storage access issues (e.g., Safari private mode)
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setDesktopUIMode = (mode: EditorInterface["desktopUIMode"]) => {
|
|
||||||
if (mode !== "compact" && mode !== "full") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
persistDesktopUIMode(mode);
|
|
||||||
|
|
||||||
return mode;
|
|
||||||
};
|
|
||||||
@@ -22,10 +22,8 @@ export interface FontMetadata {
|
|||||||
};
|
};
|
||||||
/** flag to indicate a deprecated font */
|
/** flag to indicate a deprecated font */
|
||||||
deprecated?: true;
|
deprecated?: true;
|
||||||
/**
|
/** flag to indicate a server-side only font */
|
||||||
* whether this is a font that users can use (= shown in font picker)
|
serverSide?: true;
|
||||||
*/
|
|
||||||
private?: true;
|
|
||||||
/** flag to indiccate a local-only font */
|
/** flag to indiccate a local-only font */
|
||||||
local?: true;
|
local?: true;
|
||||||
/** flag to indicate a fallback font */
|
/** flag to indicate a fallback font */
|
||||||
@@ -46,7 +44,7 @@ export const FONT_METADATA: Record<number, FontMetadata> = {
|
|||||||
unitsPerEm: 1000,
|
unitsPerEm: 1000,
|
||||||
ascender: 1011,
|
ascender: 1011,
|
||||||
descender: -353,
|
descender: -353,
|
||||||
lineHeight: 1.25,
|
lineHeight: 1.35,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
[FONT_FAMILY["Lilita One"]]: {
|
[FONT_FAMILY["Lilita One"]]: {
|
||||||
@@ -100,23 +98,14 @@ export const FONT_METADATA: Record<number, FontMetadata> = {
|
|||||||
descender: -434,
|
descender: -434,
|
||||||
lineHeight: 1.15,
|
lineHeight: 1.15,
|
||||||
},
|
},
|
||||||
private: true,
|
serverSide: true,
|
||||||
},
|
|
||||||
[FONT_FAMILY.Assistant]: {
|
|
||||||
metrics: {
|
|
||||||
unitsPerEm: 2048,
|
|
||||||
ascender: 1021,
|
|
||||||
descender: -287,
|
|
||||||
lineHeight: 1.25,
|
|
||||||
},
|
|
||||||
private: true,
|
|
||||||
},
|
},
|
||||||
[FONT_FAMILY_FALLBACKS.Xiaolai]: {
|
[FONT_FAMILY_FALLBACKS.Xiaolai]: {
|
||||||
metrics: {
|
metrics: {
|
||||||
unitsPerEm: 1000,
|
unitsPerEm: 1000,
|
||||||
ascender: 880,
|
ascender: 880,
|
||||||
descender: -144,
|
descender: -144,
|
||||||
lineHeight: 1.25,
|
lineHeight: 1.15,
|
||||||
},
|
},
|
||||||
fallback: true,
|
fallback: true,
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,4 @@
|
|||||||
export * from "./binary-heap";
|
export * from "./binary-heap";
|
||||||
export * from "./bounds";
|
|
||||||
export * from "./colors";
|
export * from "./colors";
|
||||||
export * from "./constants";
|
export * from "./constants";
|
||||||
export * from "./font-metadata";
|
export * from "./font-metadata";
|
||||||
@@ -10,6 +9,3 @@ export * from "./promise-pool";
|
|||||||
export * from "./random";
|
export * from "./random";
|
||||||
export * from "./url";
|
export * from "./url";
|
||||||
export * from "./utils";
|
export * from "./utils";
|
||||||
export * from "./emitter";
|
|
||||||
export * from "./visualdebug";
|
|
||||||
export * from "./editorInterface";
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { isDarwin } from "./editorInterface";
|
import { isDarwin } from "./constants";
|
||||||
|
|
||||||
import type { ValueOf } from "./utility-types";
|
import type { ValueOf } from "./utility-types";
|
||||||
|
|
||||||
|
|||||||
@@ -66,14 +66,10 @@ export type MakeBrand<T extends string> = {
|
|||||||
/** Maybe just promise or already fulfilled one! */
|
/** Maybe just promise or already fulfilled one! */
|
||||||
export type MaybePromise<T> = T | Promise<T>;
|
export type MaybePromise<T> = T | Promise<T>;
|
||||||
|
|
||||||
// get union of all keys from the union of types
|
|
||||||
export type AllPossibleKeys<T> = T extends any ? keyof T : never;
|
|
||||||
|
|
||||||
/** Strip all the methods or functions from a type */
|
/** Strip all the methods or functions from a type */
|
||||||
export type DTO<T> = {
|
export type DTO<T> = {
|
||||||
[K in keyof T as T[K] extends Function ? never : K]: T[K];
|
[K in keyof T as T[K] extends Function ? never : K]: T[K];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type MapEntry<M extends Map<any, any>> = M extends Map<infer K, infer V>
|
// get union of all keys from the union of types
|
||||||
? [K, V]
|
export type AllPossibleKeys<T> = T extends any ? keyof T : never;
|
||||||
: never;
|
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
import {
|
|
||||||
isTransparent,
|
|
||||||
mapFind,
|
|
||||||
reduceToCommonValue,
|
|
||||||
} from "@excalidraw/common";
|
|
||||||
|
|
||||||
describe("@excalidraw/common/utils", () => {
|
|
||||||
describe("isTransparent()", () => {
|
|
||||||
it("should return true when color is rgb transparent", () => {
|
|
||||||
expect(isTransparent("#ff00")).toEqual(true);
|
|
||||||
expect(isTransparent("#fff00000")).toEqual(true);
|
|
||||||
expect(isTransparent("transparent")).toEqual(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return false when color is not transparent", () => {
|
|
||||||
expect(isTransparent("#ced4da")).toEqual(false);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("reduceToCommonValue()", () => {
|
|
||||||
it("should return the common value when all values are the same", () => {
|
|
||||||
expect(reduceToCommonValue([1, 1])).toEqual(1);
|
|
||||||
expect(reduceToCommonValue([0, 0])).toEqual(0);
|
|
||||||
expect(reduceToCommonValue(["a", "a"])).toEqual("a");
|
|
||||||
expect(reduceToCommonValue(new Set([1]))).toEqual(1);
|
|
||||||
expect(reduceToCommonValue([""])).toEqual("");
|
|
||||||
expect(reduceToCommonValue([0])).toEqual(0);
|
|
||||||
|
|
||||||
const o = {};
|
|
||||||
expect(reduceToCommonValue([o, o])).toEqual(o);
|
|
||||||
|
|
||||||
expect(
|
|
||||||
reduceToCommonValue([{ a: 1 }, { a: 1, b: 2 }], (o) => o.a),
|
|
||||||
).toEqual(1);
|
|
||||||
expect(
|
|
||||||
reduceToCommonValue(new Set([{ a: 1 }, { a: 1, b: 2 }]), (o) => o.a),
|
|
||||||
).toEqual(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return `null` when values are different", () => {
|
|
||||||
expect(reduceToCommonValue([1, 2, 3])).toEqual(null);
|
|
||||||
expect(reduceToCommonValue(new Set([1, 2]))).toEqual(null);
|
|
||||||
expect(reduceToCommonValue([{ a: 1 }, { a: 2 }], (o) => o.a)).toEqual(
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return `null` when some values are nullable", () => {
|
|
||||||
expect(reduceToCommonValue([1, null, 1])).toEqual(null);
|
|
||||||
expect(reduceToCommonValue([null, 1])).toEqual(null);
|
|
||||||
expect(reduceToCommonValue([1, undefined])).toEqual(null);
|
|
||||||
expect(reduceToCommonValue([undefined, 1])).toEqual(null);
|
|
||||||
expect(reduceToCommonValue([null])).toEqual(null);
|
|
||||||
expect(reduceToCommonValue([undefined])).toEqual(null);
|
|
||||||
expect(reduceToCommonValue([])).toEqual(null);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("mapFind()", () => {
|
|
||||||
it("should return the first mapped non-null element", () => {
|
|
||||||
{
|
|
||||||
let counter = 0;
|
|
||||||
|
|
||||||
const result = mapFind(["a", "b", "c"], (value) => {
|
|
||||||
counter++;
|
|
||||||
return value === "b" ? 42 : null;
|
|
||||||
});
|
|
||||||
expect(result).toEqual(42);
|
|
||||||
expect(counter).toBe(2);
|
|
||||||
}
|
|
||||||
|
|
||||||
expect(mapFind([1, 2], (value) => value * 0)).toBe(0);
|
|
||||||
expect(mapFind([1, 2], () => false)).toBe(false);
|
|
||||||
expect(mapFind([1, 2], () => "")).toBe("");
|
|
||||||
});
|
|
||||||
|
|
||||||
it("should return undefined if no mapped element is found", () => {
|
|
||||||
expect(mapFind([1, 2], () => undefined)).toBe(undefined);
|
|
||||||
expect(mapFind([1, 2], () => null)).toBe(undefined);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
+44
-122
@@ -1,6 +1,11 @@
|
|||||||
import { average } from "@excalidraw/math";
|
import { average, pointFrom, type GlobalPoint } from "@excalidraw/math";
|
||||||
|
|
||||||
import type { FontFamilyValues, FontString } from "@excalidraw/element/types";
|
import type {
|
||||||
|
ExcalidrawBindableElement,
|
||||||
|
FontFamilyValues,
|
||||||
|
FontString,
|
||||||
|
ExcalidrawElement,
|
||||||
|
} from "@excalidraw/element/types";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ActiveTool,
|
ActiveTool,
|
||||||
@@ -16,6 +21,7 @@ import {
|
|||||||
ENV,
|
ENV,
|
||||||
FONT_FAMILY,
|
FONT_FAMILY,
|
||||||
getFontFamilyFallbacks,
|
getFontFamilyFallbacks,
|
||||||
|
isDarwin,
|
||||||
WINDOWS_EMOJI_FALLBACK_FONT,
|
WINDOWS_EMOJI_FALLBACK_FONT,
|
||||||
} from "./constants";
|
} from "./constants";
|
||||||
|
|
||||||
@@ -86,8 +92,7 @@ export const isWritableElement = (
|
|||||||
(target instanceof HTMLInputElement &&
|
(target instanceof HTMLInputElement &&
|
||||||
(target.type === "text" ||
|
(target.type === "text" ||
|
||||||
target.type === "number" ||
|
target.type === "number" ||
|
||||||
target.type === "password" ||
|
target.type === "password"));
|
||||||
target.type === "search"));
|
|
||||||
|
|
||||||
export const getFontFamilyString = ({
|
export const getFontFamilyString = ({
|
||||||
fontFamily,
|
fontFamily,
|
||||||
@@ -96,6 +101,7 @@ export const getFontFamilyString = ({
|
|||||||
}) => {
|
}) => {
|
||||||
for (const [fontFamilyString, id] of Object.entries(FONT_FAMILY)) {
|
for (const [fontFamilyString, id] of Object.entries(FONT_FAMILY)) {
|
||||||
if (id === fontFamily) {
|
if (id === fontFamily) {
|
||||||
|
// TODO: we should fallback first to generic family names first
|
||||||
return `${fontFamilyString}${getFontFamilyFallbacks(id)
|
return `${fontFamilyString}${getFontFamilyFallbacks(id)
|
||||||
.map((x) => `, ${x}`)
|
.map((x) => `, ${x}`)
|
||||||
.join("")}`;
|
.join("")}`;
|
||||||
@@ -115,11 +121,6 @@ export const getFontString = ({
|
|||||||
return `${fontSize}px ${getFontFamilyString({ fontFamily })}` as FontString;
|
return `${fontSize}px ${getFontFamilyString({ fontFamily })}` as FontString;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** executes callback in the frame that's after the current one */
|
|
||||||
export const nextAnimationFrame = async (cb: () => any) => {
|
|
||||||
requestAnimationFrame(() => requestAnimationFrame(cb));
|
|
||||||
};
|
|
||||||
|
|
||||||
export const debounce = <T extends any[]>(
|
export const debounce = <T extends any[]>(
|
||||||
fn: (...args: T) => void,
|
fn: (...args: T) => void,
|
||||||
timeout: number,
|
timeout: number,
|
||||||
@@ -378,10 +379,6 @@ export const removeSelection = () => {
|
|||||||
|
|
||||||
export const distance = (x: number, y: number) => Math.abs(x - y);
|
export const distance = (x: number, y: number) => Math.abs(x - y);
|
||||||
|
|
||||||
export const isSelectionLikeTool = (type: ToolType | "custom") => {
|
|
||||||
return type === "selection" || type === "lasso";
|
|
||||||
};
|
|
||||||
|
|
||||||
export const updateActiveTool = (
|
export const updateActiveTool = (
|
||||||
appState: Pick<AppState, "activeTool">,
|
appState: Pick<AppState, "activeTool">,
|
||||||
data: ((
|
data: ((
|
||||||
@@ -423,6 +420,19 @@ export const allowFullScreen = () =>
|
|||||||
|
|
||||||
export const exitFullScreen = () => document.exitFullscreen();
|
export const exitFullScreen = () => document.exitFullscreen();
|
||||||
|
|
||||||
|
export const getShortcutKey = (shortcut: string): string => {
|
||||||
|
shortcut = shortcut
|
||||||
|
.replace(/\bAlt\b/i, "Alt")
|
||||||
|
.replace(/\bShift\b/i, "Shift")
|
||||||
|
.replace(/\b(Enter|Return)\b/i, "Enter");
|
||||||
|
if (isDarwin) {
|
||||||
|
return shortcut
|
||||||
|
.replace(/\bCtrlOrCmd\b/gi, "Cmd")
|
||||||
|
.replace(/\bAlt\b/i, "Option");
|
||||||
|
}
|
||||||
|
return shortcut.replace(/\bCtrlOrCmd\b/gi, "Ctrl");
|
||||||
|
};
|
||||||
|
|
||||||
export const viewportCoordsToSceneCoords = (
|
export const viewportCoordsToSceneCoords = (
|
||||||
{ clientX, clientY }: { clientX: number; clientY: number },
|
{ clientX, clientY }: { clientX: number; clientY: number },
|
||||||
{
|
{
|
||||||
@@ -534,20 +544,6 @@ export const findLastIndex = <T>(
|
|||||||
return -1;
|
return -1;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** returns the first non-null mapped value */
|
|
||||||
export const mapFind = <T, K>(
|
|
||||||
collection: readonly T[],
|
|
||||||
iteratee: (value: T, index: number) => K | undefined | null,
|
|
||||||
): K | undefined => {
|
|
||||||
for (let idx = 0; idx < collection.length; idx++) {
|
|
||||||
const result = iteratee(collection[idx], idx);
|
|
||||||
if (result != null) {
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isTransparent = (color: string) => {
|
export const isTransparent = (color: string) => {
|
||||||
const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
|
const isRGBTransparent = color.length === 5 && color.substr(4, 1) === "0";
|
||||||
const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
|
const isRRGGBBTransparent = color.length === 9 && color.substr(7, 2) === "00";
|
||||||
@@ -558,6 +554,9 @@ export const isTransparent = (color: string) => {
|
|||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export const isBindingFallthroughEnabled = (el: ExcalidrawBindableElement) =>
|
||||||
|
el.fillStyle !== "solid" || isTransparent(el.backgroundColor);
|
||||||
|
|
||||||
export type ResolvablePromise<T> = Promise<T> & {
|
export type ResolvablePromise<T> = Promise<T> & {
|
||||||
resolve: [T] extends [undefined]
|
resolve: [T] extends [undefined]
|
||||||
? (value?: MaybePromise<Awaited<T>>) => void
|
? (value?: MaybePromise<Awaited<T>>) => void
|
||||||
@@ -699,8 +698,8 @@ export const arrayToObject = <T>(
|
|||||||
array: readonly T[],
|
array: readonly T[],
|
||||||
groupBy?: (value: T) => string | number,
|
groupBy?: (value: T) => string | number,
|
||||||
) =>
|
) =>
|
||||||
array.reduce((acc, value, idx) => {
|
array.reduce((acc, value) => {
|
||||||
acc[groupBy ? groupBy(value) : idx] = value;
|
acc[groupBy ? groupBy(value) : String(value)] = value;
|
||||||
return acc;
|
return acc;
|
||||||
}, {} as { [key: string]: T });
|
}, {} as { [key: string]: T });
|
||||||
|
|
||||||
@@ -736,25 +735,6 @@ export const arrayToList = <T>(array: readonly T[]): Node<T>[] =>
|
|||||||
return acc;
|
return acc;
|
||||||
}, [] as Node<T>[]);
|
}, [] as Node<T>[]);
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts a readonly array or map into an iterable.
|
|
||||||
* Useful for avoiding entry allocations when iterating object / map on each iteration.
|
|
||||||
*/
|
|
||||||
export const toIterable = <T>(
|
|
||||||
values: readonly T[] | ReadonlyMap<string, T>,
|
|
||||||
): Iterable<T> => {
|
|
||||||
return Array.isArray(values) ? values : values.values();
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Converts a readonly array or map into an array.
|
|
||||||
*/
|
|
||||||
export const toArray = <T>(
|
|
||||||
values: readonly T[] | ReadonlyMap<string, T>,
|
|
||||||
): T[] => {
|
|
||||||
return Array.isArray(values) ? values : Array.from(toIterable(values));
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isTestEnv = () => import.meta.env.MODE === ENV.TEST;
|
export const isTestEnv = () => import.meta.env.MODE === ENV.TEST;
|
||||||
|
|
||||||
export const isDevEnv = () => import.meta.env.MODE === ENV.DEVELOPMENT;
|
export const isDevEnv = () => import.meta.env.MODE === ENV.DEVELOPMENT;
|
||||||
@@ -1225,89 +1205,31 @@ export const escapeDoubleQuotes = (str: string) => {
|
|||||||
export const castArray = <T>(value: T | T[]): T[] =>
|
export const castArray = <T>(value: T | T[]): T[] =>
|
||||||
Array.isArray(value) ? value : [value];
|
Array.isArray(value) ? value : [value];
|
||||||
|
|
||||||
|
export const elementCenterPoint = (
|
||||||
|
element: ExcalidrawElement,
|
||||||
|
xOffset: number = 0,
|
||||||
|
yOffset: number = 0,
|
||||||
|
) => {
|
||||||
|
const { x, y, width, height } = element;
|
||||||
|
|
||||||
|
const centerXPoint = x + width / 2 + xOffset;
|
||||||
|
|
||||||
|
const centerYPoint = y + height / 2 + yOffset;
|
||||||
|
|
||||||
|
return pointFrom<GlobalPoint>(centerXPoint, centerYPoint);
|
||||||
|
};
|
||||||
|
|
||||||
/** hack for Array.isArray type guard not working with readonly value[] */
|
/** hack for Array.isArray type guard not working with readonly value[] */
|
||||||
export const isReadonlyArray = (value?: any): value is readonly any[] => {
|
export const isReadonlyArray = (value?: any): value is readonly any[] => {
|
||||||
return Array.isArray(value);
|
return Array.isArray(value);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const sizeOf = (
|
export const sizeOf = (
|
||||||
value:
|
value: readonly number[] | Readonly<Map<any, any>> | Record<any, any>,
|
||||||
| readonly unknown[]
|
|
||||||
| Readonly<Map<string, unknown>>
|
|
||||||
| Readonly<Record<string, unknown>>
|
|
||||||
| ReadonlySet<unknown>,
|
|
||||||
): number => {
|
): number => {
|
||||||
return isReadonlyArray(value)
|
return isReadonlyArray(value)
|
||||||
? value.length
|
? value.length
|
||||||
: value instanceof Map || value instanceof Set
|
: value instanceof Map
|
||||||
? value.size
|
? value.size
|
||||||
: Object.keys(value).length;
|
: Object.keys(value).length;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const reduceToCommonValue = <T, R = T>(
|
|
||||||
collection: readonly T[] | ReadonlySet<T>,
|
|
||||||
getValue?: (item: T) => R,
|
|
||||||
): R | null => {
|
|
||||||
if (sizeOf(collection) === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const valueExtractor = getValue || ((item: T) => item as unknown as R);
|
|
||||||
|
|
||||||
let commonValue: R | null = null;
|
|
||||||
|
|
||||||
for (const item of collection) {
|
|
||||||
const value = valueExtractor(item);
|
|
||||||
if ((commonValue === null || commonValue === value) && value != null) {
|
|
||||||
commonValue = value;
|
|
||||||
} else {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return commonValue;
|
|
||||||
};
|
|
||||||
|
|
||||||
type FEATURE_FLAGS = {
|
|
||||||
COMPLEX_BINDINGS: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
const FEATURE_FLAGS_STORAGE_KEY = "excalidraw-feature-flags";
|
|
||||||
const DEFAULT_FEATURE_FLAGS: FEATURE_FLAGS = {
|
|
||||||
COMPLEX_BINDINGS: false,
|
|
||||||
};
|
|
||||||
let featureFlags: FEATURE_FLAGS | null = null;
|
|
||||||
|
|
||||||
export const getFeatureFlag = <F extends keyof FEATURE_FLAGS>(
|
|
||||||
flag: F,
|
|
||||||
): FEATURE_FLAGS[F] => {
|
|
||||||
if (!featureFlags) {
|
|
||||||
try {
|
|
||||||
const serializedFlags = localStorage.getItem(FEATURE_FLAGS_STORAGE_KEY);
|
|
||||||
if (serializedFlags) {
|
|
||||||
const flags = JSON.parse(serializedFlags);
|
|
||||||
featureFlags = flags ?? DEFAULT_FEATURE_FLAGS;
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (featureFlags || DEFAULT_FEATURE_FLAGS)[flag];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const setFeatureFlag = <F extends keyof FEATURE_FLAGS>(
|
|
||||||
flag: F,
|
|
||||||
value: FEATURE_FLAGS[F],
|
|
||||||
) => {
|
|
||||||
try {
|
|
||||||
featureFlags = {
|
|
||||||
...(featureFlags || DEFAULT_FEATURE_FLAGS),
|
|
||||||
[flag]: value,
|
|
||||||
};
|
|
||||||
localStorage.setItem(
|
|
||||||
FEATURE_FLAGS_STORAGE_KEY,
|
|
||||||
JSON.stringify(featureFlags),
|
|
||||||
);
|
|
||||||
} catch (e) {
|
|
||||||
console.error("unable to set feature flag", e);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
{
|
||||||
|
"name": "@excalidraw/deltas",
|
||||||
|
"version": "0.0.1",
|
||||||
|
"main": "./dist/prod/index.js",
|
||||||
|
"type": "module",
|
||||||
|
"module": "./dist/prod/index.js",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"development": "./dist/dev/index.js",
|
||||||
|
"default": "./dist/prod/index.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"types": "./dist/types/index.d.ts",
|
||||||
|
"files": [
|
||||||
|
"dist/*"
|
||||||
|
],
|
||||||
|
"description": "Excalidraw utilities for handling deltas",
|
||||||
|
"publishConfig": {
|
||||||
|
"access": "public"
|
||||||
|
},
|
||||||
|
"license": "MIT",
|
||||||
|
"keywords": [
|
||||||
|
"excalidraw",
|
||||||
|
"excalidraw-deltas"
|
||||||
|
],
|
||||||
|
"dependencies": {
|
||||||
|
"nanoid": "5.0.9",
|
||||||
|
"roughjs": "4.6.6"
|
||||||
|
},
|
||||||
|
"devDependencies": {},
|
||||||
|
"bugs": "https://github.com/excalidraw/excalidraw/issues",
|
||||||
|
"repository": "https://github.com/excalidraw/excalidraw",
|
||||||
|
"scripts": {
|
||||||
|
"gen:types": "rm -rf types && tsc",
|
||||||
|
"build:esm": "rm -rf dist && node ../../scripts/buildShared.js && yarn gen:types",
|
||||||
|
"pack": "yarn build:umd && yarn pack"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,357 @@
|
|||||||
|
import { arrayToObject, assertNever } from "./utils";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents the difference between two objects of the same type.
|
||||||
|
*
|
||||||
|
* Both `deleted` and `inserted` partials represent the same set of added, removed or updated properties, where:
|
||||||
|
* - `deleted` is a set of all the deleted values
|
||||||
|
* - `inserted` is a set of all the inserted (added, updated) values
|
||||||
|
*
|
||||||
|
* Keeping it as pure object (without transient state, side-effects, etc.), so we won't have to instantiate it on load.
|
||||||
|
*/
|
||||||
|
export class Delta<T> {
|
||||||
|
private constructor(
|
||||||
|
public readonly deleted: Partial<T>,
|
||||||
|
public readonly inserted: Partial<T>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public static create<T>(
|
||||||
|
deleted: Partial<T>,
|
||||||
|
inserted: Partial<T>,
|
||||||
|
modifier?: (delta: Partial<T>) => Partial<T>,
|
||||||
|
modifierOptions?: "deleted" | "inserted",
|
||||||
|
) {
|
||||||
|
const modifiedDeleted =
|
||||||
|
modifier && modifierOptions !== "inserted" ? modifier(deleted) : deleted;
|
||||||
|
const modifiedInserted =
|
||||||
|
modifier && modifierOptions !== "deleted" ? modifier(inserted) : inserted;
|
||||||
|
|
||||||
|
return new Delta(modifiedDeleted, modifiedInserted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the delta between two objects.
|
||||||
|
*
|
||||||
|
* @param prevObject - The previous state of the object.
|
||||||
|
* @param nextObject - The next state of the object.
|
||||||
|
*
|
||||||
|
* @returns new delta instance.
|
||||||
|
*/
|
||||||
|
public static calculate<T extends { [key: string]: any }>(
|
||||||
|
prevObject: T,
|
||||||
|
nextObject: T,
|
||||||
|
modifier?: (partial: Partial<T>) => Partial<T>,
|
||||||
|
postProcess?: (
|
||||||
|
deleted: Partial<T>,
|
||||||
|
inserted: Partial<T>,
|
||||||
|
) => [Partial<T>, Partial<T>],
|
||||||
|
): Delta<T> {
|
||||||
|
if (prevObject === nextObject) {
|
||||||
|
return Delta.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleted = {} as Partial<T>;
|
||||||
|
const inserted = {} as Partial<T>;
|
||||||
|
|
||||||
|
// O(n^3) here for elements, but it's not as bad as it looks:
|
||||||
|
// - we do this only on store recordings, not on every frame (not for ephemerals)
|
||||||
|
// - we do this only on previously detected changed elements
|
||||||
|
// - we do shallow compare only on the first level of properties (not going any deeper)
|
||||||
|
// - # of properties is reasonably small
|
||||||
|
for (const key of this.distinctKeysIterator(
|
||||||
|
"full",
|
||||||
|
prevObject,
|
||||||
|
nextObject,
|
||||||
|
)) {
|
||||||
|
deleted[key as keyof T] = prevObject[key];
|
||||||
|
inserted[key as keyof T] = nextObject[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [processedDeleted, processedInserted] = postProcess
|
||||||
|
? postProcess(deleted, inserted)
|
||||||
|
: [deleted, inserted];
|
||||||
|
|
||||||
|
return Delta.create(processedDeleted, processedInserted, modifier);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static empty() {
|
||||||
|
return new Delta({}, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static isEmpty<T>(delta: Delta<T>): boolean {
|
||||||
|
return (
|
||||||
|
!Object.keys(delta.deleted).length && !Object.keys(delta.inserted).length
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merges deleted and inserted object partials.
|
||||||
|
*/
|
||||||
|
public static mergeObjects<T extends { [key: string]: unknown }>(
|
||||||
|
prev: T,
|
||||||
|
added: T,
|
||||||
|
removed: T,
|
||||||
|
) {
|
||||||
|
const cloned = { ...prev };
|
||||||
|
|
||||||
|
for (const key of Object.keys(removed)) {
|
||||||
|
delete cloned[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...cloned, ...added };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Merges deleted and inserted array partials.
|
||||||
|
*/
|
||||||
|
public static mergeArrays<T>(
|
||||||
|
prev: readonly T[] | null,
|
||||||
|
added: readonly T[] | null | undefined,
|
||||||
|
removed: readonly T[] | null | undefined,
|
||||||
|
predicate?: (value: T) => string,
|
||||||
|
) {
|
||||||
|
return Object.values(
|
||||||
|
Delta.mergeObjects(
|
||||||
|
arrayToObject(prev ?? [], predicate),
|
||||||
|
arrayToObject(added ?? [], predicate),
|
||||||
|
arrayToObject(removed ?? [], predicate),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Diff object partials as part of the `postProcess`.
|
||||||
|
*/
|
||||||
|
public static diffObjects<T, K extends keyof T, V extends T[K][keyof T[K]]>(
|
||||||
|
deleted: Partial<T>,
|
||||||
|
inserted: Partial<T>,
|
||||||
|
property: K,
|
||||||
|
setValue: (prevValue: V | undefined) => V,
|
||||||
|
) {
|
||||||
|
if (!deleted[property] && !inserted[property]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
typeof deleted[property] === "object" ||
|
||||||
|
typeof inserted[property] === "object"
|
||||||
|
) {
|
||||||
|
type RecordLike = Record<string, V | undefined>;
|
||||||
|
|
||||||
|
const deletedObject: RecordLike = deleted[property] ?? {};
|
||||||
|
const insertedObject: RecordLike = inserted[property] ?? {};
|
||||||
|
|
||||||
|
const deletedDifferences = Delta.getLeftDifferences(
|
||||||
|
deletedObject,
|
||||||
|
insertedObject,
|
||||||
|
).reduce((acc, curr) => {
|
||||||
|
acc[curr] = setValue(deletedObject[curr]);
|
||||||
|
return acc;
|
||||||
|
}, {} as RecordLike);
|
||||||
|
|
||||||
|
const insertedDifferences = Delta.getRightDifferences(
|
||||||
|
deletedObject,
|
||||||
|
insertedObject,
|
||||||
|
).reduce((acc, curr) => {
|
||||||
|
acc[curr] = setValue(insertedObject[curr]);
|
||||||
|
return acc;
|
||||||
|
}, {} as RecordLike);
|
||||||
|
|
||||||
|
if (
|
||||||
|
Object.keys(deletedDifferences).length ||
|
||||||
|
Object.keys(insertedDifferences).length
|
||||||
|
) {
|
||||||
|
Reflect.set(deleted, property, deletedDifferences);
|
||||||
|
Reflect.set(inserted, property, insertedDifferences);
|
||||||
|
} else {
|
||||||
|
Reflect.deleteProperty(deleted, property);
|
||||||
|
Reflect.deleteProperty(inserted, property);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Diff array partials as part of the `postProcess`.
|
||||||
|
*/
|
||||||
|
public static diffArrays<T, K extends keyof T, V extends T[K]>(
|
||||||
|
deleted: Partial<T>,
|
||||||
|
inserted: Partial<T>,
|
||||||
|
property: K,
|
||||||
|
groupBy: (value: V extends ArrayLike<infer T> ? T : never) => string,
|
||||||
|
) {
|
||||||
|
if (!deleted[property] && !inserted[property]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(deleted[property]) || Array.isArray(inserted[property])) {
|
||||||
|
const deletedArray = (
|
||||||
|
Array.isArray(deleted[property]) ? deleted[property] : []
|
||||||
|
) as [];
|
||||||
|
const insertedArray = (
|
||||||
|
Array.isArray(inserted[property]) ? inserted[property] : []
|
||||||
|
) as [];
|
||||||
|
|
||||||
|
const deletedDifferences = arrayToObject(
|
||||||
|
Delta.getLeftDifferences(
|
||||||
|
arrayToObject(deletedArray, groupBy),
|
||||||
|
arrayToObject(insertedArray, groupBy),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const insertedDifferences = arrayToObject(
|
||||||
|
Delta.getRightDifferences(
|
||||||
|
arrayToObject(deletedArray, groupBy),
|
||||||
|
arrayToObject(insertedArray, groupBy),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
Object.keys(deletedDifferences).length ||
|
||||||
|
Object.keys(insertedDifferences).length
|
||||||
|
) {
|
||||||
|
const deletedValue = deletedArray.filter(
|
||||||
|
(x) => deletedDifferences[groupBy ? groupBy(x) : String(x)],
|
||||||
|
);
|
||||||
|
const insertedValue = insertedArray.filter(
|
||||||
|
(x) => insertedDifferences[groupBy ? groupBy(x) : String(x)],
|
||||||
|
);
|
||||||
|
|
||||||
|
Reflect.set(deleted, property, deletedValue);
|
||||||
|
Reflect.set(inserted, property, insertedValue);
|
||||||
|
} else {
|
||||||
|
Reflect.deleteProperty(deleted, property);
|
||||||
|
Reflect.deleteProperty(inserted, property);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compares if object1 contains any different value compared to the object2.
|
||||||
|
*/
|
||||||
|
public static isLeftDifferent<T extends {}>(
|
||||||
|
object1: T,
|
||||||
|
object2: T,
|
||||||
|
skipShallowCompare = false,
|
||||||
|
): boolean {
|
||||||
|
const anyDistinctKey = this.distinctKeysIterator(
|
||||||
|
"left",
|
||||||
|
object1,
|
||||||
|
object2,
|
||||||
|
skipShallowCompare,
|
||||||
|
).next().value;
|
||||||
|
|
||||||
|
return !!anyDistinctKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compares if object2 contains any different value compared to the object1.
|
||||||
|
*/
|
||||||
|
public static isRightDifferent<T extends {}>(
|
||||||
|
object1: T,
|
||||||
|
object2: T,
|
||||||
|
skipShallowCompare = false,
|
||||||
|
): boolean {
|
||||||
|
const anyDistinctKey = this.distinctKeysIterator(
|
||||||
|
"right",
|
||||||
|
object1,
|
||||||
|
object2,
|
||||||
|
skipShallowCompare,
|
||||||
|
).next().value;
|
||||||
|
|
||||||
|
return !!anyDistinctKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns all the object1 keys that have distinct values.
|
||||||
|
*/
|
||||||
|
public static getLeftDifferences<T extends {}>(
|
||||||
|
object1: T,
|
||||||
|
object2: T,
|
||||||
|
skipShallowCompare = false,
|
||||||
|
) {
|
||||||
|
return Array.from(
|
||||||
|
this.distinctKeysIterator("left", object1, object2, skipShallowCompare),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns all the object2 keys that have distinct values.
|
||||||
|
*/
|
||||||
|
public static getRightDifferences<T extends {}>(
|
||||||
|
object1: T,
|
||||||
|
object2: T,
|
||||||
|
skipShallowCompare = false,
|
||||||
|
) {
|
||||||
|
return Array.from(
|
||||||
|
this.distinctKeysIterator("right", object1, object2, skipShallowCompare),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Iterator comparing values of object properties based on the passed joining strategy.
|
||||||
|
*
|
||||||
|
* @yields keys of properties with different values
|
||||||
|
*
|
||||||
|
* WARN: it's based on shallow compare performed only on the first level and doesn't go deeper than that.
|
||||||
|
*/
|
||||||
|
private static *distinctKeysIterator<T extends {}>(
|
||||||
|
join: "left" | "right" | "full",
|
||||||
|
object1: T,
|
||||||
|
object2: T,
|
||||||
|
skipShallowCompare = false,
|
||||||
|
) {
|
||||||
|
if (object1 === object2) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let keys: string[] = [];
|
||||||
|
|
||||||
|
if (join === "left") {
|
||||||
|
keys = Object.keys(object1);
|
||||||
|
} else if (join === "right") {
|
||||||
|
keys = Object.keys(object2);
|
||||||
|
} else if (join === "full") {
|
||||||
|
keys = Array.from(
|
||||||
|
new Set([...Object.keys(object1), ...Object.keys(object2)]),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
assertNever(join, "Unknown distinctKeysIterator's join param");
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const key of keys) {
|
||||||
|
const object1Value = object1[key as keyof T];
|
||||||
|
const object2Value = object2[key as keyof T];
|
||||||
|
|
||||||
|
if (object1Value !== object2Value) {
|
||||||
|
if (
|
||||||
|
!skipShallowCompare &&
|
||||||
|
typeof object1Value === "object" &&
|
||||||
|
typeof object2Value === "object" &&
|
||||||
|
object1Value !== null &&
|
||||||
|
object2Value !== null &&
|
||||||
|
this.isShallowEqual(object1Value, object2Value)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
yield key;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static isShallowEqual(object1: any, object2: any) {
|
||||||
|
const keys1 = Object.keys(object1);
|
||||||
|
const keys2 = Object.keys(object1);
|
||||||
|
|
||||||
|
if (keys1.length !== keys2.length) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const key of keys1) {
|
||||||
|
if (object1[key] !== object2[key]) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/**
|
||||||
|
* Encapsulates a set of application-level `Delta`s.
|
||||||
|
*/
|
||||||
|
export interface DeltaContainer<T> {
|
||||||
|
/**
|
||||||
|
* Inverses the `Delta`s while creating a new `DeltaContainer` instance.
|
||||||
|
*/
|
||||||
|
inverse(): DeltaContainer<T>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Applies the `Delta`s to the previous object.
|
||||||
|
*
|
||||||
|
* @returns a tuple of the next object `T` with applied `Delta`s, and `boolean`, indicating whether the applied deltas resulted in a visible change.
|
||||||
|
*/
|
||||||
|
applyTo(previous: T, ...options: unknown[]): [T, boolean];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks whether all `Delta`s are empty.
|
||||||
|
*/
|
||||||
|
isEmpty(): boolean;
|
||||||
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import { Random } from "roughjs/bin/math";
|
||||||
|
import { nanoid } from "nanoid";
|
||||||
|
|
||||||
|
import type {
|
||||||
|
AppState,
|
||||||
|
ObservedAppState,
|
||||||
|
ElementsMap,
|
||||||
|
ExcalidrawElement,
|
||||||
|
ElementUpdate,
|
||||||
|
} from "../excalidraw-types";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transform array into an object, use only when array order is irrelevant.
|
||||||
|
*/
|
||||||
|
export const arrayToObject = <T>(
|
||||||
|
array: readonly T[],
|
||||||
|
groupBy?: (value: T) => string | number,
|
||||||
|
) =>
|
||||||
|
array.reduce((acc, value) => {
|
||||||
|
acc[groupBy ? groupBy(value) : String(value)] = value;
|
||||||
|
return acc;
|
||||||
|
}, {} as { [key: string]: T });
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Transforms array of elements with `id` property into into a Map grouped by `id`.
|
||||||
|
*/
|
||||||
|
export const elementsToMap = <T extends { id: string }>(
|
||||||
|
items: readonly T[],
|
||||||
|
) => {
|
||||||
|
return items.reduce((acc: Map<string, T>, element) => {
|
||||||
|
acc.set(element.id, element);
|
||||||
|
return acc;
|
||||||
|
}, new Map());
|
||||||
|
};
|
||||||
|
|
||||||
|
// --
|
||||||
|
|
||||||
|
// hidden non-enumerable property for runtime checks
|
||||||
|
const hiddenObservedAppStateProp = "__observedAppState";
|
||||||
|
|
||||||
|
export const getObservedAppState = (appState: AppState): ObservedAppState => {
|
||||||
|
const observedAppState = {
|
||||||
|
name: appState.name,
|
||||||
|
editingGroupId: appState.editingGroupId,
|
||||||
|
viewBackgroundColor: appState.viewBackgroundColor,
|
||||||
|
selectedElementIds: appState.selectedElementIds,
|
||||||
|
selectedGroupIds: appState.selectedGroupIds,
|
||||||
|
editingLinearElementId: appState.editingLinearElement?.elementId || null,
|
||||||
|
selectedLinearElementId: appState.selectedLinearElement?.elementId || null,
|
||||||
|
croppingElementId: appState.croppingElementId,
|
||||||
|
};
|
||||||
|
|
||||||
|
Reflect.defineProperty(observedAppState, hiddenObservedAppStateProp, {
|
||||||
|
value: true,
|
||||||
|
enumerable: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
return observedAppState;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
export const assertNever = (value: never, message: string): never => {
|
||||||
|
throw new Error(`${message}: "${value}".`);
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
export const getNonDeletedGroupIds = (elements: ElementsMap) => {
|
||||||
|
const nonDeletedGroupIds = new Set<string>();
|
||||||
|
|
||||||
|
for (const [, element] of elements) {
|
||||||
|
// defensive check
|
||||||
|
if (element.isDeleted) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// defensive fallback
|
||||||
|
for (const groupId of element.groupIds ?? []) {
|
||||||
|
nonDeletedGroupIds.add(groupId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nonDeletedGroupIds;
|
||||||
|
};
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
export const isTestEnv = () => import.meta.env.MODE === "test";
|
||||||
|
|
||||||
|
export const isDevEnv = () => import.meta.env.MODE === "development";
|
||||||
|
|
||||||
|
export const isServerEnv = () => import.meta.env.MODE === "server";
|
||||||
|
|
||||||
|
export const shouldThrow = () => isDevEnv() || isTestEnv() || isServerEnv();
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
let random = new Random(Date.now());
|
||||||
|
let testIdBase = 0;
|
||||||
|
|
||||||
|
export const randomInteger = () => Math.floor(random.next() * 2 ** 31);
|
||||||
|
|
||||||
|
export const reseed = (seed: number) => {
|
||||||
|
random = new Random(seed);
|
||||||
|
testIdBase = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const randomId = () => (isTestEnv() ? `id${testIdBase++}` : nanoid());
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
export const getUpdatedTimestamp = () => (isTestEnv() ? 1 : Date.now());
|
||||||
|
|
||||||
|
// ------------------------------------------------------------
|
||||||
|
|
||||||
|
export const newElementWith = <TElement extends ExcalidrawElement>(
|
||||||
|
element: TElement,
|
||||||
|
updates: ElementUpdate<TElement>,
|
||||||
|
/** pass `true` to always regenerate */
|
||||||
|
force = false,
|
||||||
|
): TElement => {
|
||||||
|
let didChange = false;
|
||||||
|
for (const key in updates) {
|
||||||
|
const value = (updates as any)[key];
|
||||||
|
if (typeof value !== "undefined") {
|
||||||
|
if (
|
||||||
|
(element as any)[key] === value &&
|
||||||
|
// if object, always update because its attrs could have changed
|
||||||
|
(typeof value !== "object" || value === null)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
didChange = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!didChange && !force) {
|
||||||
|
return element;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...element,
|
||||||
|
...updates,
|
||||||
|
updated: getUpdatedTimestamp(),
|
||||||
|
version: element.version + 1,
|
||||||
|
versionNonce: randomInteger(),
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,404 @@
|
|||||||
|
import { Delta } from "../common/delta";
|
||||||
|
import {
|
||||||
|
assertNever,
|
||||||
|
getNonDeletedGroupIds,
|
||||||
|
getObservedAppState,
|
||||||
|
isDevEnv,
|
||||||
|
isTestEnv,
|
||||||
|
shouldThrow,
|
||||||
|
} from "../common/utils";
|
||||||
|
|
||||||
|
import type { DeltaContainer } from "../common/interfaces";
|
||||||
|
import type {
|
||||||
|
AppState,
|
||||||
|
ObservedAppState,
|
||||||
|
DTO,
|
||||||
|
SceneElementsMap,
|
||||||
|
ValueOf,
|
||||||
|
ObservedElementsAppState,
|
||||||
|
ObservedStandaloneAppState,
|
||||||
|
SubtypeOf,
|
||||||
|
} from "../excalidraw-types";
|
||||||
|
|
||||||
|
export class AppStateDelta implements DeltaContainer<AppState> {
|
||||||
|
private constructor(public readonly delta: Delta<ObservedAppState>) {}
|
||||||
|
|
||||||
|
public static calculate<T extends ObservedAppState>(
|
||||||
|
prevAppState: T,
|
||||||
|
nextAppState: T,
|
||||||
|
): AppStateDelta {
|
||||||
|
const delta = Delta.calculate(
|
||||||
|
prevAppState,
|
||||||
|
nextAppState,
|
||||||
|
undefined,
|
||||||
|
AppStateDelta.postProcess,
|
||||||
|
);
|
||||||
|
|
||||||
|
return new AppStateDelta(delta);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static restore(appStateDeltaDTO: DTO<AppStateDelta>): AppStateDelta {
|
||||||
|
const { delta } = appStateDeltaDTO;
|
||||||
|
return new AppStateDelta(delta);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static empty() {
|
||||||
|
return new AppStateDelta(Delta.create({}, {}));
|
||||||
|
}
|
||||||
|
|
||||||
|
public inverse(): AppStateDelta {
|
||||||
|
const inversedDelta = Delta.create(this.delta.inserted, this.delta.deleted);
|
||||||
|
return new AppStateDelta(inversedDelta);
|
||||||
|
}
|
||||||
|
|
||||||
|
public applyTo(
|
||||||
|
appState: AppState,
|
||||||
|
nextElements: SceneElementsMap,
|
||||||
|
): [AppState, boolean] {
|
||||||
|
try {
|
||||||
|
const {
|
||||||
|
selectedElementIds: removedSelectedElementIds = {},
|
||||||
|
selectedGroupIds: removedSelectedGroupIds = {},
|
||||||
|
} = this.delta.deleted;
|
||||||
|
|
||||||
|
const {
|
||||||
|
selectedElementIds: addedSelectedElementIds = {},
|
||||||
|
selectedGroupIds: addedSelectedGroupIds = {},
|
||||||
|
selectedLinearElementId,
|
||||||
|
editingLinearElementId,
|
||||||
|
...directlyApplicablePartial
|
||||||
|
} = this.delta.inserted;
|
||||||
|
|
||||||
|
const mergedSelectedElementIds = Delta.mergeObjects(
|
||||||
|
appState.selectedElementIds,
|
||||||
|
addedSelectedElementIds,
|
||||||
|
removedSelectedElementIds,
|
||||||
|
);
|
||||||
|
|
||||||
|
const mergedSelectedGroupIds = Delta.mergeObjects(
|
||||||
|
appState.selectedGroupIds,
|
||||||
|
addedSelectedGroupIds,
|
||||||
|
removedSelectedGroupIds,
|
||||||
|
);
|
||||||
|
|
||||||
|
// const selectedLinearElement =
|
||||||
|
// selectedLinearElementId && nextElements.has(selectedLinearElementId)
|
||||||
|
// ? new LinearElementEditor(
|
||||||
|
// nextElements.get(
|
||||||
|
// selectedLinearElementId,
|
||||||
|
// ) as NonDeleted<ExcalidrawLinearElement>,
|
||||||
|
// )
|
||||||
|
// : null;
|
||||||
|
|
||||||
|
// const editingLinearElement =
|
||||||
|
// editingLinearElementId && nextElements.has(editingLinearElementId)
|
||||||
|
// ? new LinearElementEditor(
|
||||||
|
// nextElements.get(
|
||||||
|
// editingLinearElementId,
|
||||||
|
// ) as NonDeleted<ExcalidrawLinearElement>,
|
||||||
|
// )
|
||||||
|
// : null;
|
||||||
|
|
||||||
|
const nextAppState = {
|
||||||
|
...appState,
|
||||||
|
...directlyApplicablePartial,
|
||||||
|
selectedElementIds: mergedSelectedElementIds,
|
||||||
|
selectedGroupIds: mergedSelectedGroupIds,
|
||||||
|
// selectedLinearElement:
|
||||||
|
// typeof selectedLinearElementId !== "undefined"
|
||||||
|
// ? selectedLinearElement // element was either inserted or deleted
|
||||||
|
// : appState.selectedLinearElement, // otherwise assign what we had before
|
||||||
|
// editingLinearElement:
|
||||||
|
// typeof editingLinearElementId !== "undefined"
|
||||||
|
// ? editingLinearElement // element was either inserted or deleted
|
||||||
|
// : appState.editingLinearElement, // otherwise assign what we had before
|
||||||
|
};
|
||||||
|
|
||||||
|
const constainsVisibleChanges = this.filterInvisibleChanges(
|
||||||
|
appState,
|
||||||
|
nextAppState,
|
||||||
|
nextElements,
|
||||||
|
);
|
||||||
|
|
||||||
|
return [nextAppState, constainsVisibleChanges];
|
||||||
|
} catch (e) {
|
||||||
|
// shouldn't really happen, but just in case
|
||||||
|
console.error(`Couldn't apply appstate delta`, e);
|
||||||
|
|
||||||
|
if (shouldThrow()) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
return [appState, false];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public isEmpty(): boolean {
|
||||||
|
return Delta.isEmpty(this.delta);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* It is necessary to post process the partials in case of reference values,
|
||||||
|
* for which we need to calculate the real diff between `deleted` and `inserted`.
|
||||||
|
*/
|
||||||
|
private static postProcess<T extends ObservedAppState>(
|
||||||
|
deleted: Partial<T>,
|
||||||
|
inserted: Partial<T>,
|
||||||
|
): [Partial<T>, Partial<T>] {
|
||||||
|
try {
|
||||||
|
Delta.diffObjects(
|
||||||
|
deleted,
|
||||||
|
inserted,
|
||||||
|
"selectedElementIds",
|
||||||
|
// ts language server has a bit trouble resolving this, so we are giving it a little push
|
||||||
|
(_) => true as ValueOf<T["selectedElementIds"]>,
|
||||||
|
);
|
||||||
|
Delta.diffObjects(
|
||||||
|
deleted,
|
||||||
|
inserted,
|
||||||
|
"selectedGroupIds",
|
||||||
|
(prevValue) => (prevValue ?? false) as ValueOf<T["selectedGroupIds"]>,
|
||||||
|
);
|
||||||
|
} catch (e) {
|
||||||
|
// if postprocessing fails it does not make sense to bubble up, but let's make sure we know about it
|
||||||
|
console.error(`Couldn't postprocess appstate change deltas.`);
|
||||||
|
|
||||||
|
if (isDevEnv() || isTestEnv()) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
return [deleted, inserted];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mutates `nextAppState` be filtering out state related to deleted elements.
|
||||||
|
*
|
||||||
|
* @returns `true` if a visible change is found, `false` otherwise.
|
||||||
|
*/
|
||||||
|
private filterInvisibleChanges(
|
||||||
|
prevAppState: AppState,
|
||||||
|
nextAppState: AppState,
|
||||||
|
nextElements: SceneElementsMap,
|
||||||
|
): boolean {
|
||||||
|
// TODO: #7348 we could still get an empty undo/redo, as we assume that previous appstate does not contain references to deleted elements
|
||||||
|
// which is not always true - i.e. now we do cleanup appstate during history, but we do not do it during remote updates
|
||||||
|
const prevObservedAppState = getObservedAppState(prevAppState);
|
||||||
|
const nextObservedAppState = getObservedAppState(nextAppState);
|
||||||
|
|
||||||
|
const containsStandaloneDifference = Delta.isRightDifferent(
|
||||||
|
AppStateDelta.stripElementsProps(prevObservedAppState),
|
||||||
|
AppStateDelta.stripElementsProps(nextObservedAppState),
|
||||||
|
);
|
||||||
|
|
||||||
|
const containsElementsDifference = Delta.isRightDifferent(
|
||||||
|
AppStateDelta.stripStandaloneProps(prevObservedAppState),
|
||||||
|
AppStateDelta.stripStandaloneProps(nextObservedAppState),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!containsStandaloneDifference && !containsElementsDifference) {
|
||||||
|
// no change in appstate was detected
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const visibleDifferenceFlag = {
|
||||||
|
value: containsStandaloneDifference,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (containsElementsDifference) {
|
||||||
|
// filter invisible changes on each iteration
|
||||||
|
const changedElementsProps = Delta.getRightDifferences(
|
||||||
|
AppStateDelta.stripStandaloneProps(prevObservedAppState),
|
||||||
|
AppStateDelta.stripStandaloneProps(nextObservedAppState),
|
||||||
|
) as Array<keyof ObservedElementsAppState>;
|
||||||
|
|
||||||
|
let nonDeletedGroupIds = new Set<string>();
|
||||||
|
|
||||||
|
if (
|
||||||
|
changedElementsProps.includes("editingGroupId") ||
|
||||||
|
changedElementsProps.includes("selectedGroupIds")
|
||||||
|
) {
|
||||||
|
// this one iterates through all the non deleted elements, so make sure it's not done twice
|
||||||
|
nonDeletedGroupIds = getNonDeletedGroupIds(nextElements);
|
||||||
|
}
|
||||||
|
|
||||||
|
// check whether delta properties are related to the existing non-deleted elements
|
||||||
|
for (const key of changedElementsProps) {
|
||||||
|
switch (key) {
|
||||||
|
case "selectedElementIds":
|
||||||
|
nextAppState[key] = AppStateDelta.filterSelectedElements(
|
||||||
|
nextAppState[key],
|
||||||
|
nextElements,
|
||||||
|
visibleDifferenceFlag,
|
||||||
|
);
|
||||||
|
|
||||||
|
break;
|
||||||
|
case "selectedGroupIds":
|
||||||
|
nextAppState[key] = AppStateDelta.filterSelectedGroups(
|
||||||
|
nextAppState[key],
|
||||||
|
nonDeletedGroupIds,
|
||||||
|
visibleDifferenceFlag,
|
||||||
|
);
|
||||||
|
|
||||||
|
break;
|
||||||
|
case "croppingElementId": {
|
||||||
|
const croppingElementId = nextAppState[key];
|
||||||
|
const element =
|
||||||
|
croppingElementId && nextElements.get(croppingElementId);
|
||||||
|
|
||||||
|
if (element && !element.isDeleted) {
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
} else {
|
||||||
|
nextAppState[key] = null;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "editingGroupId":
|
||||||
|
const editingGroupId = nextAppState[key];
|
||||||
|
|
||||||
|
if (!editingGroupId) {
|
||||||
|
// previously there was an editingGroup (assuming visible), now there is none
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
} else if (nonDeletedGroupIds.has(editingGroupId)) {
|
||||||
|
// previously there wasn't an editingGroup, now there is one which is visible
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
} else {
|
||||||
|
// there was assigned an editingGroup now, but it's related to deleted element
|
||||||
|
nextAppState[key] = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case "selectedLinearElementId":
|
||||||
|
case "editingLinearElementId":
|
||||||
|
const appStateKey = AppStateDelta.convertToAppStateKey(key);
|
||||||
|
const linearElement = nextAppState[appStateKey];
|
||||||
|
|
||||||
|
if (!linearElement) {
|
||||||
|
// previously there was a linear element (assuming visible), now there is none
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
} else {
|
||||||
|
const element = nextElements.get(linearElement.elementId);
|
||||||
|
|
||||||
|
if (element && !element.isDeleted) {
|
||||||
|
// previously there wasn't a linear element, now there is one which is visible
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
} else {
|
||||||
|
// there was assigned a linear element now, but it's deleted
|
||||||
|
nextAppState[appStateKey] = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
default: {
|
||||||
|
assertNever(key, `Unknown ObservedElementsAppState's key "${key}"`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return visibleDifferenceFlag.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static convertToAppStateKey(
|
||||||
|
key: keyof Pick<
|
||||||
|
ObservedElementsAppState,
|
||||||
|
"selectedLinearElementId" | "editingLinearElementId"
|
||||||
|
>,
|
||||||
|
): keyof Pick<AppState, "selectedLinearElement" | "editingLinearElement"> {
|
||||||
|
switch (key) {
|
||||||
|
case "selectedLinearElementId":
|
||||||
|
return "selectedLinearElement";
|
||||||
|
case "editingLinearElementId":
|
||||||
|
return "editingLinearElement";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static filterSelectedElements(
|
||||||
|
selectedElementIds: AppState["selectedElementIds"],
|
||||||
|
elements: SceneElementsMap,
|
||||||
|
visibleDifferenceFlag: { value: boolean },
|
||||||
|
) {
|
||||||
|
const ids = Object.keys(selectedElementIds);
|
||||||
|
|
||||||
|
if (!ids.length) {
|
||||||
|
// previously there were ids (assuming related to visible elements), now there are none
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
return selectedElementIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextSelectedElementIds = { ...selectedElementIds };
|
||||||
|
|
||||||
|
for (const id of ids) {
|
||||||
|
const element = elements.get(id);
|
||||||
|
|
||||||
|
if (element && !element.isDeleted) {
|
||||||
|
// there is a selected element id related to a visible element
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
} else {
|
||||||
|
delete nextSelectedElementIds[id];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nextSelectedElementIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static filterSelectedGroups(
|
||||||
|
selectedGroupIds: AppState["selectedGroupIds"],
|
||||||
|
nonDeletedGroupIds: Set<string>,
|
||||||
|
visibleDifferenceFlag: { value: boolean },
|
||||||
|
) {
|
||||||
|
const ids = Object.keys(selectedGroupIds);
|
||||||
|
|
||||||
|
if (!ids.length) {
|
||||||
|
// previously there were ids (assuming related to visible groups), now there are none
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
return selectedGroupIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nextSelectedGroupIds = { ...selectedGroupIds };
|
||||||
|
|
||||||
|
for (const id of Object.keys(nextSelectedGroupIds)) {
|
||||||
|
if (nonDeletedGroupIds.has(id)) {
|
||||||
|
// there is a selected group id related to a visible group
|
||||||
|
visibleDifferenceFlag.value = true;
|
||||||
|
} else {
|
||||||
|
delete nextSelectedGroupIds[id];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nextSelectedGroupIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static stripElementsProps(
|
||||||
|
delta: Partial<ObservedAppState>,
|
||||||
|
): Partial<ObservedStandaloneAppState> {
|
||||||
|
// WARN: Do not remove the type-casts as they here to ensure proper type checks
|
||||||
|
const {
|
||||||
|
editingGroupId,
|
||||||
|
selectedGroupIds,
|
||||||
|
selectedElementIds,
|
||||||
|
editingLinearElementId,
|
||||||
|
selectedLinearElementId,
|
||||||
|
croppingElementId,
|
||||||
|
...standaloneProps
|
||||||
|
} = delta as ObservedAppState;
|
||||||
|
|
||||||
|
return standaloneProps as SubtypeOf<
|
||||||
|
typeof standaloneProps,
|
||||||
|
ObservedStandaloneAppState
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static stripStandaloneProps(
|
||||||
|
delta: Partial<ObservedAppState>,
|
||||||
|
): Partial<ObservedElementsAppState> {
|
||||||
|
// WARN: Do not remove the type-casts as they here to ensure proper type checks
|
||||||
|
const { name, viewBackgroundColor, ...elementsProps } =
|
||||||
|
delta as ObservedAppState;
|
||||||
|
|
||||||
|
return elementsProps as SubtypeOf<
|
||||||
|
typeof elementsProps,
|
||||||
|
ObservedElementsAppState
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,825 @@
|
|||||||
|
import { Delta } from "../common/delta";
|
||||||
|
import { newElementWith, shouldThrow } from "../common/utils";
|
||||||
|
|
||||||
|
import type { DeltaContainer } from "../common/interfaces";
|
||||||
|
import type {
|
||||||
|
ExcalidrawElement,
|
||||||
|
ElementUpdate,
|
||||||
|
Ordered,
|
||||||
|
SceneElementsMap,
|
||||||
|
DTO,
|
||||||
|
OrderedExcalidrawElement,
|
||||||
|
ExcalidrawImageElement,
|
||||||
|
} from "../excalidraw-types";
|
||||||
|
|
||||||
|
// CFDO: consider adding here (nonnullable) version & versionNonce & updated (so that we have correct versions when recunstructing from remote)
|
||||||
|
type ElementPartial<T extends ExcalidrawElement = ExcalidrawElement> =
|
||||||
|
ElementUpdate<Ordered<T>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Elements delta is a low level primitive to encapsulate property changes between two sets of elements.
|
||||||
|
* It does so by encapsulating forward and backward `Delta`s, allowing to time-travel in both directions.
|
||||||
|
*/
|
||||||
|
export class ElementsDelta implements DeltaContainer<SceneElementsMap> {
|
||||||
|
private constructor(
|
||||||
|
public readonly added: Record<string, Delta<ElementPartial>>,
|
||||||
|
public readonly removed: Record<string, Delta<ElementPartial>>,
|
||||||
|
public readonly updated: Record<string, Delta<ElementPartial>>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
public static create(
|
||||||
|
added: Record<string, Delta<ElementPartial>>,
|
||||||
|
removed: Record<string, Delta<ElementPartial>>,
|
||||||
|
updated: Record<string, Delta<ElementPartial>>,
|
||||||
|
options: {
|
||||||
|
shouldRedistribute: boolean;
|
||||||
|
} = {
|
||||||
|
shouldRedistribute: false,
|
||||||
|
// CFDO: don't forget to re-enable
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const { shouldRedistribute } = options;
|
||||||
|
let delta: ElementsDelta;
|
||||||
|
|
||||||
|
if (shouldRedistribute) {
|
||||||
|
const nextAdded: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
const nextRemoved: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
const nextUpdated: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
|
||||||
|
const deltas = [
|
||||||
|
...Object.entries(added),
|
||||||
|
...Object.entries(removed),
|
||||||
|
...Object.entries(updated),
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const [id, delta] of deltas) {
|
||||||
|
if (this.satisfiesAddition(delta)) {
|
||||||
|
nextAdded[id] = delta;
|
||||||
|
} else if (this.satisfiesRemoval(delta)) {
|
||||||
|
nextRemoved[id] = delta;
|
||||||
|
} else {
|
||||||
|
nextUpdated[id] = delta;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
delta = new ElementsDelta(nextAdded, nextRemoved, nextUpdated);
|
||||||
|
} else {
|
||||||
|
delta = new ElementsDelta(added, removed, updated);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shouldThrow()) {
|
||||||
|
ElementsDelta.validate(delta, "added", this.satisfiesAddition);
|
||||||
|
ElementsDelta.validate(delta, "removed", this.satisfiesRemoval);
|
||||||
|
ElementsDelta.validate(delta, "updated", this.satisfiesUpdate);
|
||||||
|
}
|
||||||
|
|
||||||
|
return delta;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static restore(elementsDeltaDTO: DTO<ElementsDelta>): ElementsDelta {
|
||||||
|
const { added, removed, updated } = elementsDeltaDTO;
|
||||||
|
return ElementsDelta.create(added, removed, updated);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static satisfiesAddition = ({
|
||||||
|
deleted,
|
||||||
|
inserted,
|
||||||
|
}: Delta<ElementPartial>) =>
|
||||||
|
// dissallowing added as "deleted", which could cause issues when resolving conflicts
|
||||||
|
deleted.isDeleted === true && !inserted.isDeleted;
|
||||||
|
|
||||||
|
private static satisfiesRemoval = ({
|
||||||
|
deleted,
|
||||||
|
inserted,
|
||||||
|
}: Delta<ElementPartial>) =>
|
||||||
|
!deleted.isDeleted && inserted.isDeleted === true;
|
||||||
|
|
||||||
|
private static satisfiesUpdate = ({
|
||||||
|
deleted,
|
||||||
|
inserted,
|
||||||
|
}: Delta<ElementPartial>) => !!deleted.isDeleted === !!inserted.isDeleted;
|
||||||
|
|
||||||
|
private static validate(
|
||||||
|
elementsDelta: ElementsDelta,
|
||||||
|
type: "added" | "removed" | "updated",
|
||||||
|
satifies: (delta: Delta<ElementPartial>) => boolean,
|
||||||
|
) {
|
||||||
|
for (const [id, delta] of Object.entries(elementsDelta[type])) {
|
||||||
|
if (!satifies(delta)) {
|
||||||
|
console.error(
|
||||||
|
`Broken invariant for "${type}" delta, element "${id}", delta:`,
|
||||||
|
delta,
|
||||||
|
);
|
||||||
|
throw new Error(`ElementsDelta invariant broken for element "${id}".`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Calculates the `Delta`s between the previous and next set of elements.
|
||||||
|
*
|
||||||
|
* @param prevElements - Map representing the previous state of elements.
|
||||||
|
* @param nextElements - Map representing the next state of elements.
|
||||||
|
*
|
||||||
|
* @returns `ElementsDelta` instance representing the `Delta` changes between the two sets of elements.
|
||||||
|
*/
|
||||||
|
public static calculate<T extends OrderedExcalidrawElement>(
|
||||||
|
prevElements: Map<string, T>,
|
||||||
|
nextElements: Map<string, T>,
|
||||||
|
): ElementsDelta {
|
||||||
|
if (prevElements === nextElements) {
|
||||||
|
return ElementsDelta.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
const added: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
const removed: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
const updated: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
|
||||||
|
// this might be needed only in same edge cases, like during collab, when `isDeleted` elements get removed or when we (un)intentionally remove the elements
|
||||||
|
for (const prevElement of prevElements.values()) {
|
||||||
|
const nextElement = nextElements.get(prevElement.id);
|
||||||
|
|
||||||
|
if (!nextElement) {
|
||||||
|
const deleted = { ...prevElement, isDeleted: false } as ElementPartial;
|
||||||
|
const inserted = { isDeleted: true } as ElementPartial;
|
||||||
|
|
||||||
|
const delta = Delta.create(
|
||||||
|
deleted,
|
||||||
|
inserted,
|
||||||
|
ElementsDelta.stripIrrelevantProps,
|
||||||
|
);
|
||||||
|
|
||||||
|
removed[prevElement.id] = delta;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const nextElement of nextElements.values()) {
|
||||||
|
const prevElement = prevElements.get(nextElement.id);
|
||||||
|
|
||||||
|
if (!prevElement) {
|
||||||
|
const deleted = { isDeleted: true } as ElementPartial;
|
||||||
|
const inserted = {
|
||||||
|
...nextElement,
|
||||||
|
isDeleted: false,
|
||||||
|
} as ElementPartial;
|
||||||
|
|
||||||
|
const delta = Delta.create(
|
||||||
|
deleted,
|
||||||
|
inserted,
|
||||||
|
ElementsDelta.stripIrrelevantProps,
|
||||||
|
);
|
||||||
|
|
||||||
|
added[nextElement.id] = delta;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (prevElement.versionNonce !== nextElement.versionNonce) {
|
||||||
|
const delta = Delta.calculate<ElementPartial>(
|
||||||
|
prevElement,
|
||||||
|
nextElement,
|
||||||
|
ElementsDelta.stripIrrelevantProps,
|
||||||
|
ElementsDelta.postProcess,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (
|
||||||
|
// making sure we don't get here some non-boolean values (i.e. undefined, null, etc.)
|
||||||
|
typeof prevElement.isDeleted === "boolean" &&
|
||||||
|
typeof nextElement.isDeleted === "boolean" &&
|
||||||
|
prevElement.isDeleted !== nextElement.isDeleted
|
||||||
|
) {
|
||||||
|
// notice that other props could have been updated as well
|
||||||
|
if (prevElement.isDeleted && !nextElement.isDeleted) {
|
||||||
|
added[nextElement.id] = delta;
|
||||||
|
} else {
|
||||||
|
removed[nextElement.id] = delta;
|
||||||
|
}
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// making sure there are at least some changes
|
||||||
|
if (!Delta.isEmpty(delta)) {
|
||||||
|
updated[nextElement.id] = delta;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ElementsDelta.create(added, removed, updated);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static empty() {
|
||||||
|
return ElementsDelta.create({}, {}, {});
|
||||||
|
}
|
||||||
|
|
||||||
|
public inverse(): ElementsDelta {
|
||||||
|
const inverseInternal = (deltas: Record<string, Delta<ElementPartial>>) => {
|
||||||
|
const inversedDeltas: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
|
||||||
|
for (const [id, delta] of Object.entries(deltas)) {
|
||||||
|
inversedDeltas[id] = Delta.create(delta.inserted, delta.deleted);
|
||||||
|
}
|
||||||
|
|
||||||
|
return inversedDeltas;
|
||||||
|
};
|
||||||
|
|
||||||
|
const added = inverseInternal(this.added);
|
||||||
|
const removed = inverseInternal(this.removed);
|
||||||
|
const updated = inverseInternal(this.updated);
|
||||||
|
|
||||||
|
// notice we inverse removed with added not to break the invariants
|
||||||
|
// notice we force generate a new id
|
||||||
|
return ElementsDelta.create(removed, added, updated);
|
||||||
|
}
|
||||||
|
|
||||||
|
public isEmpty(): boolean {
|
||||||
|
return (
|
||||||
|
Object.keys(this.added).length === 0 &&
|
||||||
|
Object.keys(this.removed).length === 0 &&
|
||||||
|
Object.keys(this.updated).length === 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update delta/s based on the existing elements.
|
||||||
|
*
|
||||||
|
* @param elements current elements
|
||||||
|
* @param modifierOptions defines which of the delta (`deleted` or `inserted`) will be updated
|
||||||
|
* @returns new instance with modified delta/s
|
||||||
|
*/
|
||||||
|
public applyLatestChanges(
|
||||||
|
elements: SceneElementsMap,
|
||||||
|
modifierOptions: "deleted" | "inserted",
|
||||||
|
): ElementsDelta {
|
||||||
|
const modifier =
|
||||||
|
(element: OrderedExcalidrawElement) => (partial: ElementPartial) => {
|
||||||
|
const latestPartial: { [key: string]: unknown } = {};
|
||||||
|
|
||||||
|
for (const key of Object.keys(partial) as Array<keyof typeof partial>) {
|
||||||
|
// do not update following props:
|
||||||
|
// - `boundElements`, as it is a reference value which is postprocessed to contain only deleted/inserted keys
|
||||||
|
switch (key) {
|
||||||
|
case "boundElements":
|
||||||
|
latestPartial[key] = partial[key];
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
latestPartial[key] = element[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return latestPartial;
|
||||||
|
};
|
||||||
|
|
||||||
|
const applyLatestChangesInternal = (
|
||||||
|
deltas: Record<string, Delta<ElementPartial>>,
|
||||||
|
) => {
|
||||||
|
const modifiedDeltas: Record<string, Delta<ElementPartial>> = {};
|
||||||
|
|
||||||
|
for (const [id, delta] of Object.entries(deltas)) {
|
||||||
|
const existingElement = elements.get(id);
|
||||||
|
|
||||||
|
if (existingElement) {
|
||||||
|
const modifiedDelta = Delta.create(
|
||||||
|
delta.deleted,
|
||||||
|
delta.inserted,
|
||||||
|
modifier(existingElement),
|
||||||
|
modifierOptions,
|
||||||
|
);
|
||||||
|
|
||||||
|
modifiedDeltas[id] = modifiedDelta;
|
||||||
|
} else {
|
||||||
|
modifiedDeltas[id] = delta;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return modifiedDeltas;
|
||||||
|
};
|
||||||
|
|
||||||
|
const added = applyLatestChangesInternal(this.added);
|
||||||
|
const removed = applyLatestChangesInternal(this.removed);
|
||||||
|
const updated = applyLatestChangesInternal(this.updated);
|
||||||
|
|
||||||
|
return ElementsDelta.create(added, removed, updated, {
|
||||||
|
shouldRedistribute: true, // redistribute the deltas as `isDeleted` could have been updated
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// CFDO: does it make sense having a separate snapshot?
|
||||||
|
public applyTo(
|
||||||
|
elements: SceneElementsMap,
|
||||||
|
elementsSnapshot: Map<string, OrderedExcalidrawElement>,
|
||||||
|
): [SceneElementsMap, boolean] {
|
||||||
|
const nextElements = new Map(elements) as SceneElementsMap;
|
||||||
|
let changedElements: Map<string, OrderedExcalidrawElement>;
|
||||||
|
|
||||||
|
const flags = {
|
||||||
|
containsVisibleDifference: false,
|
||||||
|
containsZindexDifference: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
// mimic a transaction by applying deltas into `nextElements` (always new instance, no mutation)
|
||||||
|
try {
|
||||||
|
const applyDeltas = ElementsDelta.createApplier(
|
||||||
|
nextElements,
|
||||||
|
elementsSnapshot,
|
||||||
|
flags,
|
||||||
|
);
|
||||||
|
|
||||||
|
const addedElements = applyDeltas("added", this.added);
|
||||||
|
const removedElements = applyDeltas("removed", this.removed);
|
||||||
|
const updatedElements = applyDeltas("updated", this.updated);
|
||||||
|
|
||||||
|
// CFDO I: don't forget to fix this part
|
||||||
|
// const affectedElements = this.resolveConflicts(elements, nextElements);
|
||||||
|
|
||||||
|
// TODO: #7348 validate elements semantically and syntactically the changed elements, in case they would result data integrity issues
|
||||||
|
changedElements = new Map([
|
||||||
|
...addedElements,
|
||||||
|
...removedElements,
|
||||||
|
...updatedElements,
|
||||||
|
// ...affectedElements,
|
||||||
|
]);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(`Couldn't apply elements delta`, e);
|
||||||
|
|
||||||
|
if (shouldThrow()) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
|
||||||
|
// should not really happen, but just in case we cannot apply deltas, let's return the previous elements with visible change set to `true`
|
||||||
|
// even though there is obviously no visible change, returning `false` could be dangerous, as i.e.:
|
||||||
|
// in the worst case, it could lead into iterating through the whole stack with no possibility to redo
|
||||||
|
// instead, the worst case when returning `true` is an empty undo / redo
|
||||||
|
return [elements, true];
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// CFDO I: don't forget to fix this part
|
||||||
|
// // TODO: #7348 refactor away mutations below, so that we couldn't end up in an incosistent state
|
||||||
|
// ElementsDelta.redrawTextBoundingBoxes(nextElements, changedElements);
|
||||||
|
// // the following reorder performs also mutations, but only on new instances of changed elements
|
||||||
|
// // (unless something goes really bad and it fallbacks to fixing all invalid indices)
|
||||||
|
// nextElements = ElementsDelta.reorderElements(
|
||||||
|
// nextElements,
|
||||||
|
// changedElements,
|
||||||
|
// flags,
|
||||||
|
// );
|
||||||
|
// // Need ordered nextElements to avoid z-index binding issues
|
||||||
|
// ElementsDelta.redrawBoundArrows(nextElements, changedElements);
|
||||||
|
} catch (e) {
|
||||||
|
console.error(
|
||||||
|
`Couldn't mutate elements after applying elements change`,
|
||||||
|
e,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (shouldThrow()) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
return [nextElements, flags.containsVisibleDifference];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static createApplier =
|
||||||
|
(
|
||||||
|
nextElements: SceneElementsMap,
|
||||||
|
snapshot: Map<string, OrderedExcalidrawElement>,
|
||||||
|
flags: {
|
||||||
|
containsVisibleDifference: boolean;
|
||||||
|
containsZindexDifference: boolean;
|
||||||
|
},
|
||||||
|
) =>
|
||||||
|
(
|
||||||
|
type: "added" | "removed" | "updated",
|
||||||
|
deltas: Record<string, Delta<ElementPartial>>,
|
||||||
|
) => {
|
||||||
|
const getElement = ElementsDelta.createGetter(
|
||||||
|
type,
|
||||||
|
nextElements,
|
||||||
|
snapshot,
|
||||||
|
flags,
|
||||||
|
);
|
||||||
|
|
||||||
|
return Object.entries(deltas).reduce((acc, [id, delta]) => {
|
||||||
|
const element = getElement(id, delta.inserted);
|
||||||
|
|
||||||
|
if (element) {
|
||||||
|
const newElement = ElementsDelta.applyDelta(element, delta, flags);
|
||||||
|
nextElements.set(newElement.id, newElement);
|
||||||
|
acc.set(newElement.id, newElement);
|
||||||
|
}
|
||||||
|
|
||||||
|
return acc;
|
||||||
|
}, new Map<string, OrderedExcalidrawElement>());
|
||||||
|
};
|
||||||
|
|
||||||
|
private static createGetter =
|
||||||
|
(
|
||||||
|
type: "added" | "removed" | "updated",
|
||||||
|
elements: SceneElementsMap,
|
||||||
|
snapshot: Map<string, OrderedExcalidrawElement>,
|
||||||
|
flags: {
|
||||||
|
containsVisibleDifference: boolean;
|
||||||
|
containsZindexDifference: boolean;
|
||||||
|
},
|
||||||
|
) =>
|
||||||
|
(id: string, partial: ElementPartial) => {
|
||||||
|
let element = elements.get(id);
|
||||||
|
|
||||||
|
if (!element) {
|
||||||
|
// always fallback to the local snapshot, in cases when we cannot find the element in the elements array
|
||||||
|
element = snapshot.get(id);
|
||||||
|
|
||||||
|
if (element) {
|
||||||
|
// as the element was brought from the snapshot, it automatically results in a possible zindex difference
|
||||||
|
flags.containsZindexDifference = true;
|
||||||
|
|
||||||
|
// as the element was force deleted, we need to check if adding it back results in a visible change
|
||||||
|
if (
|
||||||
|
partial.isDeleted === false ||
|
||||||
|
(partial.isDeleted !== true && element.isDeleted === false)
|
||||||
|
) {
|
||||||
|
flags.containsVisibleDifference = true;
|
||||||
|
}
|
||||||
|
} else if (type === "added") {
|
||||||
|
// for additions the element does not have to exist (i.e. remote update)
|
||||||
|
// CFDO II: the version itself might be different!
|
||||||
|
element = newElementWith(
|
||||||
|
{ id, version: 1 } as OrderedExcalidrawElement,
|
||||||
|
{
|
||||||
|
...partial,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return element;
|
||||||
|
};
|
||||||
|
|
||||||
|
private static applyDelta(
|
||||||
|
element: OrderedExcalidrawElement,
|
||||||
|
delta: Delta<ElementPartial>,
|
||||||
|
flags: {
|
||||||
|
containsVisibleDifference: boolean;
|
||||||
|
containsZindexDifference: boolean;
|
||||||
|
} = {
|
||||||
|
// by default we don't care about about the flags
|
||||||
|
containsVisibleDifference: true,
|
||||||
|
containsZindexDifference: true,
|
||||||
|
},
|
||||||
|
) {
|
||||||
|
const { boundElements, ...directlyApplicablePartial } = delta.inserted;
|
||||||
|
|
||||||
|
if (
|
||||||
|
delta.deleted.boundElements?.length ||
|
||||||
|
delta.inserted.boundElements?.length
|
||||||
|
) {
|
||||||
|
const mergedBoundElements = Delta.mergeArrays(
|
||||||
|
element.boundElements,
|
||||||
|
delta.inserted.boundElements,
|
||||||
|
delta.deleted.boundElements,
|
||||||
|
(x) => x.id,
|
||||||
|
);
|
||||||
|
|
||||||
|
Object.assign(directlyApplicablePartial, {
|
||||||
|
boundElements: mergedBoundElements,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// CFDO: this looks wrong
|
||||||
|
if (element.type === "image") {
|
||||||
|
const _delta = delta as Delta<ElementPartial<ExcalidrawImageElement>>;
|
||||||
|
// we want to override `crop` only if modified so that we don't reset
|
||||||
|
// when undoing/redoing unrelated change
|
||||||
|
if (_delta.deleted.crop || _delta.inserted.crop) {
|
||||||
|
Object.assign(directlyApplicablePartial, {
|
||||||
|
// apply change verbatim
|
||||||
|
crop: _delta.inserted.crop ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!flags.containsVisibleDifference) {
|
||||||
|
// strip away fractional index, as even if it would be different, it doesn't have to result in visible change
|
||||||
|
const { index, ...rest } = directlyApplicablePartial;
|
||||||
|
const containsVisibleDifference = ElementsDelta.checkForVisibleDifference(
|
||||||
|
element,
|
||||||
|
rest,
|
||||||
|
);
|
||||||
|
|
||||||
|
flags.containsVisibleDifference = containsVisibleDifference;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!flags.containsZindexDifference) {
|
||||||
|
flags.containsZindexDifference =
|
||||||
|
delta.deleted.index !== delta.inserted.index;
|
||||||
|
}
|
||||||
|
|
||||||
|
return newElementWith(element, directlyApplicablePartial);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check for visible changes regardless of whether they were removed, added or updated.
|
||||||
|
*/
|
||||||
|
private static checkForVisibleDifference(
|
||||||
|
element: OrderedExcalidrawElement,
|
||||||
|
partial: ElementPartial,
|
||||||
|
) {
|
||||||
|
if (element.isDeleted && partial.isDeleted !== false) {
|
||||||
|
// when it's deleted and partial is not false, it cannot end up with a visible change
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.isDeleted && partial.isDeleted === false) {
|
||||||
|
// when we add an element, it results in a visible change
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (element.isDeleted === false && partial.isDeleted) {
|
||||||
|
// when we remove an element, it results in a visible change
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// check for any difference on a visible element
|
||||||
|
return Delta.isRightDifferent(element, partial);
|
||||||
|
}
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Resolves conflicts for all previously added, removed and updated elements.
|
||||||
|
// * Updates the previous deltas with all the changes after conflict resolution.
|
||||||
|
// *
|
||||||
|
// * // CFDO: revisit since arrow seem often redrawn incorrectly
|
||||||
|
// *
|
||||||
|
// * @returns all elements affected by the conflict resolution
|
||||||
|
// */
|
||||||
|
// private resolveConflicts(
|
||||||
|
// prevElements: SceneElementsMap,
|
||||||
|
// nextElements: SceneElementsMap,
|
||||||
|
// ) {
|
||||||
|
// const nextAffectedElements = new Map<string, OrderedExcalidrawElement>();
|
||||||
|
// const updater = (
|
||||||
|
// element: ExcalidrawElement,
|
||||||
|
// updates: ElementUpdate<ExcalidrawElement>,
|
||||||
|
// ) => {
|
||||||
|
// const nextElement = nextElements.get(element.id); // only ever modify next element!
|
||||||
|
// if (!nextElement) {
|
||||||
|
// return;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// let affectedElement: OrderedExcalidrawElement;
|
||||||
|
|
||||||
|
// if (prevElements.get(element.id) === nextElement) {
|
||||||
|
// // create the new element instance in case we didn't modify the element yet
|
||||||
|
// // so that we won't end up in an incosistent state in case we would fail in the middle of mutations
|
||||||
|
// affectedElement = newElementWith(
|
||||||
|
// nextElement,
|
||||||
|
// updates as ElementUpdate<OrderedExcalidrawElement>,
|
||||||
|
// );
|
||||||
|
// } else {
|
||||||
|
// affectedElement = mutateElement(
|
||||||
|
// nextElement,
|
||||||
|
// updates as ElementUpdate<OrderedExcalidrawElement>,
|
||||||
|
// );
|
||||||
|
// }
|
||||||
|
|
||||||
|
// nextAffectedElements.set(affectedElement.id, affectedElement);
|
||||||
|
// nextElements.set(affectedElement.id, affectedElement);
|
||||||
|
// };
|
||||||
|
|
||||||
|
// // removed delta is affecting the bindings always, as all the affected elements of the removed elements need to be unbound
|
||||||
|
// for (const id of Object.keys(this.removed)) {
|
||||||
|
// ElementsDelta.unbindAffected(prevElements, nextElements, id, updater);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // added delta is affecting the bindings always, all the affected elements of the added elements need to be rebound
|
||||||
|
// for (const id of Object.keys(this.added)) {
|
||||||
|
// ElementsDelta.rebindAffected(prevElements, nextElements, id, updater);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // updated delta is affecting the binding only in case it contains changed binding or bindable property
|
||||||
|
// for (const [id] of Array.from(Object.entries(this.updated)).filter(
|
||||||
|
// ([_, delta]) =>
|
||||||
|
// Object.keys({ ...delta.deleted, ...delta.inserted }).find((prop) =>
|
||||||
|
// bindingProperties.has(prop as BindingProp | BindableProp),
|
||||||
|
// ),
|
||||||
|
// )) {
|
||||||
|
// const updatedElement = nextElements.get(id);
|
||||||
|
// if (!updatedElement || updatedElement.isDeleted) {
|
||||||
|
// // skip fixing bindings for updates on deleted elements
|
||||||
|
// continue;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// ElementsDelta.rebindAffected(prevElements, nextElements, id, updater);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // filter only previous elements, which were now affected
|
||||||
|
// const prevAffectedElements = new Map(
|
||||||
|
// Array.from(prevElements).filter(([id]) => nextAffectedElements.has(id)),
|
||||||
|
// );
|
||||||
|
|
||||||
|
// // calculate complete deltas for affected elements, and assign them back to all the deltas
|
||||||
|
// // technically we could do better here if perf. would become an issue
|
||||||
|
// const { added, removed, updated } = ElementsDelta.calculate(
|
||||||
|
// prevAffectedElements,
|
||||||
|
// nextAffectedElements,
|
||||||
|
// );
|
||||||
|
|
||||||
|
// for (const [id, delta] of Object.entries(added)) {
|
||||||
|
// this.added[id] = delta;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// for (const [id, delta] of Object.entries(removed)) {
|
||||||
|
// this.removed[id] = delta;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// for (const [id, delta] of Object.entries(updated)) {
|
||||||
|
// this.updated[id] = delta;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return nextAffectedElements;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Non deleted affected elements of removed elements (before and after applying delta),
|
||||||
|
// * should be unbound ~ bindings should not point from non deleted into the deleted element/s.
|
||||||
|
// */
|
||||||
|
// private static unbindAffected(
|
||||||
|
// prevElements: SceneElementsMap,
|
||||||
|
// nextElements: SceneElementsMap,
|
||||||
|
// id: string,
|
||||||
|
// updater: (
|
||||||
|
// element: ExcalidrawElement,
|
||||||
|
// updates: ElementUpdate<ExcalidrawElement>,
|
||||||
|
// ) => void,
|
||||||
|
// ) {
|
||||||
|
// // the instance could have been updated, so make sure we are passing the latest element to each function below
|
||||||
|
// const prevElement = () => prevElements.get(id); // element before removal
|
||||||
|
// const nextElement = () => nextElements.get(id); // element after removal
|
||||||
|
|
||||||
|
// BoundElement.unbindAffected(nextElements, prevElement(), updater);
|
||||||
|
// BoundElement.unbindAffected(nextElements, nextElement(), updater);
|
||||||
|
|
||||||
|
// BindableElement.unbindAffected(nextElements, prevElement(), updater);
|
||||||
|
// BindableElement.unbindAffected(nextElements, nextElement(), updater);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// /**
|
||||||
|
// * Non deleted affected elements of added or updated element/s (before and after applying delta),
|
||||||
|
// * should be rebound (if possible) with the current element ~ bindings should be bidirectional.
|
||||||
|
// */
|
||||||
|
// private static rebindAffected(
|
||||||
|
// prevElements: SceneElementsMap,
|
||||||
|
// nextElements: SceneElementsMap,
|
||||||
|
// id: string,
|
||||||
|
// updater: (
|
||||||
|
// element: ExcalidrawElement,
|
||||||
|
// updates: ElementUpdate<ExcalidrawElement>,
|
||||||
|
// ) => void,
|
||||||
|
// ) {
|
||||||
|
// // the instance could have been updated, so make sure we are passing the latest element to each function below
|
||||||
|
// const prevElement = () => prevElements.get(id); // element before addition / update
|
||||||
|
// const nextElement = () => nextElements.get(id); // element after addition / update
|
||||||
|
|
||||||
|
// BoundElement.unbindAffected(nextElements, prevElement(), updater);
|
||||||
|
// BoundElement.rebindAffected(nextElements, nextElement(), updater);
|
||||||
|
|
||||||
|
// BindableElement.unbindAffected(
|
||||||
|
// nextElements,
|
||||||
|
// prevElement(),
|
||||||
|
// (element, updates) => {
|
||||||
|
// // we cannot rebind arrows with bindable element so we don't unbind them at all during rebind (we still need to unbind them on removal)
|
||||||
|
// // TODO: #7348 add startBinding / endBinding to the `BoundElement` context so that we could rebind arrows and remove this condition
|
||||||
|
// if (isTextElement(element)) {
|
||||||
|
// updater(element, updates);
|
||||||
|
// }
|
||||||
|
// },
|
||||||
|
// );
|
||||||
|
// BindableElement.rebindAffected(nextElements, nextElement(), updater);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// private static redrawTextBoundingBoxes(
|
||||||
|
// elements: SceneElementsMap,
|
||||||
|
// changed: Map<string, OrderedExcalidrawElement>,
|
||||||
|
// ) {
|
||||||
|
// const boxesToRedraw = new Map<
|
||||||
|
// string,
|
||||||
|
// { container: OrderedExcalidrawElement; boundText: ExcalidrawTextElement }
|
||||||
|
// >();
|
||||||
|
|
||||||
|
// for (const element of changed.values()) {
|
||||||
|
// if (isBoundToContainer(element)) {
|
||||||
|
// const { containerId } = element as ExcalidrawTextElement;
|
||||||
|
// const container = containerId ? elements.get(containerId) : undefined;
|
||||||
|
|
||||||
|
// if (container) {
|
||||||
|
// boxesToRedraw.set(container.id, {
|
||||||
|
// container,
|
||||||
|
// boundText: element as ExcalidrawTextElement,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// if (hasBoundTextElement(element)) {
|
||||||
|
// const boundTextElementId = getBoundTextElementId(element);
|
||||||
|
// const boundText = boundTextElementId
|
||||||
|
// ? elements.get(boundTextElementId)
|
||||||
|
// : undefined;
|
||||||
|
|
||||||
|
// if (boundText) {
|
||||||
|
// boxesToRedraw.set(element.id, {
|
||||||
|
// container: element,
|
||||||
|
// boundText: boundText as ExcalidrawTextElement,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// for (const { container, boundText } of boxesToRedraw.values()) {
|
||||||
|
// if (container.isDeleted || boundText.isDeleted) {
|
||||||
|
// // skip redraw if one of them is deleted, as it would not result in a meaningful redraw
|
||||||
|
// continue;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// redrawTextBoundingBox(boundText, container, elements, false);
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// private static redrawBoundArrows(
|
||||||
|
// elements: SceneElementsMap,
|
||||||
|
// changed: Map<string, OrderedExcalidrawElement>,
|
||||||
|
// ) {
|
||||||
|
// for (const element of changed.values()) {
|
||||||
|
// if (!element.isDeleted && isBindableElement(element)) {
|
||||||
|
// updateBoundElements(element, elements, {
|
||||||
|
// changedElements: changed,
|
||||||
|
// });
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
// }
|
||||||
|
|
||||||
|
// private static reorderElements(
|
||||||
|
// elements: SceneElementsMap,
|
||||||
|
// changed: Map<string, OrderedExcalidrawElement>,
|
||||||
|
// flags: {
|
||||||
|
// containsVisibleDifference: boolean;
|
||||||
|
// containsZindexDifference: boolean;
|
||||||
|
// },
|
||||||
|
// ) {
|
||||||
|
// if (!flags.containsZindexDifference) {
|
||||||
|
// return elements;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// const unordered = Array.from(elements.values());
|
||||||
|
// const ordered = orderByFractionalIndex([...unordered]);
|
||||||
|
// const moved = Delta.getRightDifferences(unordered, ordered, true).reduce(
|
||||||
|
// (acc, arrayIndex) => {
|
||||||
|
// const candidate = unordered[Number(arrayIndex)];
|
||||||
|
// if (candidate && changed.has(candidate.id)) {
|
||||||
|
// acc.set(candidate.id, candidate);
|
||||||
|
// }
|
||||||
|
|
||||||
|
// return acc;
|
||||||
|
// },
|
||||||
|
// new Map(),
|
||||||
|
// );
|
||||||
|
|
||||||
|
// if (!flags.containsVisibleDifference && moved.size) {
|
||||||
|
// // we found a difference in order!
|
||||||
|
// flags.containsVisibleDifference = true;
|
||||||
|
// }
|
||||||
|
|
||||||
|
// // synchronize all elements that were actually moved
|
||||||
|
// // could fallback to synchronizing all invalid indices
|
||||||
|
// return elementsToMap(syncMovedIndices(ordered, moved)) as typeof elements;
|
||||||
|
// }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* It is necessary to post process the partials in case of reference values,
|
||||||
|
* for which we need to calculate the real diff between `deleted` and `inserted`.
|
||||||
|
*/
|
||||||
|
private static postProcess(
|
||||||
|
deleted: ElementPartial,
|
||||||
|
inserted: ElementPartial,
|
||||||
|
): [ElementPartial, ElementPartial] {
|
||||||
|
try {
|
||||||
|
Delta.diffArrays(deleted, inserted, "boundElements", (x) => x.id);
|
||||||
|
} catch (e) {
|
||||||
|
// if postprocessing fails, it does not make sense to bubble up, but let's make sure we know about it
|
||||||
|
console.error(`Couldn't postprocess elements delta.`);
|
||||||
|
|
||||||
|
if (shouldThrow()) {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
return [deleted, inserted];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static stripIrrelevantProps(
|
||||||
|
partial: Partial<OrderedExcalidrawElement>,
|
||||||
|
): ElementPartial {
|
||||||
|
const { id, updated, version, versionNonce, ...strippedPartial } = partial;
|
||||||
|
|
||||||
|
return strippedPartial;
|
||||||
|
}
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
export type {
|
||||||
|
AppState,
|
||||||
|
ObservedElementsAppState,
|
||||||
|
ObservedStandaloneAppState,
|
||||||
|
ObservedAppState,
|
||||||
|
} from "@excalidraw/excalidraw/dist/excalidraw/types";
|
||||||
|
export type {
|
||||||
|
DTO,
|
||||||
|
SubtypeOf,
|
||||||
|
ValueOf,
|
||||||
|
} from "@excalidraw/excalidraw/dist/excalidraw/utility-types";
|
||||||
|
|
||||||
|
export type {
|
||||||
|
ExcalidrawElement,
|
||||||
|
ExcalidrawImageElement,
|
||||||
|
ExcalidrawTextElement,
|
||||||
|
Ordered,
|
||||||
|
OrderedExcalidrawElement,
|
||||||
|
SceneElementsMap,
|
||||||
|
ElementsMap,
|
||||||
|
} from "@excalidraw/excalidraw/dist/excalidraw/element/types";
|
||||||
|
export type { ElementUpdate } from "@excalidraw/excalidraw/dist/excalidraw/element/mutateElement";
|
||||||
|
export type {
|
||||||
|
BindableProp,
|
||||||
|
BindingProp,
|
||||||
|
} from "@excalidraw/excalidraw/dist/excalidraw/element/binding";
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export type { DeltaContainer } from "./common/interfaces";
|
||||||
|
|
||||||
|
export { Delta } from "./common/delta";
|
||||||
|
export { ElementsDelta } from "./containers/elements";
|
||||||
|
export { AppStateDelta } from "./containers/appstate";
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"target": "ESNext",
|
||||||
|
"strict": true,
|
||||||
|
"outDir": "dist/types",
|
||||||
|
"skipLibCheck": true,
|
||||||
|
"declaration": true,
|
||||||
|
"emitDeclarationOnly": true,
|
||||||
|
"allowSyntheticDefaultImports": true,
|
||||||
|
"module": "ESNext",
|
||||||
|
"moduleResolution": "Node",
|
||||||
|
},
|
||||||
|
"exclude": [
|
||||||
|
"**/*.test.*",
|
||||||
|
"**/tests/*",
|
||||||
|
"types",
|
||||||
|
"dist",
|
||||||
|
],
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@excalidraw/element",
|
"name": "@excalidraw/element",
|
||||||
"version": "0.18.0",
|
"version": "0.1.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"types": "./dist/types/element/src/index.d.ts",
|
"types": "./dist/types/element/src/index.d.ts",
|
||||||
"main": "./dist/prod/index.js",
|
"main": "./dist/prod/index.js",
|
||||||
@@ -13,10 +13,7 @@
|
|||||||
"default": "./dist/prod/index.js"
|
"default": "./dist/prod/index.js"
|
||||||
},
|
},
|
||||||
"./*": {
|
"./*": {
|
||||||
"types": "./dist/types/element/src/*.d.ts",
|
"types": "./../element/dist/types/element/src/*.d.ts"
|
||||||
"development": "./dist/dev/index.js",
|
|
||||||
"production": "./dist/prod/index.js",
|
|
||||||
"default": "./dist/prod/index.js"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
@@ -53,11 +50,7 @@
|
|||||||
"bugs": "https://github.com/excalidraw/excalidraw/issues",
|
"bugs": "https://github.com/excalidraw/excalidraw/issues",
|
||||||
"repository": "https://github.com/excalidraw/excalidraw",
|
"repository": "https://github.com/excalidraw/excalidraw",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"gen:types": "rimraf types && tsc",
|
"gen:types": "rm -rf types && tsc",
|
||||||
"build:esm": "rimraf dist && node ../../scripts/buildBase.js && yarn gen:types"
|
"build:esm": "rm -rf dist && node ../../scripts/buildBase.js && yarn gen:types"
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@excalidraw/common": "0.18.0",
|
|
||||||
"@excalidraw/math": "0.18.0"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,21 +6,25 @@ import {
|
|||||||
toBrandedType,
|
toBrandedType,
|
||||||
isDevEnv,
|
isDevEnv,
|
||||||
isTestEnv,
|
isTestEnv,
|
||||||
toArray,
|
isReadonlyArray,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
import { isNonDeletedElement } from "@excalidraw/element";
|
import { isNonDeletedElement } from "@excalidraw/element";
|
||||||
import { isFrameLikeElement } from "@excalidraw/element";
|
import { isFrameLikeElement } from "@excalidraw/element/typeChecks";
|
||||||
import { getElementsInGroup } from "@excalidraw/element";
|
import { getElementsInGroup } from "@excalidraw/element/groups";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
|
orderByFractionalIndex,
|
||||||
syncInvalidIndices,
|
syncInvalidIndices,
|
||||||
syncMovedIndices,
|
syncMovedIndices,
|
||||||
validateFractionalIndices,
|
validateFractionalIndices,
|
||||||
} from "@excalidraw/element";
|
} from "@excalidraw/element/fractionalIndex";
|
||||||
|
|
||||||
import { getSelectedElements } from "@excalidraw/element";
|
import { getSelectedElements } from "@excalidraw/element/selection";
|
||||||
|
|
||||||
import { mutateElement, type ElementUpdate } from "@excalidraw/element";
|
import {
|
||||||
|
mutateElement,
|
||||||
|
type ElementUpdate,
|
||||||
|
} from "@excalidraw/element/mutateElement";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
@@ -105,7 +109,7 @@ const hashSelectionOpts = (
|
|||||||
// in our codebase
|
// in our codebase
|
||||||
export type ExcalidrawElementsIncludingDeleted = readonly ExcalidrawElement[];
|
export type ExcalidrawElementsIncludingDeleted = readonly ExcalidrawElement[];
|
||||||
|
|
||||||
export class Scene {
|
class Scene {
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
// instance methods/props
|
// instance methods/props
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
@@ -164,14 +168,9 @@ export class Scene {
|
|||||||
return this.frames;
|
return this.frames;
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(
|
constructor(elements: ElementsMapOrArray | null = null) {
|
||||||
elements: ElementsMapOrArray | null = null,
|
|
||||||
options?: {
|
|
||||||
skipValidation?: true;
|
|
||||||
},
|
|
||||||
) {
|
|
||||||
if (elements) {
|
if (elements) {
|
||||||
this.replaceAllElements(elements, options);
|
this.replaceAllElements(elements);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -268,21 +267,20 @@ export class Scene {
|
|||||||
return didChange;
|
return didChange;
|
||||||
}
|
}
|
||||||
|
|
||||||
replaceAllElements(
|
replaceAllElements(nextElements: ElementsMapOrArray) {
|
||||||
nextElements: ElementsMapOrArray,
|
// ts doesn't like `Array.isArray` of `instanceof Map`
|
||||||
options?: {
|
if (!isReadonlyArray(nextElements)) {
|
||||||
skipValidation?: true;
|
// need to order by fractional indices to get the correct order
|
||||||
},
|
nextElements = orderByFractionalIndex(
|
||||||
) {
|
Array.from(nextElements.values()) as OrderedExcalidrawElement[],
|
||||||
// we do trust the insertion order on the map, though maybe we shouldn't and should prefer order defined by fractional indices
|
);
|
||||||
const _nextElements = toArray(nextElements);
|
|
||||||
const nextFrameLikes: ExcalidrawFrameLikeElement[] = [];
|
|
||||||
|
|
||||||
if (!options?.skipValidation) {
|
|
||||||
validateIndicesThrottled(_nextElements);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
this.elements = syncInvalidIndices(_nextElements);
|
const nextFrameLikes: ExcalidrawFrameLikeElement[] = [];
|
||||||
|
|
||||||
|
validateIndicesThrottled(nextElements);
|
||||||
|
|
||||||
|
this.elements = syncInvalidIndices(nextElements);
|
||||||
this.elementsMap.clear();
|
this.elementsMap.clear();
|
||||||
this.elements.forEach((element) => {
|
this.elements.forEach((element) => {
|
||||||
if (isFrameLikeElement(element)) {
|
if (isFrameLikeElement(element)) {
|
||||||
@@ -466,3 +464,5 @@ export class Scene {
|
|||||||
return element;
|
return element;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default Scene;
|
||||||
|
|||||||
@@ -1,65 +1,26 @@
|
|||||||
import { simplify } from "points-on-curve";
|
import { simplify } from "points-on-curve";
|
||||||
|
|
||||||
import {
|
import { pointFrom, pointDistance, type LocalPoint } from "@excalidraw/math";
|
||||||
type GeometricShape,
|
import { ROUGHNESS, isTransparent, assertNever } from "@excalidraw/common";
|
||||||
getClosedCurveShape,
|
|
||||||
getCurveShape,
|
|
||||||
getEllipseShape,
|
|
||||||
getFreedrawShape,
|
|
||||||
getPolygonShape,
|
|
||||||
} from "@excalidraw/utils/shape";
|
|
||||||
|
|
||||||
import {
|
|
||||||
pointFrom,
|
|
||||||
pointDistance,
|
|
||||||
type LocalPoint,
|
|
||||||
pointRotateRads,
|
|
||||||
} from "@excalidraw/math";
|
|
||||||
import {
|
|
||||||
ROUGHNESS,
|
|
||||||
isTransparent,
|
|
||||||
assertNever,
|
|
||||||
COLOR_PALETTE,
|
|
||||||
LINE_POLYGON_POINT_MERGE_DISTANCE,
|
|
||||||
} from "@excalidraw/common";
|
|
||||||
|
|
||||||
import { RoughGenerator } from "roughjs/bin/generator";
|
|
||||||
|
|
||||||
import type { GlobalPoint } from "@excalidraw/math";
|
|
||||||
|
|
||||||
import type { Mutable } from "@excalidraw/common/utility-types";
|
import type { Mutable } from "@excalidraw/common/utility-types";
|
||||||
|
|
||||||
import type {
|
import type { EmbedsValidationStatus } from "@excalidraw/excalidraw/types";
|
||||||
AppState,
|
import type { ElementShapes } from "@excalidraw/excalidraw/scene/types";
|
||||||
EmbedsValidationStatus,
|
|
||||||
} from "@excalidraw/excalidraw/types";
|
|
||||||
import type {
|
|
||||||
ElementShape,
|
|
||||||
ElementShapes,
|
|
||||||
} from "@excalidraw/excalidraw/scene/types";
|
|
||||||
|
|
||||||
import { elementWithCanvasCache } from "./renderElement";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
canBecomePolygon,
|
|
||||||
isElbowArrow,
|
isElbowArrow,
|
||||||
isEmbeddableElement,
|
isEmbeddableElement,
|
||||||
isIframeElement,
|
isIframeElement,
|
||||||
isIframeLikeElement,
|
isIframeLikeElement,
|
||||||
isLinearElement,
|
isLinearElement,
|
||||||
} from "./typeChecks";
|
} from "./typeChecks";
|
||||||
import { getCornerRadius, isPathALoop } from "./utils";
|
import { getCornerRadius, isPathALoop } from "./shapes";
|
||||||
import { headingForPointIsHorizontal } from "./heading";
|
import { headingForPointIsHorizontal } from "./heading";
|
||||||
|
|
||||||
import { canChangeRoundness } from "./comparisons";
|
import { canChangeRoundness } from "./comparisons";
|
||||||
import { generateFreeDrawShape } from "./renderElement";
|
import { generateFreeDrawShape } from "./renderElement";
|
||||||
import {
|
import { getArrowheadPoints, getDiamondPoints } from "./bounds";
|
||||||
getArrowheadPoints,
|
|
||||||
getCenterForBounds,
|
|
||||||
getDiamondPoints,
|
|
||||||
getElementAbsoluteCoords,
|
|
||||||
} from "./bounds";
|
|
||||||
import { shouldTestInside } from "./collision";
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
@@ -67,89 +28,12 @@ import type {
|
|||||||
ExcalidrawSelectionElement,
|
ExcalidrawSelectionElement,
|
||||||
ExcalidrawLinearElement,
|
ExcalidrawLinearElement,
|
||||||
Arrowhead,
|
Arrowhead,
|
||||||
ExcalidrawFreeDrawElement,
|
|
||||||
ElementsMap,
|
|
||||||
ExcalidrawLineElement,
|
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
import type { Drawable, Options } from "roughjs/bin/core";
|
import type { Drawable, Options } from "roughjs/bin/core";
|
||||||
|
import type { RoughGenerator } from "roughjs/bin/generator";
|
||||||
import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
||||||
|
|
||||||
export class ShapeCache {
|
|
||||||
private static rg = new RoughGenerator();
|
|
||||||
private static cache = new WeakMap<ExcalidrawElement, ElementShape>();
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves shape from cache if available. Use this only if shape
|
|
||||||
* is optional and you have a fallback in case it's not cached.
|
|
||||||
*/
|
|
||||||
public static get = <T extends ExcalidrawElement>(element: T) => {
|
|
||||||
return ShapeCache.cache.get(
|
|
||||||
element,
|
|
||||||
) as T["type"] extends keyof ElementShapes
|
|
||||||
? ElementShapes[T["type"]] | undefined
|
|
||||||
: ElementShape | undefined;
|
|
||||||
};
|
|
||||||
|
|
||||||
public static set = <T extends ExcalidrawElement>(
|
|
||||||
element: T,
|
|
||||||
shape: T["type"] extends keyof ElementShapes
|
|
||||||
? ElementShapes[T["type"]]
|
|
||||||
: Drawable,
|
|
||||||
) => ShapeCache.cache.set(element, shape);
|
|
||||||
|
|
||||||
public static delete = (element: ExcalidrawElement) =>
|
|
||||||
ShapeCache.cache.delete(element);
|
|
||||||
|
|
||||||
public static destroy = () => {
|
|
||||||
ShapeCache.cache = new WeakMap();
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generates & caches shape for element if not already cached, otherwise
|
|
||||||
* returns cached shape.
|
|
||||||
*/
|
|
||||||
public static generateElementShape = <
|
|
||||||
T extends Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
|
|
||||||
>(
|
|
||||||
element: T,
|
|
||||||
renderConfig: {
|
|
||||||
isExporting: boolean;
|
|
||||||
canvasBackgroundColor: AppState["viewBackgroundColor"];
|
|
||||||
embedsValidationStatus: EmbedsValidationStatus;
|
|
||||||
} | null,
|
|
||||||
) => {
|
|
||||||
// when exporting, always regenerated to guarantee the latest shape
|
|
||||||
const cachedShape = renderConfig?.isExporting
|
|
||||||
? undefined
|
|
||||||
: ShapeCache.get(element);
|
|
||||||
|
|
||||||
// `null` indicates no rc shape applicable for this element type,
|
|
||||||
// but it's considered a valid cache value (= do not regenerate)
|
|
||||||
if (cachedShape !== undefined) {
|
|
||||||
return cachedShape;
|
|
||||||
}
|
|
||||||
|
|
||||||
elementWithCanvasCache.delete(element);
|
|
||||||
|
|
||||||
const shape = generateElementShape(
|
|
||||||
element,
|
|
||||||
ShapeCache.rg,
|
|
||||||
renderConfig || {
|
|
||||||
isExporting: false,
|
|
||||||
canvasBackgroundColor: COLOR_PALETTE.white,
|
|
||||||
embedsValidationStatus: null,
|
|
||||||
},
|
|
||||||
) as T["type"] extends keyof ElementShapes
|
|
||||||
? ElementShapes[T["type"]]
|
|
||||||
: Drawable | null;
|
|
||||||
|
|
||||||
ShapeCache.cache.set(element, shape);
|
|
||||||
|
|
||||||
return shape;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const getDashArrayDashed = (strokeWidth: number) => [8, 8 + strokeWidth];
|
const getDashArrayDashed = (strokeWidth: number) => [8, 8 + strokeWidth];
|
||||||
|
|
||||||
const getDashArrayDotted = (strokeWidth: number) => [1.5, 6 + strokeWidth];
|
const getDashArrayDotted = (strokeWidth: number) => [1.5, 6 + strokeWidth];
|
||||||
@@ -419,182 +303,6 @@ const getArrowheadShapes = (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const generateLinearCollisionShape = (
|
|
||||||
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
|
|
||||||
) => {
|
|
||||||
const generator = new RoughGenerator();
|
|
||||||
const options: Options = {
|
|
||||||
seed: element.seed,
|
|
||||||
disableMultiStroke: true,
|
|
||||||
disableMultiStrokeFill: true,
|
|
||||||
roughness: 0,
|
|
||||||
preserveVertices: true,
|
|
||||||
};
|
|
||||||
const center = getCenterForBounds(
|
|
||||||
// Need a non-rotated center point
|
|
||||||
element.points.reduce(
|
|
||||||
(acc, point) => {
|
|
||||||
return [
|
|
||||||
Math.min(element.x + point[0], acc[0]),
|
|
||||||
Math.min(element.y + point[1], acc[1]),
|
|
||||||
Math.max(element.x + point[0], acc[2]),
|
|
||||||
Math.max(element.y + point[1], acc[3]),
|
|
||||||
];
|
|
||||||
},
|
|
||||||
[Infinity, Infinity, -Infinity, -Infinity],
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
switch (element.type) {
|
|
||||||
case "line":
|
|
||||||
case "arrow": {
|
|
||||||
// points array can be empty in the beginning, so it is important to add
|
|
||||||
// initial position to it
|
|
||||||
const points = element.points.length
|
|
||||||
? element.points
|
|
||||||
: [pointFrom<LocalPoint>(0, 0)];
|
|
||||||
|
|
||||||
if (isElbowArrow(element)) {
|
|
||||||
return generator.path(generateElbowArrowShape(points, 16), options)
|
|
||||||
.sets[0].ops;
|
|
||||||
} else if (!element.roundness) {
|
|
||||||
return points.map((point, idx) => {
|
|
||||||
const p = pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(element.x + point[0], element.y + point[1]),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
op: idx === 0 ? "move" : "lineTo",
|
|
||||||
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return generator
|
|
||||||
.curve(points as unknown as RoughPoint[], options)
|
|
||||||
.sets[0].ops.slice(0, element.points.length)
|
|
||||||
.map((op, i) => {
|
|
||||||
if (i === 0) {
|
|
||||||
const p = pointRotateRads<GlobalPoint>(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[0],
|
|
||||||
element.y + op.data[1],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
op: "move",
|
|
||||||
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
op: "bcurveTo",
|
|
||||||
data: [
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[0],
|
|
||||||
element.y + op.data[1],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[2],
|
|
||||||
element.y + op.data[3],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[4],
|
|
||||||
element.y + op.data[5],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
]
|
|
||||||
.map((p) =>
|
|
||||||
pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
||||||
)
|
|
||||||
.flat(),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
case "freedraw": {
|
|
||||||
if (element.points.length < 2) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const simplifiedPoints = simplify(
|
|
||||||
element.points as Mutable<LocalPoint[]>,
|
|
||||||
0.75,
|
|
||||||
);
|
|
||||||
|
|
||||||
return generator
|
|
||||||
.curve(simplifiedPoints as [number, number][], options)
|
|
||||||
.sets[0].ops.slice(0, element.points.length)
|
|
||||||
.map((op, i) => {
|
|
||||||
if (i === 0) {
|
|
||||||
const p = pointRotateRads<GlobalPoint>(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[0],
|
|
||||||
element.y + op.data[1],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
);
|
|
||||||
|
|
||||||
return {
|
|
||||||
op: "move",
|
|
||||||
data: pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
op: "bcurveTo",
|
|
||||||
data: [
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[0],
|
|
||||||
element.y + op.data[1],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[2],
|
|
||||||
element.y + op.data[3],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
element.x + op.data[4],
|
|
||||||
element.y + op.data[5],
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
]
|
|
||||||
.map((p) =>
|
|
||||||
pointFrom<LocalPoint>(p[0] - element.x, p[1] - element.y),
|
|
||||||
)
|
|
||||||
.flat(),
|
|
||||||
};
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates the roughjs shape for given element.
|
* Generates the roughjs shape for given element.
|
||||||
*
|
*
|
||||||
@@ -602,7 +310,7 @@ export const generateLinearCollisionShape = (
|
|||||||
*
|
*
|
||||||
* @private
|
* @private
|
||||||
*/
|
*/
|
||||||
const generateElementShape = (
|
export const _generateElementShape = (
|
||||||
element: Exclude<NonDeletedExcalidrawElement, ExcalidrawSelectionElement>,
|
element: Exclude<NonDeletedExcalidrawElement, ExcalidrawSelectionElement>,
|
||||||
generator: RoughGenerator,
|
generator: RoughGenerator,
|
||||||
{
|
{
|
||||||
@@ -903,103 +611,3 @@ const generateElbowArrowShape = (
|
|||||||
|
|
||||||
return d.join(" ");
|
return d.join(" ");
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* get the pure geometric shape of an excalidraw elementw
|
|
||||||
* which is then used for hit detection
|
|
||||||
*/
|
|
||||||
export const getElementShape = <Point extends GlobalPoint | LocalPoint>(
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
): GeometricShape<Point> => {
|
|
||||||
switch (element.type) {
|
|
||||||
case "rectangle":
|
|
||||||
case "diamond":
|
|
||||||
case "frame":
|
|
||||||
case "magicframe":
|
|
||||||
case "embeddable":
|
|
||||||
case "image":
|
|
||||||
case "iframe":
|
|
||||||
case "text":
|
|
||||||
case "selection":
|
|
||||||
return getPolygonShape(element);
|
|
||||||
case "arrow":
|
|
||||||
case "line": {
|
|
||||||
const roughShape =
|
|
||||||
ShapeCache.get(element)?.[0] ??
|
|
||||||
ShapeCache.generateElementShape(element, null)[0];
|
|
||||||
const [, , , , cx, cy] = getElementAbsoluteCoords(element, elementsMap);
|
|
||||||
|
|
||||||
return shouldTestInside(element)
|
|
||||||
? getClosedCurveShape<Point>(
|
|
||||||
element,
|
|
||||||
roughShape,
|
|
||||||
pointFrom<Point>(element.x, element.y),
|
|
||||||
element.angle,
|
|
||||||
pointFrom(cx, cy),
|
|
||||||
)
|
|
||||||
: getCurveShape<Point>(
|
|
||||||
roughShape,
|
|
||||||
pointFrom<Point>(element.x, element.y),
|
|
||||||
element.angle,
|
|
||||||
pointFrom(cx, cy),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
case "ellipse":
|
|
||||||
return getEllipseShape(element);
|
|
||||||
|
|
||||||
case "freedraw": {
|
|
||||||
const [, , , , cx, cy] = getElementAbsoluteCoords(element, elementsMap);
|
|
||||||
return getFreedrawShape(
|
|
||||||
element,
|
|
||||||
pointFrom(cx, cy),
|
|
||||||
shouldTestInside(element),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
export const toggleLinePolygonState = (
|
|
||||||
element: ExcalidrawLineElement,
|
|
||||||
nextPolygonState: boolean,
|
|
||||||
): {
|
|
||||||
polygon: ExcalidrawLineElement["polygon"];
|
|
||||||
points: ExcalidrawLineElement["points"];
|
|
||||||
} | null => {
|
|
||||||
const updatedPoints = [...element.points];
|
|
||||||
|
|
||||||
if (nextPolygonState) {
|
|
||||||
if (!canBecomePolygon(element.points)) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const firstPoint = updatedPoints[0];
|
|
||||||
const lastPoint = updatedPoints[updatedPoints.length - 1];
|
|
||||||
|
|
||||||
const distance = Math.hypot(
|
|
||||||
firstPoint[0] - lastPoint[0],
|
|
||||||
firstPoint[1] - lastPoint[1],
|
|
||||||
);
|
|
||||||
|
|
||||||
if (
|
|
||||||
distance > LINE_POLYGON_POINT_MERGE_DISTANCE ||
|
|
||||||
updatedPoints.length < 4
|
|
||||||
) {
|
|
||||||
updatedPoints.push(pointFrom(firstPoint[0], firstPoint[1]));
|
|
||||||
} else {
|
|
||||||
updatedPoints[updatedPoints.length - 1] = pointFrom(
|
|
||||||
firstPoint[0],
|
|
||||||
firstPoint[1],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TODO: satisfies ElementUpdate<ExcalidrawLineElement>
|
|
||||||
const ret = {
|
|
||||||
polygon: nextPolygonState,
|
|
||||||
points: updatedPoints,
|
|
||||||
};
|
|
||||||
|
|
||||||
return ret;
|
|
||||||
};
|
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import { RoughGenerator } from "roughjs/bin/generator";
|
||||||
|
|
||||||
|
import { COLOR_PALETTE } from "@excalidraw/common";
|
||||||
|
|
||||||
|
import type {
|
||||||
|
AppState,
|
||||||
|
EmbedsValidationStatus,
|
||||||
|
} from "@excalidraw/excalidraw/types";
|
||||||
|
import type {
|
||||||
|
ElementShape,
|
||||||
|
ElementShapes,
|
||||||
|
} from "@excalidraw/excalidraw/scene/types";
|
||||||
|
|
||||||
|
import { _generateElementShape } from "./Shape";
|
||||||
|
|
||||||
|
import { elementWithCanvasCache } from "./renderElement";
|
||||||
|
|
||||||
|
import type { ExcalidrawElement, ExcalidrawSelectionElement } from "./types";
|
||||||
|
|
||||||
|
import type { Drawable } from "roughjs/bin/core";
|
||||||
|
|
||||||
|
export class ShapeCache {
|
||||||
|
private static rg = new RoughGenerator();
|
||||||
|
private static cache = new WeakMap<ExcalidrawElement, ElementShape>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves shape from cache if available. Use this only if shape
|
||||||
|
* is optional and you have a fallback in case it's not cached.
|
||||||
|
*/
|
||||||
|
public static get = <T extends ExcalidrawElement>(element: T) => {
|
||||||
|
return ShapeCache.cache.get(
|
||||||
|
element,
|
||||||
|
) as T["type"] extends keyof ElementShapes
|
||||||
|
? ElementShapes[T["type"]] | undefined
|
||||||
|
: ElementShape | undefined;
|
||||||
|
};
|
||||||
|
|
||||||
|
public static set = <T extends ExcalidrawElement>(
|
||||||
|
element: T,
|
||||||
|
shape: T["type"] extends keyof ElementShapes
|
||||||
|
? ElementShapes[T["type"]]
|
||||||
|
: Drawable,
|
||||||
|
) => ShapeCache.cache.set(element, shape);
|
||||||
|
|
||||||
|
public static delete = (element: ExcalidrawElement) =>
|
||||||
|
ShapeCache.cache.delete(element);
|
||||||
|
|
||||||
|
public static destroy = () => {
|
||||||
|
ShapeCache.cache = new WeakMap();
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generates & caches shape for element if not already cached, otherwise
|
||||||
|
* returns cached shape.
|
||||||
|
*/
|
||||||
|
public static generateElementShape = <
|
||||||
|
T extends Exclude<ExcalidrawElement, ExcalidrawSelectionElement>,
|
||||||
|
>(
|
||||||
|
element: T,
|
||||||
|
renderConfig: {
|
||||||
|
isExporting: boolean;
|
||||||
|
canvasBackgroundColor: AppState["viewBackgroundColor"];
|
||||||
|
embedsValidationStatus: EmbedsValidationStatus;
|
||||||
|
} | null,
|
||||||
|
) => {
|
||||||
|
// when exporting, always regenerated to guarantee the latest shape
|
||||||
|
const cachedShape = renderConfig?.isExporting
|
||||||
|
? undefined
|
||||||
|
: ShapeCache.get(element);
|
||||||
|
|
||||||
|
// `null` indicates no rc shape applicable for this element type,
|
||||||
|
// but it's considered a valid cache value (= do not regenerate)
|
||||||
|
if (cachedShape !== undefined) {
|
||||||
|
return cachedShape;
|
||||||
|
}
|
||||||
|
|
||||||
|
elementWithCanvasCache.delete(element);
|
||||||
|
|
||||||
|
const shape = _generateElementShape(
|
||||||
|
element,
|
||||||
|
ShapeCache.rg,
|
||||||
|
renderConfig || {
|
||||||
|
isExporting: false,
|
||||||
|
canvasBackgroundColor: COLOR_PALETTE.white,
|
||||||
|
embedsValidationStatus: null,
|
||||||
|
},
|
||||||
|
) as T["type"] extends keyof ElementShapes
|
||||||
|
? ElementShapes[T["type"]]
|
||||||
|
: Drawable | null;
|
||||||
|
|
||||||
|
ShapeCache.cache.set(element, shape);
|
||||||
|
|
||||||
|
return shape;
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -1,10 +1,8 @@
|
|||||||
import type { AppState } from "@excalidraw/excalidraw/types";
|
|
||||||
|
|
||||||
import { updateBoundElements } from "./binding";
|
import { updateBoundElements } from "./binding";
|
||||||
import { getCommonBoundingBox } from "./bounds";
|
import { getCommonBoundingBox } from "./bounds";
|
||||||
import { getSelectedElementsByGroup } from "./groups";
|
import { getMaximumGroups } from "./groups";
|
||||||
|
|
||||||
import type { Scene } from "./Scene";
|
import type Scene from "./Scene";
|
||||||
|
|
||||||
import type { BoundingBox } from "./bounds";
|
import type { BoundingBox } from "./bounds";
|
||||||
import type { ExcalidrawElement } from "./types";
|
import type { ExcalidrawElement } from "./types";
|
||||||
@@ -18,12 +16,11 @@ export const alignElements = (
|
|||||||
selectedElements: ExcalidrawElement[],
|
selectedElements: ExcalidrawElement[],
|
||||||
alignment: Alignment,
|
alignment: Alignment,
|
||||||
scene: Scene,
|
scene: Scene,
|
||||||
appState: Readonly<AppState>,
|
|
||||||
): ExcalidrawElement[] => {
|
): ExcalidrawElement[] => {
|
||||||
const groups: ExcalidrawElement[][] = getSelectedElementsByGroup(
|
const elementsMap = scene.getNonDeletedElementsMap();
|
||||||
|
const groups: ExcalidrawElement[][] = getMaximumGroups(
|
||||||
selectedElements,
|
selectedElements,
|
||||||
scene.getNonDeletedElementsMap(),
|
elementsMap,
|
||||||
appState,
|
|
||||||
);
|
);
|
||||||
const selectionBoundingBox = getCommonBoundingBox(selectedElements);
|
const selectionBoundingBox = getCommonBoundingBox(selectedElements);
|
||||||
|
|
||||||
|
|||||||
+1258
-1846
File diff suppressed because it is too large
Load Diff
+45
-177
@@ -1,18 +1,17 @@
|
|||||||
import rough from "roughjs/bin/rough";
|
import rough from "roughjs/bin/rough";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
arrayToMap,
|
|
||||||
type Bounds,
|
|
||||||
invariant,
|
|
||||||
rescalePoints,
|
rescalePoints,
|
||||||
|
arrayToMap,
|
||||||
|
invariant,
|
||||||
sizeOf,
|
sizeOf,
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
degreesToRadians,
|
degreesToRadians,
|
||||||
lineSegment,
|
lineSegment,
|
||||||
pointDistance,
|
|
||||||
pointFrom,
|
pointFrom,
|
||||||
|
pointDistance,
|
||||||
pointFromArray,
|
pointFromArray,
|
||||||
pointRotateRads,
|
pointRotateRads,
|
||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
@@ -34,8 +33,8 @@ import type { AppState } from "@excalidraw/excalidraw/types";
|
|||||||
|
|
||||||
import type { Mutable } from "@excalidraw/common/utility-types";
|
import type { Mutable } from "@excalidraw/common/utility-types";
|
||||||
|
|
||||||
import { generateRoughOptions } from "./shape";
|
import { ShapeCache } from "./ShapeCache";
|
||||||
import { ShapeCache } from "./shape";
|
import { generateRoughOptions } from "./Shape";
|
||||||
import { LinearElementEditor } from "./linearElementEditor";
|
import { LinearElementEditor } from "./linearElementEditor";
|
||||||
import { getBoundTextElement, getContainerElement } from "./textElement";
|
import { getBoundTextElement, getContainerElement } from "./textElement";
|
||||||
import {
|
import {
|
||||||
@@ -43,31 +42,30 @@ import {
|
|||||||
isBoundToContainer,
|
isBoundToContainer,
|
||||||
isFreeDrawElement,
|
isFreeDrawElement,
|
||||||
isLinearElement,
|
isLinearElement,
|
||||||
isLineElement,
|
|
||||||
isTextElement,
|
isTextElement,
|
||||||
} from "./typeChecks";
|
} from "./typeChecks";
|
||||||
|
|
||||||
import { getElementShape } from "./shape";
|
import { getElementShape } from "./shapes";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
deconstructDiamondElement,
|
deconstructDiamondElement,
|
||||||
deconstructRectanguloidElement,
|
deconstructRectanguloidElement,
|
||||||
} from "./utils";
|
} from "./utils";
|
||||||
|
|
||||||
|
import type {
|
||||||
|
ExcalidrawElement,
|
||||||
|
ExcalidrawLinearElement,
|
||||||
|
Arrowhead,
|
||||||
|
ExcalidrawFreeDrawElement,
|
||||||
|
NonDeleted,
|
||||||
|
ExcalidrawTextElementWithContainer,
|
||||||
|
ElementsMap,
|
||||||
|
ExcalidrawRectanguloidElement,
|
||||||
|
ExcalidrawEllipseElement,
|
||||||
|
ElementsMapOrArray,
|
||||||
|
} from "./types";
|
||||||
import type { Drawable, Op } from "roughjs/bin/core";
|
import type { Drawable, Op } from "roughjs/bin/core";
|
||||||
import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
import type { Point as RoughPoint } from "roughjs/bin/geometry";
|
||||||
import type {
|
|
||||||
Arrowhead,
|
|
||||||
ElementsMap,
|
|
||||||
ElementsMapOrArray,
|
|
||||||
ExcalidrawElement,
|
|
||||||
ExcalidrawEllipseElement,
|
|
||||||
ExcalidrawFreeDrawElement,
|
|
||||||
ExcalidrawLinearElement,
|
|
||||||
ExcalidrawRectanguloidElement,
|
|
||||||
ExcalidrawTextElementWithContainer,
|
|
||||||
NonDeleted,
|
|
||||||
} from "./types";
|
|
||||||
|
|
||||||
export type RectangleBox = {
|
export type RectangleBox = {
|
||||||
x: number;
|
x: number;
|
||||||
@@ -79,6 +77,16 @@ export type RectangleBox = {
|
|||||||
|
|
||||||
type MaybeQuadraticSolution = [number | null, number | null] | false;
|
type MaybeQuadraticSolution = [number | null, number | null] | false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* x and y position of top left corner, x and y position of bottom right corner
|
||||||
|
*/
|
||||||
|
export type Bounds = readonly [
|
||||||
|
minX: number,
|
||||||
|
minY: number,
|
||||||
|
maxX: number,
|
||||||
|
maxY: number,
|
||||||
|
];
|
||||||
|
|
||||||
export type SceneBounds = readonly [
|
export type SceneBounds = readonly [
|
||||||
sceneX: number,
|
sceneX: number,
|
||||||
sceneY: number,
|
sceneY: number,
|
||||||
@@ -94,23 +102,9 @@ export class ElementBounds {
|
|||||||
version: ExcalidrawElement["version"];
|
version: ExcalidrawElement["version"];
|
||||||
}
|
}
|
||||||
>();
|
>();
|
||||||
private static nonRotatedBoundsCache = new WeakMap<
|
|
||||||
ExcalidrawElement,
|
|
||||||
{
|
|
||||||
bounds: Bounds;
|
|
||||||
version: ExcalidrawElement["version"];
|
|
||||||
}
|
|
||||||
>();
|
|
||||||
|
|
||||||
static getBounds(
|
static getBounds(element: ExcalidrawElement, elementsMap: ElementsMap) {
|
||||||
element: ExcalidrawElement,
|
const cachedBounds = ElementBounds.boundsCache.get(element);
|
||||||
elementsMap: ElementsMap,
|
|
||||||
nonRotated: boolean = false,
|
|
||||||
) {
|
|
||||||
const cachedBounds =
|
|
||||||
nonRotated && element.angle !== 0
|
|
||||||
? ElementBounds.nonRotatedBoundsCache.get(element)
|
|
||||||
: ElementBounds.boundsCache.get(element);
|
|
||||||
|
|
||||||
if (
|
if (
|
||||||
cachedBounds?.version &&
|
cachedBounds?.version &&
|
||||||
@@ -121,23 +115,6 @@ export class ElementBounds {
|
|||||||
) {
|
) {
|
||||||
return cachedBounds.bounds;
|
return cachedBounds.bounds;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (nonRotated && element.angle !== 0) {
|
|
||||||
const nonRotatedBounds = ElementBounds.calculateBounds(
|
|
||||||
{
|
|
||||||
...element,
|
|
||||||
angle: 0 as Radians,
|
|
||||||
},
|
|
||||||
elementsMap,
|
|
||||||
);
|
|
||||||
ElementBounds.nonRotatedBoundsCache.set(element, {
|
|
||||||
version: element.version,
|
|
||||||
bounds: nonRotatedBounds,
|
|
||||||
});
|
|
||||||
|
|
||||||
return nonRotatedBounds;
|
|
||||||
}
|
|
||||||
|
|
||||||
const bounds = ElementBounds.calculateBounds(element, elementsMap);
|
const bounds = ElementBounds.calculateBounds(element, elementsMap);
|
||||||
|
|
||||||
ElementBounds.boundsCache.set(element, {
|
ElementBounds.boundsCache.set(element, {
|
||||||
@@ -313,42 +290,19 @@ export const getElementLineSegments = (
|
|||||||
|
|
||||||
if (shape.type === "polycurve") {
|
if (shape.type === "polycurve") {
|
||||||
const curves = shape.data;
|
const curves = shape.data;
|
||||||
const pointsOnCurves = curves.map((curve) =>
|
const points = curves
|
||||||
pointsOnBezierCurves(curve, 10),
|
.map((curve) => pointsOnBezierCurves(curve, 10))
|
||||||
);
|
.flat();
|
||||||
|
let i = 0;
|
||||||
const segments: LineSegment<GlobalPoint>[] = [];
|
const segments: LineSegment<GlobalPoint>[] = [];
|
||||||
|
while (i < points.length - 1) {
|
||||||
if (
|
segments.push(
|
||||||
(isLineElement(element) && !element.polygon) ||
|
lineSegment(
|
||||||
isArrowElement(element)
|
pointFrom(points[i][0], points[i][1]),
|
||||||
) {
|
pointFrom(points[i + 1][0], points[i + 1][1]),
|
||||||
for (const points of pointsOnCurves) {
|
),
|
||||||
let i = 0;
|
);
|
||||||
|
i++;
|
||||||
while (i < points.length - 1) {
|
|
||||||
segments.push(
|
|
||||||
lineSegment(
|
|
||||||
pointFrom(points[i][0], points[i][1]),
|
|
||||||
pointFrom(points[i + 1][0], points[i + 1][1]),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
const points = pointsOnCurves.flat();
|
|
||||||
let i = 0;
|
|
||||||
|
|
||||||
while (i < points.length - 1) {
|
|
||||||
segments.push(
|
|
||||||
lineSegment(
|
|
||||||
pointFrom(points[i][0], points[i][1]),
|
|
||||||
pointFrom(points[i + 1][0], points[i + 1][1]),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
i++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return segments;
|
return segments;
|
||||||
@@ -599,7 +553,7 @@ const solveQuadratic = (
|
|||||||
return [s1, s2];
|
return [s1, s2];
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getCubicBezierCurveBound = (
|
const getCubicBezierCurveBound = (
|
||||||
p0: GlobalPoint,
|
p0: GlobalPoint,
|
||||||
p1: GlobalPoint,
|
p1: GlobalPoint,
|
||||||
p2: GlobalPoint,
|
p2: GlobalPoint,
|
||||||
@@ -985,9 +939,8 @@ const getLinearElementRotatedBounds = (
|
|||||||
export const getElementBounds = (
|
export const getElementBounds = (
|
||||||
element: ExcalidrawElement,
|
element: ExcalidrawElement,
|
||||||
elementsMap: ElementsMap,
|
elementsMap: ElementsMap,
|
||||||
nonRotated: boolean = false,
|
|
||||||
): Bounds => {
|
): Bounds => {
|
||||||
return ElementBounds.getBounds(element, elementsMap, nonRotated);
|
return ElementBounds.getBounds(element, elementsMap);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getCommonBounds = (
|
export const getCommonBounds = (
|
||||||
@@ -1141,9 +1094,7 @@ export interface BoundingBox {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const getCommonBoundingBox = (
|
export const getCommonBoundingBox = (
|
||||||
elements:
|
elements: ExcalidrawElement[] | readonly NonDeleted<ExcalidrawElement>[],
|
||||||
| readonly ExcalidrawElement[]
|
|
||||||
| readonly NonDeleted<ExcalidrawElement>[],
|
|
||||||
): BoundingBox => {
|
): BoundingBox => {
|
||||||
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
||||||
return {
|
return {
|
||||||
@@ -1182,71 +1133,6 @@ export const getCenterForBounds = (bounds: Bounds): GlobalPoint =>
|
|||||||
bounds[1] + (bounds[3] - bounds[1]) / 2,
|
bounds[1] + (bounds[3] - bounds[1]) / 2,
|
||||||
);
|
);
|
||||||
|
|
||||||
/**
|
|
||||||
* Get the axis-aligned bounding box for a given element
|
|
||||||
*/
|
|
||||||
export const aabbForElement = (
|
|
||||||
element: Readonly<ExcalidrawElement>,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
offset?: [number, number, number, number],
|
|
||||||
) => {
|
|
||||||
const bbox = {
|
|
||||||
minX: element.x,
|
|
||||||
minY: element.y,
|
|
||||||
maxX: element.x + element.width,
|
|
||||||
maxY: element.y + element.height,
|
|
||||||
midX: element.x + element.width / 2,
|
|
||||||
midY: element.y + element.height / 2,
|
|
||||||
};
|
|
||||||
|
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
|
||||||
const [topLeftX, topLeftY] = pointRotateRads(
|
|
||||||
pointFrom(bbox.minX, bbox.minY),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
);
|
|
||||||
const [topRightX, topRightY] = pointRotateRads(
|
|
||||||
pointFrom(bbox.maxX, bbox.minY),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
);
|
|
||||||
const [bottomRightX, bottomRightY] = pointRotateRads(
|
|
||||||
pointFrom(bbox.maxX, bbox.maxY),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
);
|
|
||||||
const [bottomLeftX, bottomLeftY] = pointRotateRads(
|
|
||||||
pointFrom(bbox.minX, bbox.maxY),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
);
|
|
||||||
|
|
||||||
const bounds = [
|
|
||||||
Math.min(topLeftX, topRightX, bottomRightX, bottomLeftX),
|
|
||||||
Math.min(topLeftY, topRightY, bottomRightY, bottomLeftY),
|
|
||||||
Math.max(topLeftX, topRightX, bottomRightX, bottomLeftX),
|
|
||||||
Math.max(topLeftY, topRightY, bottomRightY, bottomLeftY),
|
|
||||||
] as Bounds;
|
|
||||||
|
|
||||||
if (offset) {
|
|
||||||
const [topOffset, rightOffset, downOffset, leftOffset] = offset;
|
|
||||||
return [
|
|
||||||
bounds[0] - leftOffset,
|
|
||||||
bounds[1] - topOffset,
|
|
||||||
bounds[2] + rightOffset,
|
|
||||||
bounds[3] + downOffset,
|
|
||||||
] as Bounds;
|
|
||||||
}
|
|
||||||
|
|
||||||
return bounds;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const pointInsideBounds = <P extends GlobalPoint | LocalPoint>(
|
|
||||||
p: P,
|
|
||||||
bounds: Bounds,
|
|
||||||
): boolean =>
|
|
||||||
p[0] > bounds[0] && p[0] < bounds[2] && p[1] > bounds[1] && p[1] < bounds[3];
|
|
||||||
|
|
||||||
export const doBoundsIntersect = (
|
export const doBoundsIntersect = (
|
||||||
bounds1: Bounds | null,
|
bounds1: Bounds | null,
|
||||||
bounds2: Bounds | null,
|
bounds2: Bounds | null,
|
||||||
@@ -1260,21 +1146,3 @@ export const doBoundsIntersect = (
|
|||||||
|
|
||||||
return minX1 < maxX2 && maxX1 > minX2 && minY1 < maxY2 && maxY1 > minY2;
|
return minX1 < maxX2 && maxX1 > minX2 && minY1 < maxY2 && maxY1 > minY2;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const elementCenterPoint = (
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
xOffset: number = 0,
|
|
||||||
yOffset: number = 0,
|
|
||||||
) => {
|
|
||||||
if (isLinearElement(element)) {
|
|
||||||
const [x1, y1, x2, y2] = getElementAbsoluteCoords(element, elementsMap);
|
|
||||||
const [x, y] = pointFrom<GlobalPoint>((x1 + x2) / 2, (y1 + y2) / 2);
|
|
||||||
|
|
||||||
return pointFrom<GlobalPoint>(x + xOffset, y + yOffset);
|
|
||||||
}
|
|
||||||
|
|
||||||
const [x, y] = getCenterForBounds(getElementBounds(element, elementsMap));
|
|
||||||
|
|
||||||
return pointFrom<GlobalPoint>(x + xOffset, y + yOffset);
|
|
||||||
};
|
|
||||||
|
|||||||
+129
-557
@@ -1,77 +1,53 @@
|
|||||||
import { invariant, isTransparent, type Bounds } from "@excalidraw/common";
|
import { isTransparent, elementCenterPoint } from "@excalidraw/common";
|
||||||
import {
|
import {
|
||||||
curveIntersectLineSegment,
|
curveIntersectLineSegment,
|
||||||
isPointWithinBounds,
|
isPointWithinBounds,
|
||||||
|
line,
|
||||||
lineSegment,
|
lineSegment,
|
||||||
lineSegmentIntersectionPoints,
|
lineSegmentIntersectionPoints,
|
||||||
pointFrom,
|
pointFrom,
|
||||||
pointFromVector,
|
|
||||||
pointRotateRads,
|
pointRotateRads,
|
||||||
pointsEqual,
|
pointsEqual,
|
||||||
vectorFromPoint,
|
|
||||||
vectorNormalize,
|
|
||||||
vectorScale,
|
|
||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
ellipse,
|
ellipse,
|
||||||
ellipseSegmentInterceptPoints,
|
ellipseLineIntersectionPoints,
|
||||||
} from "@excalidraw/math/ellipse";
|
} from "@excalidraw/math/ellipse";
|
||||||
|
|
||||||
|
import { isPointInShape, isPointOnShape } from "@excalidraw/utils/collision";
|
||||||
|
import { type GeometricShape, getPolygonShape } from "@excalidraw/utils/shape";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
Curve,
|
|
||||||
GlobalPoint,
|
GlobalPoint,
|
||||||
LineSegment,
|
LineSegment,
|
||||||
|
LocalPoint,
|
||||||
|
Polygon,
|
||||||
Radians,
|
Radians,
|
||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
|
|
||||||
import type { FrameNameBounds } from "@excalidraw/excalidraw/types";
|
import type { FrameNameBounds } from "@excalidraw/excalidraw/types";
|
||||||
|
|
||||||
import { isPathALoop } from "./utils";
|
import { getBoundTextShape, isPathALoop } from "./shapes";
|
||||||
import {
|
import { getElementBounds } from "./bounds";
|
||||||
doBoundsIntersect,
|
|
||||||
elementCenterPoint,
|
|
||||||
getCenterForBounds,
|
|
||||||
getCubicBezierCurveBound,
|
|
||||||
getDiamondPoints,
|
|
||||||
getElementBounds,
|
|
||||||
pointInsideBounds,
|
|
||||||
} from "./bounds";
|
|
||||||
import {
|
import {
|
||||||
hasBoundTextElement,
|
hasBoundTextElement,
|
||||||
isBindableElement,
|
|
||||||
isFrameLikeElement,
|
|
||||||
isFreeDrawElement,
|
|
||||||
isIframeLikeElement,
|
isIframeLikeElement,
|
||||||
isImageElement,
|
isImageElement,
|
||||||
isLinearElement,
|
|
||||||
isTextElement,
|
isTextElement,
|
||||||
} from "./typeChecks";
|
} from "./typeChecks";
|
||||||
import {
|
import {
|
||||||
deconstructDiamondElement,
|
deconstructDiamondElement,
|
||||||
deconstructLinearOrFreeDrawElement,
|
|
||||||
deconstructRectanguloidElement,
|
deconstructRectanguloidElement,
|
||||||
} from "./utils";
|
} from "./utils";
|
||||||
|
|
||||||
import { getBoundTextElement } from "./textElement";
|
|
||||||
|
|
||||||
import { LinearElementEditor } from "./linearElementEditor";
|
|
||||||
|
|
||||||
import { distanceToElement } from "./distance";
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ElementsMap,
|
ElementsMap,
|
||||||
ExcalidrawBindableElement,
|
|
||||||
ExcalidrawDiamondElement,
|
ExcalidrawDiamondElement,
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
ExcalidrawEllipseElement,
|
ExcalidrawEllipseElement,
|
||||||
ExcalidrawFreeDrawElement,
|
ExcalidrawRectangleElement,
|
||||||
ExcalidrawLinearElement,
|
|
||||||
ExcalidrawRectanguloidElement,
|
ExcalidrawRectanguloidElement,
|
||||||
NonDeleted,
|
|
||||||
NonDeletedExcalidrawElement,
|
|
||||||
NonDeletedSceneElementsMap,
|
|
||||||
Ordered,
|
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export const shouldTestInside = (element: ExcalidrawElement) => {
|
export const shouldTestInside = (element: ExcalidrawElement) => {
|
||||||
@@ -96,68 +72,45 @@ export const shouldTestInside = (element: ExcalidrawElement) => {
|
|||||||
return isDraggableFromInside || isImageElement(element);
|
return isDraggableFromInside || isImageElement(element);
|
||||||
};
|
};
|
||||||
|
|
||||||
export type HitTestArgs = {
|
export type HitTestArgs<Point extends GlobalPoint | LocalPoint> = {
|
||||||
point: GlobalPoint;
|
x: number;
|
||||||
|
y: number;
|
||||||
element: ExcalidrawElement;
|
element: ExcalidrawElement;
|
||||||
threshold: number;
|
shape: GeometricShape<Point>;
|
||||||
elementsMap: ElementsMap;
|
threshold?: number;
|
||||||
frameNameBound?: FrameNameBounds | null;
|
frameNameBound?: FrameNameBounds | null;
|
||||||
overrideShouldTestInside?: boolean;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const hitElementItself = ({
|
export const hitElementItself = <Point extends GlobalPoint | LocalPoint>({
|
||||||
point,
|
x,
|
||||||
|
y,
|
||||||
element,
|
element,
|
||||||
threshold,
|
shape,
|
||||||
elementsMap,
|
threshold = 10,
|
||||||
frameNameBound = null,
|
frameNameBound = null,
|
||||||
overrideShouldTestInside = false,
|
}: HitTestArgs<Point>) => {
|
||||||
}: HitTestArgs) => {
|
let hit = shouldTestInside(element)
|
||||||
// Hit test against a frame's name
|
|
||||||
const hitFrameName = frameNameBound
|
|
||||||
? isPointWithinBounds(
|
|
||||||
pointFrom(frameNameBound.x - threshold, frameNameBound.y - threshold),
|
|
||||||
point,
|
|
||||||
pointFrom(
|
|
||||||
frameNameBound.x + frameNameBound.width + threshold,
|
|
||||||
frameNameBound.y + frameNameBound.height + threshold,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
: false;
|
|
||||||
|
|
||||||
// Hit test against the extended, rotated bounding box of the element first
|
|
||||||
const bounds = getElementBounds(element, elementsMap, true);
|
|
||||||
const hitBounds = isPointWithinBounds(
|
|
||||||
pointFrom(bounds[0] - threshold, bounds[1] - threshold),
|
|
||||||
pointRotateRads(
|
|
||||||
point,
|
|
||||||
getCenterForBounds(bounds),
|
|
||||||
-element.angle as Radians,
|
|
||||||
),
|
|
||||||
pointFrom(bounds[2] + threshold, bounds[3] + threshold),
|
|
||||||
);
|
|
||||||
|
|
||||||
// PERF: Bail out early if the point is not even in the
|
|
||||||
// rotated bounding box or not hitting the frame name (saves 99%)
|
|
||||||
if (!hitBounds && !hitFrameName) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do the precise (and relatively costly) hit test
|
|
||||||
const hitElement = (
|
|
||||||
overrideShouldTestInside ? true : shouldTestInside(element)
|
|
||||||
)
|
|
||||||
? // Since `inShape` tests STRICTLY againt the insides of a shape
|
? // Since `inShape` tests STRICTLY againt the insides of a shape
|
||||||
// we would need `onShape` as well to include the "borders"
|
// we would need `onShape` as well to include the "borders"
|
||||||
isPointInElement(point, element, elementsMap) ||
|
isPointInShape(pointFrom(x, y), shape) ||
|
||||||
isPointOnElementOutline(point, element, elementsMap, threshold)
|
isPointOnShape(pointFrom(x, y), shape, threshold)
|
||||||
: isPointOnElementOutline(point, element, elementsMap, threshold);
|
: isPointOnShape(pointFrom(x, y), shape, threshold);
|
||||||
|
|
||||||
return hitElement || hitFrameName;
|
// hit test against a frame's name
|
||||||
|
if (!hit && frameNameBound) {
|
||||||
|
hit = isPointInShape(pointFrom(x, y), {
|
||||||
|
type: "polygon",
|
||||||
|
data: getPolygonShape(frameNameBound as ExcalidrawRectangleElement)
|
||||||
|
.data as Polygon<Point>,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return hit;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const hitElementBoundingBox = (
|
export const hitElementBoundingBox = (
|
||||||
point: GlobalPoint,
|
x: number,
|
||||||
|
y: number,
|
||||||
element: ExcalidrawElement,
|
element: ExcalidrawElement,
|
||||||
elementsMap: ElementsMap,
|
elementsMap: ElementsMap,
|
||||||
tolerance = 0,
|
tolerance = 0,
|
||||||
@@ -167,152 +120,37 @@ export const hitElementBoundingBox = (
|
|||||||
y1 -= tolerance;
|
y1 -= tolerance;
|
||||||
x2 += tolerance;
|
x2 += tolerance;
|
||||||
y2 += tolerance;
|
y2 += tolerance;
|
||||||
return isPointWithinBounds(pointFrom(x1, y1), point, pointFrom(x2, y2));
|
return isPointWithinBounds(
|
||||||
};
|
pointFrom(x1, y1),
|
||||||
|
pointFrom(x, y),
|
||||||
export const hitElementBoundingBoxOnly = (
|
pointFrom(x2, y2),
|
||||||
hitArgs: HitTestArgs,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
) =>
|
|
||||||
!hitElementItself(hitArgs) &&
|
|
||||||
// bound text is considered part of the element (even if it's outside the bounding box)
|
|
||||||
!hitElementBoundText(hitArgs.point, hitArgs.element, elementsMap) &&
|
|
||||||
hitElementBoundingBox(hitArgs.point, hitArgs.element, elementsMap);
|
|
||||||
|
|
||||||
export const hitElementBoundText = (
|
|
||||||
point: GlobalPoint,
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
): boolean => {
|
|
||||||
const boundTextElementCandidate = getBoundTextElement(element, elementsMap);
|
|
||||||
|
|
||||||
if (!boundTextElementCandidate) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
const boundTextElement = isLinearElement(element)
|
|
||||||
? {
|
|
||||||
...boundTextElementCandidate,
|
|
||||||
// arrow's bound text accurate position is not stored in the element's property
|
|
||||||
// but rather calculated and returned from the following static method
|
|
||||||
...LinearElementEditor.getBoundTextElementPosition(
|
|
||||||
element,
|
|
||||||
boundTextElementCandidate,
|
|
||||||
elementsMap,
|
|
||||||
),
|
|
||||||
}
|
|
||||||
: boundTextElementCandidate;
|
|
||||||
|
|
||||||
return isPointInElement(point, boundTextElement, elementsMap);
|
|
||||||
};
|
|
||||||
|
|
||||||
const bindingBorderTest = (
|
|
||||||
element: NonDeleted<ExcalidrawBindableElement>,
|
|
||||||
[x, y]: Readonly<GlobalPoint>,
|
|
||||||
elementsMap: NonDeletedSceneElementsMap,
|
|
||||||
tolerance: number = 0,
|
|
||||||
): boolean => {
|
|
||||||
const p = pointFrom<GlobalPoint>(x, y);
|
|
||||||
const shouldTestInside =
|
|
||||||
// disable fullshape snapping for frame elements so we
|
|
||||||
// can bind to frame children
|
|
||||||
!isFrameLikeElement(element);
|
|
||||||
|
|
||||||
// PERF: Run a cheap test to see if the binding element
|
|
||||||
// is even close to the element
|
|
||||||
const t = Math.max(1, tolerance);
|
|
||||||
const bounds = [x - t, y - t, x + t, y + t] as Bounds;
|
|
||||||
const elementBounds = getElementBounds(element, elementsMap);
|
|
||||||
if (!doBoundsIntersect(bounds, elementBounds)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If the element is inside a frame, we should clip the element
|
|
||||||
if (element.frameId) {
|
|
||||||
const enclosingFrame = elementsMap.get(element.frameId);
|
|
||||||
if (enclosingFrame && isFrameLikeElement(enclosingFrame)) {
|
|
||||||
const enclosingFrameBounds = getElementBounds(
|
|
||||||
enclosingFrame,
|
|
||||||
elementsMap,
|
|
||||||
);
|
|
||||||
if (!pointInsideBounds(p, enclosingFrameBounds)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do the intersection test against the element since it's close enough
|
|
||||||
const intersections = intersectElementWithLineSegment(
|
|
||||||
element,
|
|
||||||
elementsMap,
|
|
||||||
lineSegment(elementCenterPoint(element, elementsMap), p),
|
|
||||||
);
|
);
|
||||||
const distance = distanceToElement(element, elementsMap, p);
|
|
||||||
|
|
||||||
return shouldTestInside
|
|
||||||
? intersections.length === 0 || distance <= tolerance
|
|
||||||
: intersections.length > 0 && distance <= t;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getAllHoveredElementAtPoint = (
|
export const hitElementBoundingBoxOnly = <
|
||||||
point: Readonly<GlobalPoint>,
|
Point extends GlobalPoint | LocalPoint,
|
||||||
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
|
>(
|
||||||
elementsMap: NonDeletedSceneElementsMap,
|
hitArgs: HitTestArgs<Point>,
|
||||||
toleranceFn?: (element: ExcalidrawBindableElement) => number,
|
elementsMap: ElementsMap,
|
||||||
): NonDeleted<ExcalidrawBindableElement>[] => {
|
) => {
|
||||||
const candidateElements: NonDeleted<ExcalidrawBindableElement>[] = [];
|
return (
|
||||||
// We need to to hit testing from front (end of the array) to back (beginning of the array)
|
!hitElementItself(hitArgs) &&
|
||||||
// because array is ordered from lower z-index to highest and we want element z-index
|
// bound text is considered part of the element (even if it's outside the bounding box)
|
||||||
// with higher z-index
|
!hitElementBoundText(
|
||||||
for (let index = elements.length - 1; index >= 0; --index) {
|
hitArgs.x,
|
||||||
const element = elements[index];
|
hitArgs.y,
|
||||||
|
getBoundTextShape(hitArgs.element, elementsMap),
|
||||||
invariant(
|
) &&
|
||||||
!element.isDeleted,
|
hitElementBoundingBox(hitArgs.x, hitArgs.y, hitArgs.element, elementsMap)
|
||||||
"Elements in the function parameter for getAllElementsAtPositionForBinding() should not contain deleted elements",
|
|
||||||
);
|
|
||||||
|
|
||||||
if (
|
|
||||||
isBindableElement(element, false) &&
|
|
||||||
bindingBorderTest(element, point, elementsMap, toleranceFn?.(element))
|
|
||||||
) {
|
|
||||||
candidateElements.push(element);
|
|
||||||
|
|
||||||
if (!isTransparent(element.backgroundColor)) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return candidateElements;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getHoveredElementForBinding = (
|
|
||||||
point: Readonly<GlobalPoint>,
|
|
||||||
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
|
|
||||||
elementsMap: NonDeletedSceneElementsMap,
|
|
||||||
toleranceFn?: (element: ExcalidrawBindableElement) => number,
|
|
||||||
): NonDeleted<ExcalidrawBindableElement> | null => {
|
|
||||||
const candidateElements = getAllHoveredElementAtPoint(
|
|
||||||
point,
|
|
||||||
elements,
|
|
||||||
elementsMap,
|
|
||||||
toleranceFn,
|
|
||||||
);
|
);
|
||||||
|
};
|
||||||
|
|
||||||
if (!candidateElements || candidateElements.length === 0) {
|
export const hitElementBoundText = <Point extends GlobalPoint | LocalPoint>(
|
||||||
return null;
|
x: number,
|
||||||
}
|
y: number,
|
||||||
|
textShape: GeometricShape<Point> | null,
|
||||||
if (candidateElements.length === 1) {
|
): boolean => {
|
||||||
return candidateElements[0];
|
return !!textShape && isPointInShape(pointFrom(x, y), textShape);
|
||||||
}
|
|
||||||
|
|
||||||
// Prefer smaller shapes
|
|
||||||
return candidateElements
|
|
||||||
.sort(
|
|
||||||
(a, b) => b.width ** 2 + b.height ** 2 - (a.width ** 2 + a.height ** 2),
|
|
||||||
)
|
|
||||||
.pop() as NonDeleted<ExcalidrawBindableElement>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -325,26 +163,9 @@ export const getHoveredElementForBinding = (
|
|||||||
*/
|
*/
|
||||||
export const intersectElementWithLineSegment = (
|
export const intersectElementWithLineSegment = (
|
||||||
element: ExcalidrawElement,
|
element: ExcalidrawElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
line: LineSegment<GlobalPoint>,
|
line: LineSegment<GlobalPoint>,
|
||||||
offset: number = 0,
|
offset: number = 0,
|
||||||
onlyFirst = false,
|
|
||||||
): GlobalPoint[] => {
|
): GlobalPoint[] => {
|
||||||
// First check if the line intersects the element's axis-aligned bounding box
|
|
||||||
// as it is much faster than checking intersection against the element's shape
|
|
||||||
const intersectorBounds = [
|
|
||||||
Math.min(line[0][0] - offset, line[1][0] - offset),
|
|
||||||
Math.min(line[0][1] - offset, line[1][1] - offset),
|
|
||||||
Math.max(line[0][0] + offset, line[1][0] + offset),
|
|
||||||
Math.max(line[0][1] + offset, line[1][1] + offset),
|
|
||||||
] as Bounds;
|
|
||||||
const elementBounds = getElementBounds(element, elementsMap);
|
|
||||||
|
|
||||||
if (!doBoundsIntersect(intersectorBounds, elementBounds)) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
// Do the actual intersection test against the element's shape
|
|
||||||
switch (element.type) {
|
switch (element.type) {
|
||||||
case "rectangle":
|
case "rectangle":
|
||||||
case "image":
|
case "image":
|
||||||
@@ -352,196 +173,67 @@ export const intersectElementWithLineSegment = (
|
|||||||
case "iframe":
|
case "iframe":
|
||||||
case "embeddable":
|
case "embeddable":
|
||||||
case "frame":
|
case "frame":
|
||||||
case "selection":
|
|
||||||
case "magicframe":
|
case "magicframe":
|
||||||
return intersectRectanguloidWithLineSegment(
|
return intersectRectanguloidWithLineSegment(element, line, offset);
|
||||||
element,
|
|
||||||
elementsMap,
|
|
||||||
line,
|
|
||||||
offset,
|
|
||||||
onlyFirst,
|
|
||||||
);
|
|
||||||
case "diamond":
|
case "diamond":
|
||||||
return intersectDiamondWithLineSegment(
|
return intersectDiamondWithLineSegment(element, line, offset);
|
||||||
element,
|
|
||||||
elementsMap,
|
|
||||||
line,
|
|
||||||
offset,
|
|
||||||
onlyFirst,
|
|
||||||
);
|
|
||||||
case "ellipse":
|
case "ellipse":
|
||||||
return intersectEllipseWithLineSegment(
|
return intersectEllipseWithLineSegment(element, line, offset);
|
||||||
element,
|
default:
|
||||||
elementsMap,
|
throw new Error(`Unimplemented element type '${element.type}'`);
|
||||||
line,
|
|
||||||
offset,
|
|
||||||
);
|
|
||||||
case "line":
|
|
||||||
case "freedraw":
|
|
||||||
case "arrow":
|
|
||||||
return intersectLinearOrFreeDrawWithLineSegment(element, line, onlyFirst);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const curveIntersections = (
|
|
||||||
curves: Curve<GlobalPoint>[],
|
|
||||||
segment: LineSegment<GlobalPoint>,
|
|
||||||
intersections: GlobalPoint[],
|
|
||||||
center: GlobalPoint,
|
|
||||||
angle: Radians,
|
|
||||||
onlyFirst = false,
|
|
||||||
) => {
|
|
||||||
for (const c of curves) {
|
|
||||||
// Optimize by doing a cheap bounding box check first
|
|
||||||
const b1 = getCubicBezierCurveBound(c[0], c[1], c[2], c[3]);
|
|
||||||
const b2 = [
|
|
||||||
Math.min(segment[0][0], segment[1][0]),
|
|
||||||
Math.min(segment[0][1], segment[1][1]),
|
|
||||||
Math.max(segment[0][0], segment[1][0]),
|
|
||||||
Math.max(segment[0][1], segment[1][1]),
|
|
||||||
] as Bounds;
|
|
||||||
|
|
||||||
if (!doBoundsIntersect(b1, b2)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const hits = curveIntersectLineSegment(c, segment);
|
|
||||||
|
|
||||||
if (hits.length > 0) {
|
|
||||||
for (const j of hits) {
|
|
||||||
intersections.push(pointRotateRads(j, center, angle));
|
|
||||||
}
|
|
||||||
|
|
||||||
if (onlyFirst) {
|
|
||||||
return intersections;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return intersections;
|
|
||||||
};
|
|
||||||
|
|
||||||
const lineIntersections = (
|
|
||||||
lines: LineSegment<GlobalPoint>[],
|
|
||||||
segment: LineSegment<GlobalPoint>,
|
|
||||||
intersections: GlobalPoint[],
|
|
||||||
center: GlobalPoint,
|
|
||||||
angle: Radians,
|
|
||||||
onlyFirst = false,
|
|
||||||
) => {
|
|
||||||
for (const l of lines) {
|
|
||||||
const intersection = lineSegmentIntersectionPoints(l, segment);
|
|
||||||
if (intersection) {
|
|
||||||
intersections.push(pointRotateRads(intersection, center, angle));
|
|
||||||
|
|
||||||
if (onlyFirst) {
|
|
||||||
return intersections;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return intersections;
|
|
||||||
};
|
|
||||||
|
|
||||||
const intersectLinearOrFreeDrawWithLineSegment = (
|
|
||||||
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
|
|
||||||
segment: LineSegment<GlobalPoint>,
|
|
||||||
onlyFirst = false,
|
|
||||||
): GlobalPoint[] => {
|
|
||||||
// NOTE: This is the only one which return the decomposed elements
|
|
||||||
// rotated! This is due to taking advantage of roughjs definitions.
|
|
||||||
const [lines, curves] = deconstructLinearOrFreeDrawElement(element);
|
|
||||||
const intersections: GlobalPoint[] = [];
|
|
||||||
|
|
||||||
for (const l of lines) {
|
|
||||||
const intersection = lineSegmentIntersectionPoints(l, segment);
|
|
||||||
if (intersection) {
|
|
||||||
intersections.push(intersection);
|
|
||||||
|
|
||||||
if (onlyFirst) {
|
|
||||||
return intersections;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const c of curves) {
|
|
||||||
// Optimize by doing a cheap bounding box check first
|
|
||||||
const b1 = getCubicBezierCurveBound(c[0], c[1], c[2], c[3]);
|
|
||||||
const b2 = [
|
|
||||||
Math.min(segment[0][0], segment[1][0]),
|
|
||||||
Math.min(segment[0][1], segment[1][1]),
|
|
||||||
Math.max(segment[0][0], segment[1][0]),
|
|
||||||
Math.max(segment[0][1], segment[1][1]),
|
|
||||||
] as Bounds;
|
|
||||||
|
|
||||||
if (!doBoundsIntersect(b1, b2)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const hits = curveIntersectLineSegment(c, segment);
|
|
||||||
|
|
||||||
if (hits.length > 0) {
|
|
||||||
intersections.push(...hits);
|
|
||||||
|
|
||||||
if (onlyFirst) {
|
|
||||||
return intersections;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return intersections;
|
|
||||||
};
|
|
||||||
|
|
||||||
const intersectRectanguloidWithLineSegment = (
|
const intersectRectanguloidWithLineSegment = (
|
||||||
element: ExcalidrawRectanguloidElement,
|
element: ExcalidrawRectanguloidElement,
|
||||||
elementsMap: ElementsMap,
|
l: LineSegment<GlobalPoint>,
|
||||||
segment: LineSegment<GlobalPoint>,
|
|
||||||
offset: number = 0,
|
offset: number = 0,
|
||||||
onlyFirst = false,
|
|
||||||
): GlobalPoint[] => {
|
): GlobalPoint[] => {
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
const center = elementCenterPoint(element);
|
||||||
// To emulate a rotated rectangle we rotate the point in the inverse angle
|
// To emulate a rotated rectangle we rotate the point in the inverse angle
|
||||||
// instead. It's all the same distance-wise.
|
// instead. It's all the same distance-wise.
|
||||||
const rotatedA = pointRotateRads<GlobalPoint>(
|
const rotatedA = pointRotateRads<GlobalPoint>(
|
||||||
segment[0],
|
l[0],
|
||||||
center,
|
center,
|
||||||
-element.angle as Radians,
|
-element.angle as Radians,
|
||||||
);
|
);
|
||||||
const rotatedB = pointRotateRads<GlobalPoint>(
|
const rotatedB = pointRotateRads<GlobalPoint>(
|
||||||
segment[1],
|
l[1],
|
||||||
center,
|
center,
|
||||||
-element.angle as Radians,
|
-element.angle as Radians,
|
||||||
);
|
);
|
||||||
const rotatedIntersector = lineSegment(rotatedA, rotatedB);
|
|
||||||
|
|
||||||
// Get the element's building components we can test against
|
// Get the element's building components we can test against
|
||||||
const [sides, corners] = deconstructRectanguloidElement(element, offset);
|
const [sides, corners] = deconstructRectanguloidElement(element, offset);
|
||||||
|
|
||||||
const intersections: GlobalPoint[] = [];
|
return (
|
||||||
|
// Test intersection against the sides, keep only the valid
|
||||||
lineIntersections(
|
// intersection points and rotate them back to scene space
|
||||||
sides,
|
sides
|
||||||
rotatedIntersector,
|
.map((s) =>
|
||||||
intersections,
|
lineSegmentIntersectionPoints(
|
||||||
center,
|
lineSegment<GlobalPoint>(rotatedA, rotatedB),
|
||||||
element.angle,
|
s,
|
||||||
onlyFirst,
|
),
|
||||||
|
)
|
||||||
|
.filter((x) => x != null)
|
||||||
|
.map((j) => pointRotateRads<GlobalPoint>(j!, center, element.angle))
|
||||||
|
// Test intersection against the corners which are cubic bezier curves,
|
||||||
|
// keep only the valid intersection points and rotate them back to scene
|
||||||
|
// space
|
||||||
|
.concat(
|
||||||
|
corners
|
||||||
|
.flatMap((t) =>
|
||||||
|
curveIntersectLineSegment(t, lineSegment(rotatedA, rotatedB)),
|
||||||
|
)
|
||||||
|
.filter((i) => i != null)
|
||||||
|
.map((j) => pointRotateRads(j, center, element.angle)),
|
||||||
|
)
|
||||||
|
// Remove duplicates
|
||||||
|
.filter(
|
||||||
|
(p, idx, points) => points.findIndex((d) => pointsEqual(p, d)) === idx,
|
||||||
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (onlyFirst && intersections.length > 0) {
|
|
||||||
return intersections;
|
|
||||||
}
|
|
||||||
|
|
||||||
curveIntersections(
|
|
||||||
corners,
|
|
||||||
rotatedIntersector,
|
|
||||||
intersections,
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
onlyFirst,
|
|
||||||
);
|
|
||||||
|
|
||||||
return intersections;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -553,45 +245,43 @@ const intersectRectanguloidWithLineSegment = (
|
|||||||
*/
|
*/
|
||||||
const intersectDiamondWithLineSegment = (
|
const intersectDiamondWithLineSegment = (
|
||||||
element: ExcalidrawDiamondElement,
|
element: ExcalidrawDiamondElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
l: LineSegment<GlobalPoint>,
|
l: LineSegment<GlobalPoint>,
|
||||||
offset: number = 0,
|
offset: number = 0,
|
||||||
onlyFirst = false,
|
|
||||||
): GlobalPoint[] => {
|
): GlobalPoint[] => {
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
const center = elementCenterPoint(element);
|
||||||
|
|
||||||
// Rotate the point to the inverse direction to simulate the rotated diamond
|
// Rotate the point to the inverse direction to simulate the rotated diamond
|
||||||
// points. It's all the same distance-wise.
|
// points. It's all the same distance-wise.
|
||||||
const rotatedA = pointRotateRads(l[0], center, -element.angle as Radians);
|
const rotatedA = pointRotateRads(l[0], center, -element.angle as Radians);
|
||||||
const rotatedB = pointRotateRads(l[1], center, -element.angle as Radians);
|
const rotatedB = pointRotateRads(l[1], center, -element.angle as Radians);
|
||||||
const rotatedIntersector = lineSegment(rotatedA, rotatedB);
|
|
||||||
|
|
||||||
const [sides, corners] = deconstructDiamondElement(element, offset);
|
const [sides, curves] = deconstructDiamondElement(element, offset);
|
||||||
const intersections: GlobalPoint[] = [];
|
|
||||||
|
|
||||||
lineIntersections(
|
return (
|
||||||
sides,
|
sides
|
||||||
rotatedIntersector,
|
.map((s) =>
|
||||||
intersections,
|
lineSegmentIntersectionPoints(
|
||||||
center,
|
lineSegment<GlobalPoint>(rotatedA, rotatedB),
|
||||||
element.angle,
|
s,
|
||||||
onlyFirst,
|
),
|
||||||
|
)
|
||||||
|
.filter((p): p is GlobalPoint => p != null)
|
||||||
|
// Rotate back intersection points
|
||||||
|
.map((p) => pointRotateRads<GlobalPoint>(p!, center, element.angle))
|
||||||
|
.concat(
|
||||||
|
curves
|
||||||
|
.flatMap((p) =>
|
||||||
|
curveIntersectLineSegment(p, lineSegment(rotatedA, rotatedB)),
|
||||||
|
)
|
||||||
|
.filter((p) => p != null)
|
||||||
|
// Rotate back intersection points
|
||||||
|
.map((p) => pointRotateRads(p, center, element.angle)),
|
||||||
|
)
|
||||||
|
// Remove duplicates
|
||||||
|
.filter(
|
||||||
|
(p, idx, points) => points.findIndex((d) => pointsEqual(p, d)) === idx,
|
||||||
|
)
|
||||||
);
|
);
|
||||||
|
|
||||||
if (onlyFirst && intersections.length > 0) {
|
|
||||||
return intersections;
|
|
||||||
}
|
|
||||||
|
|
||||||
curveIntersections(
|
|
||||||
corners,
|
|
||||||
rotatedIntersector,
|
|
||||||
intersections,
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
onlyFirst,
|
|
||||||
);
|
|
||||||
|
|
||||||
return intersections;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -603,134 +293,16 @@ const intersectDiamondWithLineSegment = (
|
|||||||
*/
|
*/
|
||||||
const intersectEllipseWithLineSegment = (
|
const intersectEllipseWithLineSegment = (
|
||||||
element: ExcalidrawEllipseElement,
|
element: ExcalidrawEllipseElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
l: LineSegment<GlobalPoint>,
|
l: LineSegment<GlobalPoint>,
|
||||||
offset: number = 0,
|
offset: number = 0,
|
||||||
): GlobalPoint[] => {
|
): GlobalPoint[] => {
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
const center = elementCenterPoint(element);
|
||||||
|
|
||||||
const rotatedA = pointRotateRads(l[0], center, -element.angle as Radians);
|
const rotatedA = pointRotateRads(l[0], center, -element.angle as Radians);
|
||||||
const rotatedB = pointRotateRads(l[1], center, -element.angle as Radians);
|
const rotatedB = pointRotateRads(l[1], center, -element.angle as Radians);
|
||||||
|
|
||||||
return ellipseSegmentInterceptPoints(
|
return ellipseLineIntersectionPoints(
|
||||||
ellipse(center, element.width / 2 + offset, element.height / 2 + offset),
|
ellipse(center, element.width / 2 + offset, element.height / 2 + offset),
|
||||||
lineSegment(rotatedA, rotatedB),
|
line(rotatedA, rotatedB),
|
||||||
).map((p) => pointRotateRads(p, center, element.angle));
|
).map((p) => pointRotateRads(p, center, element.angle));
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the given point is considered on the given shape's border
|
|
||||||
*
|
|
||||||
* @param point
|
|
||||||
* @param element
|
|
||||||
* @param tolerance
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
const isPointOnElementOutline = (
|
|
||||||
point: GlobalPoint,
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
tolerance = 1,
|
|
||||||
) => distanceToElement(element, elementsMap, point) <= tolerance;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Check if the given point is considered inside the element's border
|
|
||||||
*
|
|
||||||
* @param point
|
|
||||||
* @param element
|
|
||||||
* @returns
|
|
||||||
*/
|
|
||||||
export const isPointInElement = (
|
|
||||||
point: GlobalPoint,
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
) => {
|
|
||||||
if (
|
|
||||||
(isLinearElement(element) || isFreeDrawElement(element)) &&
|
|
||||||
!isPathALoop(element.points)
|
|
||||||
) {
|
|
||||||
// There isn't any "inside" for a non-looping path
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const [x1, y1, x2, y2] = getElementBounds(element, elementsMap);
|
|
||||||
|
|
||||||
if (!isPointWithinBounds(pointFrom(x1, y1), point, pointFrom(x2, y2))) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const center = pointFrom<GlobalPoint>((x1 + x2) / 2, (y1 + y2) / 2);
|
|
||||||
const otherPoint = pointFromVector(
|
|
||||||
vectorScale(
|
|
||||||
vectorNormalize(vectorFromPoint(point, center, 0.1)),
|
|
||||||
Math.max(element.width, element.height) * 2,
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
);
|
|
||||||
const intersector = lineSegment(point, otherPoint);
|
|
||||||
const intersections = intersectElementWithLineSegment(
|
|
||||||
element,
|
|
||||||
elementsMap,
|
|
||||||
intersector,
|
|
||||||
).filter((p, pos, arr) => arr.findIndex((q) => pointsEqual(q, p)) === pos);
|
|
||||||
|
|
||||||
return intersections.length % 2 === 1;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const isBindableElementInsideOtherBindable = (
|
|
||||||
innerElement: ExcalidrawBindableElement,
|
|
||||||
outerElement: ExcalidrawBindableElement,
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
): boolean => {
|
|
||||||
// Get corner points of the inner element based on its type
|
|
||||||
const getCornerPoints = (
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
offset: number,
|
|
||||||
): GlobalPoint[] => {
|
|
||||||
const { x, y, width, height, angle } = element;
|
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
|
||||||
|
|
||||||
if (element.type === "diamond") {
|
|
||||||
// Diamond has 4 corner points at the middle of each side
|
|
||||||
const [topX, topY, rightX, rightY, bottomX, bottomY, leftX, leftY] =
|
|
||||||
getDiamondPoints(element);
|
|
||||||
const corners: GlobalPoint[] = [
|
|
||||||
pointFrom(x + topX, y + topY - offset), // top
|
|
||||||
pointFrom(x + rightX + offset, y + rightY), // right
|
|
||||||
pointFrom(x + bottomX, y + bottomY + offset), // bottom
|
|
||||||
pointFrom(x + leftX - offset, y + leftY), // left
|
|
||||||
];
|
|
||||||
return corners.map((corner) => pointRotateRads(corner, center, angle));
|
|
||||||
}
|
|
||||||
if (element.type === "ellipse") {
|
|
||||||
// For ellipse, test points at the extremes (top, right, bottom, left)
|
|
||||||
const cx = x + width / 2;
|
|
||||||
const cy = y + height / 2;
|
|
||||||
const rx = width / 2;
|
|
||||||
const ry = height / 2;
|
|
||||||
const corners: GlobalPoint[] = [
|
|
||||||
pointFrom(cx, cy - ry - offset), // top
|
|
||||||
pointFrom(cx + rx + offset, cy), // right
|
|
||||||
pointFrom(cx, cy + ry + offset), // bottom
|
|
||||||
pointFrom(cx - rx - offset, cy), // left
|
|
||||||
];
|
|
||||||
return corners.map((corner) => pointRotateRads(corner, center, angle));
|
|
||||||
}
|
|
||||||
// Rectangle and other rectangular shapes (image, text, etc.)
|
|
||||||
const corners: GlobalPoint[] = [
|
|
||||||
pointFrom(x - offset, y - offset), // top-left
|
|
||||||
pointFrom(x + width + offset, y - offset), // top-right
|
|
||||||
pointFrom(x + width + offset, y + height + offset), // bottom-right
|
|
||||||
pointFrom(x - offset, y + height + offset), // bottom-left
|
|
||||||
];
|
|
||||||
return corners.map((corner) => pointRotateRads(corner, center, angle));
|
|
||||||
};
|
|
||||||
|
|
||||||
const offset = (-1 * Math.max(innerElement.width, innerElement.height)) / 20; // 5% offset
|
|
||||||
const innerCorners = getCornerPoints(innerElement, offset);
|
|
||||||
|
|
||||||
// Check if all corner points of the inner element are inside the outer element
|
|
||||||
return innerCorners.every((corner) =>
|
|
||||||
isPointInElement(corner, outerElement, elementsMap),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -10,14 +10,7 @@ export const hasBackground = (type: ElementOrToolType) =>
|
|||||||
type === "freedraw";
|
type === "freedraw";
|
||||||
|
|
||||||
export const hasStrokeColor = (type: ElementOrToolType) =>
|
export const hasStrokeColor = (type: ElementOrToolType) =>
|
||||||
type === "rectangle" ||
|
type !== "image" && type !== "frame" && type !== "magicframe";
|
||||||
type === "ellipse" ||
|
|
||||||
type === "diamond" ||
|
|
||||||
type === "freedraw" ||
|
|
||||||
type === "arrow" ||
|
|
||||||
type === "line" ||
|
|
||||||
type === "text" ||
|
|
||||||
type === "embeddable";
|
|
||||||
|
|
||||||
export const hasStrokeWidth = (type: ElementOrToolType) =>
|
export const hasStrokeWidth = (type: ElementOrToolType) =>
|
||||||
type === "rectangle" ||
|
type === "rectangle" ||
|
||||||
|
|||||||
@@ -14,8 +14,9 @@ import {
|
|||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
import { type Point } from "points-on-curve";
|
import { type Point } from "points-on-curve";
|
||||||
|
|
||||||
|
import { elementCenterPoint } from "@excalidraw/common";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
elementCenterPoint,
|
|
||||||
getElementAbsoluteCoords,
|
getElementAbsoluteCoords,
|
||||||
getResizedElementAbsoluteCoords,
|
getResizedElementAbsoluteCoords,
|
||||||
} from "./bounds";
|
} from "./bounds";
|
||||||
@@ -33,7 +34,6 @@ export const MINIMAL_CROP_SIZE = 10;
|
|||||||
|
|
||||||
export const cropElement = (
|
export const cropElement = (
|
||||||
element: ExcalidrawImageElement,
|
element: ExcalidrawImageElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
transformHandle: TransformHandleType,
|
transformHandle: TransformHandleType,
|
||||||
naturalWidth: number,
|
naturalWidth: number,
|
||||||
naturalHeight: number,
|
naturalHeight: number,
|
||||||
@@ -63,7 +63,7 @@ export const cropElement = (
|
|||||||
|
|
||||||
const rotatedPointer = pointRotateRads(
|
const rotatedPointer = pointRotateRads(
|
||||||
pointFrom(pointerX, pointerY),
|
pointFrom(pointerX, pointerY),
|
||||||
elementCenterPoint(element, elementsMap),
|
elementCenterPoint(element),
|
||||||
-element.angle as Radians,
|
-element.angle as Radians,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
|||||||
@@ -6,33 +6,27 @@ import {
|
|||||||
|
|
||||||
import { ellipse, ellipseDistanceFromPoint } from "@excalidraw/math/ellipse";
|
import { ellipse, ellipseDistanceFromPoint } from "@excalidraw/math/ellipse";
|
||||||
|
|
||||||
|
import { elementCenterPoint } from "@excalidraw/common";
|
||||||
|
|
||||||
import type { GlobalPoint, Radians } from "@excalidraw/math";
|
import type { GlobalPoint, Radians } from "@excalidraw/math";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
deconstructDiamondElement,
|
deconstructDiamondElement,
|
||||||
deconstructLinearOrFreeDrawElement,
|
|
||||||
deconstructRectanguloidElement,
|
deconstructRectanguloidElement,
|
||||||
} from "./utils";
|
} from "./utils";
|
||||||
|
|
||||||
import { elementCenterPoint } from "./bounds";
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ElementsMap,
|
ExcalidrawBindableElement,
|
||||||
ExcalidrawDiamondElement,
|
ExcalidrawDiamondElement,
|
||||||
ExcalidrawElement,
|
|
||||||
ExcalidrawEllipseElement,
|
ExcalidrawEllipseElement,
|
||||||
ExcalidrawFreeDrawElement,
|
|
||||||
ExcalidrawLinearElement,
|
|
||||||
ExcalidrawRectanguloidElement,
|
ExcalidrawRectanguloidElement,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export const distanceToElement = (
|
export const distanceToBindableElement = (
|
||||||
element: ExcalidrawElement,
|
element: ExcalidrawBindableElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
p: GlobalPoint,
|
p: GlobalPoint,
|
||||||
): number => {
|
): number => {
|
||||||
switch (element.type) {
|
switch (element.type) {
|
||||||
case "selection":
|
|
||||||
case "rectangle":
|
case "rectangle":
|
||||||
case "image":
|
case "image":
|
||||||
case "text":
|
case "text":
|
||||||
@@ -40,15 +34,11 @@ export const distanceToElement = (
|
|||||||
case "embeddable":
|
case "embeddable":
|
||||||
case "frame":
|
case "frame":
|
||||||
case "magicframe":
|
case "magicframe":
|
||||||
return distanceToRectanguloidElement(element, elementsMap, p);
|
return distanceToRectanguloidElement(element, p);
|
||||||
case "diamond":
|
case "diamond":
|
||||||
return distanceToDiamondElement(element, elementsMap, p);
|
return distanceToDiamondElement(element, p);
|
||||||
case "ellipse":
|
case "ellipse":
|
||||||
return distanceToEllipseElement(element, elementsMap, p);
|
return distanceToEllipseElement(element, p);
|
||||||
case "line":
|
|
||||||
case "arrow":
|
|
||||||
case "freedraw":
|
|
||||||
return distanceToLinearOrFreeDraElement(element, p);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -62,10 +52,9 @@ export const distanceToElement = (
|
|||||||
*/
|
*/
|
||||||
const distanceToRectanguloidElement = (
|
const distanceToRectanguloidElement = (
|
||||||
element: ExcalidrawRectanguloidElement,
|
element: ExcalidrawRectanguloidElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
p: GlobalPoint,
|
p: GlobalPoint,
|
||||||
) => {
|
) => {
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
const center = elementCenterPoint(element);
|
||||||
// To emulate a rotated rectangle we rotate the point in the inverse angle
|
// To emulate a rotated rectangle we rotate the point in the inverse angle
|
||||||
// instead. It's all the same distance-wise.
|
// instead. It's all the same distance-wise.
|
||||||
const rotatedPoint = pointRotateRads(p, center, -element.angle as Radians);
|
const rotatedPoint = pointRotateRads(p, center, -element.angle as Radians);
|
||||||
@@ -91,10 +80,9 @@ const distanceToRectanguloidElement = (
|
|||||||
*/
|
*/
|
||||||
const distanceToDiamondElement = (
|
const distanceToDiamondElement = (
|
||||||
element: ExcalidrawDiamondElement,
|
element: ExcalidrawDiamondElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
p: GlobalPoint,
|
p: GlobalPoint,
|
||||||
): number => {
|
): number => {
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
const center = elementCenterPoint(element);
|
||||||
|
|
||||||
// Rotate the point to the inverse direction to simulate the rotated diamond
|
// Rotate the point to the inverse direction to simulate the rotated diamond
|
||||||
// points. It's all the same distance-wise.
|
// points. It's all the same distance-wise.
|
||||||
@@ -120,24 +108,12 @@ const distanceToDiamondElement = (
|
|||||||
*/
|
*/
|
||||||
const distanceToEllipseElement = (
|
const distanceToEllipseElement = (
|
||||||
element: ExcalidrawEllipseElement,
|
element: ExcalidrawEllipseElement,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
p: GlobalPoint,
|
p: GlobalPoint,
|
||||||
): number => {
|
): number => {
|
||||||
const center = elementCenterPoint(element, elementsMap);
|
const center = elementCenterPoint(element);
|
||||||
return ellipseDistanceFromPoint(
|
return ellipseDistanceFromPoint(
|
||||||
// Instead of rotating the ellipse, rotate the point to the inverse angle
|
// Instead of rotating the ellipse, rotate the point to the inverse angle
|
||||||
pointRotateRads(p, center, -element.angle as Radians),
|
pointRotateRads(p, center, -element.angle as Radians),
|
||||||
ellipse(center, element.width / 2, element.height / 2),
|
ellipse(center, element.width / 2, element.height / 2),
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
const distanceToLinearOrFreeDraElement = (
|
|
||||||
element: ExcalidrawLinearElement | ExcalidrawFreeDrawElement,
|
|
||||||
p: GlobalPoint,
|
|
||||||
) => {
|
|
||||||
const [lines, curves] = deconstructLinearOrFreeDrawElement(element);
|
|
||||||
return Math.min(
|
|
||||||
...lines.map((s) => distanceToLineSegment(p, s)),
|
|
||||||
...curves.map((a) => curvePointDistance(a, p)),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import type { AppState } from "@excalidraw/excalidraw/types";
|
|
||||||
|
|
||||||
import { getCommonBoundingBox } from "./bounds";
|
import { getCommonBoundingBox } from "./bounds";
|
||||||
import { newElementWith } from "./mutateElement";
|
import { newElementWith } from "./mutateElement";
|
||||||
|
|
||||||
import { getSelectedElementsByGroup } from "./groups";
|
import { getMaximumGroups } from "./groups";
|
||||||
|
|
||||||
import type { ElementsMap, ExcalidrawElement } from "./types";
|
import type { ElementsMap, ExcalidrawElement } from "./types";
|
||||||
|
|
||||||
@@ -16,7 +14,6 @@ export const distributeElements = (
|
|||||||
selectedElements: ExcalidrawElement[],
|
selectedElements: ExcalidrawElement[],
|
||||||
elementsMap: ElementsMap,
|
elementsMap: ElementsMap,
|
||||||
distribution: Distribution,
|
distribution: Distribution,
|
||||||
appState: Readonly<AppState>,
|
|
||||||
): ExcalidrawElement[] => {
|
): ExcalidrawElement[] => {
|
||||||
const [start, mid, end, extent] =
|
const [start, mid, end, extent] =
|
||||||
distribution.axis === "x"
|
distribution.axis === "x"
|
||||||
@@ -24,11 +21,7 @@ export const distributeElements = (
|
|||||||
: (["minY", "midY", "maxY", "height"] as const);
|
: (["minY", "midY", "maxY", "height"] as const);
|
||||||
|
|
||||||
const bounds = getCommonBoundingBox(selectedElements);
|
const bounds = getCommonBoundingBox(selectedElements);
|
||||||
const groups = getSelectedElementsByGroup(
|
const groups = getMaximumGroups(selectedElements, elementsMap)
|
||||||
selectedElements,
|
|
||||||
elementsMap,
|
|
||||||
appState,
|
|
||||||
)
|
|
||||||
.map((group) => [group, getCommonBoundingBox(group)] as const)
|
.map((group) => [group, getCommonBoundingBox(group)] as const)
|
||||||
.sort((a, b) => a[1][mid] - b[1][mid]);
|
.sort((a, b) => a[1][mid] - b[1][mid]);
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
type Bounds,
|
|
||||||
TEXT_AUTOWRAP_THRESHOLD,
|
TEXT_AUTOWRAP_THRESHOLD,
|
||||||
getGridPoint,
|
getGridPoint,
|
||||||
getFontString,
|
getFontString,
|
||||||
DRAGGING_THRESHOLD,
|
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
@@ -15,7 +13,7 @@ import type {
|
|||||||
|
|
||||||
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
|
import type { NonDeletedExcalidrawElement } from "@excalidraw/element/types";
|
||||||
|
|
||||||
import { unbindBindingElement, updateBoundElements } from "./binding";
|
import { updateBoundElements } from "./binding";
|
||||||
import { getCommonBounds } from "./bounds";
|
import { getCommonBounds } from "./bounds";
|
||||||
import { getPerfectElementSize } from "./sizeHelpers";
|
import { getPerfectElementSize } from "./sizeHelpers";
|
||||||
import { getBoundTextElement } from "./textElement";
|
import { getBoundTextElement } from "./textElement";
|
||||||
@@ -28,8 +26,9 @@ import {
|
|||||||
isTextElement,
|
isTextElement,
|
||||||
} from "./typeChecks";
|
} from "./typeChecks";
|
||||||
|
|
||||||
import type { Scene } from "./Scene";
|
import type Scene from "./Scene";
|
||||||
|
|
||||||
|
import type { Bounds } from "./bounds";
|
||||||
import type { ExcalidrawElement } from "./types";
|
import type { ExcalidrawElement } from "./types";
|
||||||
|
|
||||||
export const dragSelectedElements = (
|
export const dragSelectedElements = (
|
||||||
@@ -103,26 +102,9 @@ export const dragSelectedElements = (
|
|||||||
gridSize,
|
gridSize,
|
||||||
);
|
);
|
||||||
|
|
||||||
const elementsToUpdateIds = new Set(
|
|
||||||
Array.from(elementsToUpdate, (el) => el.id),
|
|
||||||
);
|
|
||||||
|
|
||||||
elementsToUpdate.forEach((element) => {
|
elementsToUpdate.forEach((element) => {
|
||||||
const isArrow = !isArrowElement(element);
|
updateElementCoords(pointerDownState, element, scene, adjustedOffset);
|
||||||
const isStartBoundElementSelected =
|
|
||||||
isArrow ||
|
|
||||||
(element.startBinding
|
|
||||||
? elementsToUpdateIds.has(element.startBinding.elementId)
|
|
||||||
: false);
|
|
||||||
const isEndBoundElementSelected =
|
|
||||||
isArrow ||
|
|
||||||
(element.endBinding
|
|
||||||
? elementsToUpdateIds.has(element.endBinding.elementId)
|
|
||||||
: false);
|
|
||||||
|
|
||||||
if (!isArrowElement(element)) {
|
if (!isArrowElement(element)) {
|
||||||
updateElementCoords(pointerDownState, element, scene, adjustedOffset);
|
|
||||||
|
|
||||||
// skip arrow labels since we calculate its position during render
|
// skip arrow labels since we calculate its position during render
|
||||||
const textElement = getBoundTextElement(
|
const textElement = getBoundTextElement(
|
||||||
element,
|
element,
|
||||||
@@ -139,33 +121,6 @@ export const dragSelectedElements = (
|
|||||||
updateBoundElements(element, scene, {
|
updateBoundElements(element, scene, {
|
||||||
simultaneouslyUpdated: Array.from(elementsToUpdate),
|
simultaneouslyUpdated: Array.from(elementsToUpdate),
|
||||||
});
|
});
|
||||||
} else if (
|
|
||||||
// NOTE: Add a little initial drag to the arrow dragging when the arrow
|
|
||||||
// is the single element being dragged to avoid accidentally unbinding
|
|
||||||
// the arrow when the user just wants to select it.
|
|
||||||
|
|
||||||
elementsToUpdate.size > 1 ||
|
|
||||||
Math.max(Math.abs(adjustedOffset.x), Math.abs(adjustedOffset.y)) >
|
|
||||||
DRAGGING_THRESHOLD ||
|
|
||||||
(!element.startBinding && !element.endBinding)
|
|
||||||
) {
|
|
||||||
updateElementCoords(pointerDownState, element, scene, adjustedOffset);
|
|
||||||
|
|
||||||
const shouldUnbindStart =
|
|
||||||
element.startBinding && !isStartBoundElementSelected;
|
|
||||||
const shouldUnbindEnd = element.endBinding && !isEndBoundElementSelected;
|
|
||||||
if (shouldUnbindStart || shouldUnbindEnd) {
|
|
||||||
// NOTE: Moving the bound arrow should unbind it, otherwise we would
|
|
||||||
// have weird situations, like 0 lenght arrow when the user moves
|
|
||||||
// the arrow outside a filled shape suddenly forcing the arrow start
|
|
||||||
// and end point to jump "outside" the shape.
|
|
||||||
if (shouldUnbindStart) {
|
|
||||||
unbindBindingElement(element, "start", scene);
|
|
||||||
}
|
|
||||||
if (shouldUnbindEnd) {
|
|
||||||
unbindBindingElement(element, "end", scene);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -14,26 +14,25 @@ import {
|
|||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
type Bounds,
|
|
||||||
BinaryHeap,
|
BinaryHeap,
|
||||||
invariant,
|
invariant,
|
||||||
isAnyTrue,
|
isAnyTrue,
|
||||||
|
tupleToCoors,
|
||||||
getSizeFromPoints,
|
getSizeFromPoints,
|
||||||
isDevEnv,
|
isDevEnv,
|
||||||
arrayToMap,
|
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import type { AppState } from "@excalidraw/excalidraw/types";
|
import type { AppState } from "@excalidraw/excalidraw/types";
|
||||||
|
|
||||||
import {
|
import {
|
||||||
bindPointToSnapToElementOutline,
|
bindPointToSnapToElementOutline,
|
||||||
|
FIXED_BINDING_DISTANCE,
|
||||||
getHeadingForElbowArrowSnap,
|
getHeadingForElbowArrowSnap,
|
||||||
getGlobalFixedPointForBindableElement,
|
getGlobalFixedPointForBindableElement,
|
||||||
getBindingGap,
|
snapToMid,
|
||||||
maxBindingDistance_simple,
|
getHoveredElementForBinding,
|
||||||
BASE_BINDING_GAP_ELBOW,
|
|
||||||
} from "./binding";
|
} from "./binding";
|
||||||
import { distanceToElement } from "./distance";
|
import { distanceToBindableElement } from "./distance";
|
||||||
import {
|
import {
|
||||||
compareHeading,
|
compareHeading,
|
||||||
flipHeading,
|
flipHeading,
|
||||||
@@ -52,9 +51,10 @@ import {
|
|||||||
type ExcalidrawElbowArrowElement,
|
type ExcalidrawElbowArrowElement,
|
||||||
type NonDeletedSceneElementsMap,
|
type NonDeletedSceneElementsMap,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
import { aabbForElement, pointInsideBounds } from "./bounds";
|
|
||||||
import { getHoveredElementForBinding } from "./collision";
|
|
||||||
|
|
||||||
|
import { aabbForElement, pointInsideBounds } from "./shapes";
|
||||||
|
|
||||||
|
import type { Bounds } from "./bounds";
|
||||||
import type { Heading } from "./heading";
|
import type { Heading } from "./heading";
|
||||||
import type {
|
import type {
|
||||||
Arrowhead,
|
Arrowhead,
|
||||||
@@ -63,7 +63,6 @@ import type {
|
|||||||
FixedPointBinding,
|
FixedPointBinding,
|
||||||
FixedSegment,
|
FixedSegment,
|
||||||
NonDeletedExcalidrawElement,
|
NonDeletedExcalidrawElement,
|
||||||
Ordered,
|
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
type GridAddress = [number, number] & { _brand: "gridaddress" };
|
type GridAddress = [number, number] & { _brand: "gridaddress" };
|
||||||
@@ -360,12 +359,6 @@ const handleSegmentRelease = (
|
|||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!restoredPoints || restoredPoints.length < 2) {
|
|
||||||
throw new Error(
|
|
||||||
"Property 'points' is required in the update returned by normalizeArrowElementUpdate()",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const nextPoints: GlobalPoint[] = [];
|
const nextPoints: GlobalPoint[] = [];
|
||||||
|
|
||||||
// First part of the arrow are the old points
|
// First part of the arrow are the old points
|
||||||
@@ -713,7 +706,7 @@ const handleEndpointDrag = (
|
|||||||
endGlobalPoint: GlobalPoint,
|
endGlobalPoint: GlobalPoint,
|
||||||
hoveredStartElement: ExcalidrawBindableElement | null,
|
hoveredStartElement: ExcalidrawBindableElement | null,
|
||||||
hoveredEndElement: ExcalidrawBindableElement | null,
|
hoveredEndElement: ExcalidrawBindableElement | null,
|
||||||
): ElementUpdate<ExcalidrawElbowArrowElement> => {
|
) => {
|
||||||
let startIsSpecial = arrow.startIsSpecial ?? null;
|
let startIsSpecial = arrow.startIsSpecial ?? null;
|
||||||
let endIsSpecial = arrow.endIsSpecial ?? null;
|
let endIsSpecial = arrow.endIsSpecial ?? null;
|
||||||
const globalUpdatedPoints = updatedPoints.map((p, i) =>
|
const globalUpdatedPoints = updatedPoints.map((p, i) =>
|
||||||
@@ -748,15 +741,8 @@ const handleEndpointDrag = (
|
|||||||
|
|
||||||
// Calculate the moving second point connection and add the start point
|
// Calculate the moving second point connection and add the start point
|
||||||
{
|
{
|
||||||
const secondPoint = globalUpdatedPoints.at(startIsSpecial ? 2 : 1);
|
const secondPoint = globalUpdatedPoints[startIsSpecial ? 2 : 1];
|
||||||
const thirdPoint = globalUpdatedPoints.at(startIsSpecial ? 3 : 2);
|
const thirdPoint = globalUpdatedPoints[startIsSpecial ? 3 : 2];
|
||||||
|
|
||||||
if (!secondPoint || !thirdPoint) {
|
|
||||||
throw new Error(
|
|
||||||
`Second and third points must exist when handling endpoint drag (${startIsSpecial})`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const startIsHorizontal = headingIsHorizontal(startHeading);
|
const startIsHorizontal = headingIsHorizontal(startHeading);
|
||||||
const secondIsHorizontal = headingIsHorizontal(
|
const secondIsHorizontal = headingIsHorizontal(
|
||||||
vectorToHeading(vectorFromPoint(secondPoint, thirdPoint)),
|
vectorToHeading(vectorFromPoint(secondPoint, thirdPoint)),
|
||||||
@@ -815,19 +801,10 @@ const handleEndpointDrag = (
|
|||||||
|
|
||||||
// Calculate the moving second to last point connection
|
// Calculate the moving second to last point connection
|
||||||
{
|
{
|
||||||
const secondToLastPoint = globalUpdatedPoints.at(
|
const secondToLastPoint =
|
||||||
globalUpdatedPoints.length - (endIsSpecial ? 3 : 2),
|
globalUpdatedPoints[globalUpdatedPoints.length - (endIsSpecial ? 3 : 2)];
|
||||||
);
|
const thirdToLastPoint =
|
||||||
const thirdToLastPoint = globalUpdatedPoints.at(
|
globalUpdatedPoints[globalUpdatedPoints.length - (endIsSpecial ? 4 : 3)];
|
||||||
globalUpdatedPoints.length - (endIsSpecial ? 4 : 3),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (!secondToLastPoint || !thirdToLastPoint) {
|
|
||||||
throw new Error(
|
|
||||||
`Second and third to last points must exist when handling endpoint drag (${endIsSpecial})`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const endIsHorizontal = headingIsHorizontal(endHeading);
|
const endIsHorizontal = headingIsHorizontal(endHeading);
|
||||||
const secondIsHorizontal = headingForPointIsHorizontal(
|
const secondIsHorizontal = headingForPointIsHorizontal(
|
||||||
thirdToLastPoint,
|
thirdToLastPoint,
|
||||||
@@ -921,6 +898,50 @@ export const updateElbowArrowPoints = (
|
|||||||
return { points: updates.points ?? arrow.points };
|
return { points: updates.points ?? arrow.points };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// NOTE (mtolmacs): This is a temporary check to ensure that the incoming elbow
|
||||||
|
// arrow size is valid. This check will be removed once the issue is identified
|
||||||
|
if (
|
||||||
|
arrow.x < -MAX_POS ||
|
||||||
|
arrow.x > MAX_POS ||
|
||||||
|
arrow.y < -MAX_POS ||
|
||||||
|
arrow.y > MAX_POS ||
|
||||||
|
arrow.x + (updates?.points?.[updates?.points?.length - 1]?.[0] ?? 0) <
|
||||||
|
-MAX_POS ||
|
||||||
|
arrow.x + (updates?.points?.[updates?.points?.length - 1]?.[0] ?? 0) >
|
||||||
|
MAX_POS ||
|
||||||
|
arrow.y + (updates?.points?.[updates?.points?.length - 1]?.[1] ?? 0) <
|
||||||
|
-MAX_POS ||
|
||||||
|
arrow.y + (updates?.points?.[updates?.points?.length - 1]?.[1] ?? 0) >
|
||||||
|
MAX_POS ||
|
||||||
|
arrow.x + (arrow?.points?.[arrow?.points?.length - 1]?.[0] ?? 0) <
|
||||||
|
-MAX_POS ||
|
||||||
|
arrow.x + (arrow?.points?.[arrow?.points?.length - 1]?.[0] ?? 0) >
|
||||||
|
MAX_POS ||
|
||||||
|
arrow.y + (arrow?.points?.[arrow?.points?.length - 1]?.[1] ?? 0) <
|
||||||
|
-MAX_POS ||
|
||||||
|
arrow.y + (arrow?.points?.[arrow?.points?.length - 1]?.[1] ?? 0) > MAX_POS
|
||||||
|
) {
|
||||||
|
console.error(
|
||||||
|
"Elbow arrow (or update) is outside reasonable bounds (> 1e6)",
|
||||||
|
{
|
||||||
|
arrow,
|
||||||
|
updates,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// @ts-ignore See above note
|
||||||
|
arrow.x = clamp(arrow.x, -MAX_POS, MAX_POS);
|
||||||
|
// @ts-ignore See above note
|
||||||
|
arrow.y = clamp(arrow.y, -MAX_POS, MAX_POS);
|
||||||
|
if (updates.points) {
|
||||||
|
updates.points = updates.points.map(([x, y]) =>
|
||||||
|
pointFrom<LocalPoint>(
|
||||||
|
clamp(x, -MAX_POS, MAX_POS),
|
||||||
|
clamp(y, -MAX_POS, MAX_POS),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (!import.meta.env.PROD) {
|
if (!import.meta.env.PROD) {
|
||||||
invariant(
|
invariant(
|
||||||
!updates.points || updates.points.length >= 2,
|
!updates.points || updates.points.length >= 2,
|
||||||
@@ -953,25 +974,6 @@ export const updateElbowArrowPoints = (
|
|||||||
),
|
),
|
||||||
"Elbow arrow segments must be either horizontal or vertical",
|
"Elbow arrow segments must be either horizontal or vertical",
|
||||||
);
|
);
|
||||||
|
|
||||||
invariant(
|
|
||||||
updates.fixedSegments?.find(
|
|
||||||
(segment) =>
|
|
||||||
segment.index === 1 &&
|
|
||||||
pointsEqual(segment.start, (updates.points ?? arrow.points)[0]),
|
|
||||||
) == null &&
|
|
||||||
updates.fixedSegments?.find(
|
|
||||||
(segment) =>
|
|
||||||
segment.index === (updates.points ?? arrow.points).length - 1 &&
|
|
||||||
pointsEqual(
|
|
||||||
segment.end,
|
|
||||||
(updates.points ?? arrow.points)[
|
|
||||||
(updates.points ?? arrow.points).length - 1
|
|
||||||
],
|
|
||||||
),
|
|
||||||
) == null,
|
|
||||||
"The first and last segments cannot be fixed",
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const fixedSegments = updates.fixedSegments ?? arrow.fixedSegments ?? [];
|
const fixedSegments = updates.fixedSegments ?? arrow.fixedSegments ?? [];
|
||||||
@@ -1244,7 +1246,6 @@ const getElbowArrowData = (
|
|||||||
const startGlobalPoint = getGlobalPoint(
|
const startGlobalPoint = getGlobalPoint(
|
||||||
{
|
{
|
||||||
...arrow,
|
...arrow,
|
||||||
angle: 0,
|
|
||||||
type: "arrow",
|
type: "arrow",
|
||||||
elbowed: true,
|
elbowed: true,
|
||||||
points: nextPoints,
|
points: nextPoints,
|
||||||
@@ -1253,13 +1254,11 @@ const getElbowArrowData = (
|
|||||||
arrow.startBinding?.fixedPoint,
|
arrow.startBinding?.fixedPoint,
|
||||||
origStartGlobalPoint,
|
origStartGlobalPoint,
|
||||||
hoveredStartElement,
|
hoveredStartElement,
|
||||||
elementsMap,
|
|
||||||
options?.isDragging,
|
options?.isDragging,
|
||||||
);
|
);
|
||||||
const endGlobalPoint = getGlobalPoint(
|
const endGlobalPoint = getGlobalPoint(
|
||||||
{
|
{
|
||||||
...arrow,
|
...arrow,
|
||||||
angle: 0,
|
|
||||||
type: "arrow",
|
type: "arrow",
|
||||||
elbowed: true,
|
elbowed: true,
|
||||||
points: nextPoints,
|
points: nextPoints,
|
||||||
@@ -1268,7 +1267,6 @@ const getElbowArrowData = (
|
|||||||
arrow.endBinding?.fixedPoint,
|
arrow.endBinding?.fixedPoint,
|
||||||
origEndGlobalPoint,
|
origEndGlobalPoint,
|
||||||
hoveredEndElement,
|
hoveredEndElement,
|
||||||
elementsMap,
|
|
||||||
options?.isDragging,
|
options?.isDragging,
|
||||||
);
|
);
|
||||||
const startHeading = getBindPointHeading(
|
const startHeading = getBindPointHeading(
|
||||||
@@ -1276,16 +1274,12 @@ const getElbowArrowData = (
|
|||||||
endGlobalPoint,
|
endGlobalPoint,
|
||||||
hoveredStartElement,
|
hoveredStartElement,
|
||||||
origStartGlobalPoint,
|
origStartGlobalPoint,
|
||||||
elementsMap,
|
|
||||||
options?.zoom,
|
|
||||||
);
|
);
|
||||||
const endHeading = getBindPointHeading(
|
const endHeading = getBindPointHeading(
|
||||||
endGlobalPoint,
|
endGlobalPoint,
|
||||||
startGlobalPoint,
|
startGlobalPoint,
|
||||||
hoveredEndElement,
|
hoveredEndElement,
|
||||||
origEndGlobalPoint,
|
origEndGlobalPoint,
|
||||||
elementsMap,
|
|
||||||
options?.zoom,
|
|
||||||
);
|
);
|
||||||
const startPointBounds = [
|
const startPointBounds = [
|
||||||
startGlobalPoint[0] - 2,
|
startGlobalPoint[0] - 2,
|
||||||
@@ -1302,12 +1296,11 @@ const getElbowArrowData = (
|
|||||||
const startElementBounds = hoveredStartElement
|
const startElementBounds = hoveredStartElement
|
||||||
? aabbForElement(
|
? aabbForElement(
|
||||||
hoveredStartElement,
|
hoveredStartElement,
|
||||||
elementsMap,
|
|
||||||
offsetFromHeading(
|
offsetFromHeading(
|
||||||
startHeading,
|
startHeading,
|
||||||
arrow.startArrowhead
|
arrow.startArrowhead
|
||||||
? getBindingGap(hoveredStartElement, { elbowed: true }) * 6
|
? FIXED_BINDING_DISTANCE * 6
|
||||||
: getBindingGap(hoveredStartElement, { elbowed: true }) * 2,
|
: FIXED_BINDING_DISTANCE * 2,
|
||||||
1,
|
1,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -1315,12 +1308,11 @@ const getElbowArrowData = (
|
|||||||
const endElementBounds = hoveredEndElement
|
const endElementBounds = hoveredEndElement
|
||||||
? aabbForElement(
|
? aabbForElement(
|
||||||
hoveredEndElement,
|
hoveredEndElement,
|
||||||
elementsMap,
|
|
||||||
offsetFromHeading(
|
offsetFromHeading(
|
||||||
endHeading,
|
endHeading,
|
||||||
arrow.endArrowhead
|
arrow.endArrowhead
|
||||||
? getBindingGap(hoveredEndElement, { elbowed: true }) * 6
|
? FIXED_BINDING_DISTANCE * 6
|
||||||
: getBindingGap(hoveredEndElement, { elbowed: true }) * 2,
|
: FIXED_BINDING_DISTANCE * 2,
|
||||||
1,
|
1,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -1331,7 +1323,6 @@ const getElbowArrowData = (
|
|||||||
hoveredEndElement
|
hoveredEndElement
|
||||||
? aabbForElement(
|
? aabbForElement(
|
||||||
hoveredEndElement,
|
hoveredEndElement,
|
||||||
elementsMap,
|
|
||||||
offsetFromHeading(endHeading, BASE_PADDING, BASE_PADDING),
|
offsetFromHeading(endHeading, BASE_PADDING, BASE_PADDING),
|
||||||
)
|
)
|
||||||
: endPointBounds,
|
: endPointBounds,
|
||||||
@@ -1341,7 +1332,6 @@ const getElbowArrowData = (
|
|||||||
hoveredStartElement
|
hoveredStartElement
|
||||||
? aabbForElement(
|
? aabbForElement(
|
||||||
hoveredStartElement,
|
hoveredStartElement,
|
||||||
elementsMap,
|
|
||||||
offsetFromHeading(startHeading, BASE_PADDING, BASE_PADDING),
|
offsetFromHeading(startHeading, BASE_PADDING, BASE_PADDING),
|
||||||
)
|
)
|
||||||
: startPointBounds,
|
: startPointBounds,
|
||||||
@@ -1367,8 +1357,8 @@ const getElbowArrowData = (
|
|||||||
? 0
|
? 0
|
||||||
: BASE_PADDING -
|
: BASE_PADDING -
|
||||||
(arrow.startArrowhead
|
(arrow.startArrowhead
|
||||||
? BASE_BINDING_GAP_ELBOW * 6
|
? FIXED_BINDING_DISTANCE * 6
|
||||||
: BASE_BINDING_GAP_ELBOW * 2),
|
: FIXED_BINDING_DISTANCE * 2),
|
||||||
BASE_PADDING,
|
BASE_PADDING,
|
||||||
),
|
),
|
||||||
boundsOverlap
|
boundsOverlap
|
||||||
@@ -1383,13 +1373,13 @@ const getElbowArrowData = (
|
|||||||
? 0
|
? 0
|
||||||
: BASE_PADDING -
|
: BASE_PADDING -
|
||||||
(arrow.endArrowhead
|
(arrow.endArrowhead
|
||||||
? BASE_BINDING_GAP_ELBOW * 6
|
? FIXED_BINDING_DISTANCE * 6
|
||||||
: BASE_BINDING_GAP_ELBOW * 2),
|
: FIXED_BINDING_DISTANCE * 2),
|
||||||
BASE_PADDING,
|
BASE_PADDING,
|
||||||
),
|
),
|
||||||
boundsOverlap,
|
boundsOverlap,
|
||||||
hoveredStartElement && aabbForElement(hoveredStartElement, elementsMap),
|
hoveredStartElement && aabbForElement(hoveredStartElement),
|
||||||
hoveredEndElement && aabbForElement(hoveredEndElement, elementsMap),
|
hoveredEndElement && aabbForElement(hoveredEndElement),
|
||||||
);
|
);
|
||||||
const startDonglePosition = getDonglePosition(
|
const startDonglePosition = getDonglePosition(
|
||||||
dynamicAABBs[0],
|
dynamicAABBs[0],
|
||||||
@@ -2098,7 +2088,16 @@ const normalizeArrowElementUpdate = (
|
|||||||
nextFixedSegments: readonly FixedSegment[] | null,
|
nextFixedSegments: readonly FixedSegment[] | null,
|
||||||
startIsSpecial?: ExcalidrawElbowArrowElement["startIsSpecial"],
|
startIsSpecial?: ExcalidrawElbowArrowElement["startIsSpecial"],
|
||||||
endIsSpecial?: ExcalidrawElbowArrowElement["startIsSpecial"],
|
endIsSpecial?: ExcalidrawElbowArrowElement["startIsSpecial"],
|
||||||
): ElementUpdate<ExcalidrawElbowArrowElement> => {
|
): {
|
||||||
|
points: LocalPoint[];
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
width: number;
|
||||||
|
height: number;
|
||||||
|
fixedSegments: readonly FixedSegment[] | null;
|
||||||
|
startIsSpecial?: ExcalidrawElbowArrowElement["startIsSpecial"];
|
||||||
|
endIsSpecial?: ExcalidrawElbowArrowElement["startIsSpecial"];
|
||||||
|
} => {
|
||||||
const offsetX = global[0][0];
|
const offsetX = global[0][0];
|
||||||
const offsetY = global[0][1];
|
const offsetY = global[0][1];
|
||||||
let points = global.map((p) =>
|
let points = global.map((p) =>
|
||||||
@@ -2211,28 +2210,35 @@ const getGlobalPoint = (
|
|||||||
fixedPointRatio: [number, number] | undefined | null,
|
fixedPointRatio: [number, number] | undefined | null,
|
||||||
initialPoint: GlobalPoint,
|
initialPoint: GlobalPoint,
|
||||||
element?: ExcalidrawBindableElement | null,
|
element?: ExcalidrawBindableElement | null,
|
||||||
elementsMap?: ElementsMap,
|
|
||||||
isDragging?: boolean,
|
isDragging?: boolean,
|
||||||
): GlobalPoint => {
|
): GlobalPoint => {
|
||||||
if (isDragging) {
|
if (isDragging) {
|
||||||
if (element && elementsMap) {
|
if (element) {
|
||||||
return bindPointToSnapToElementOutline(
|
const snapPoint = bindPointToSnapToElementOutline(
|
||||||
arrow,
|
arrow,
|
||||||
element,
|
element,
|
||||||
startOrEnd,
|
startOrEnd,
|
||||||
elementsMap,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
return snapToMid(element, snapPoint);
|
||||||
}
|
}
|
||||||
|
|
||||||
return initialPoint;
|
return initialPoint;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (element) {
|
if (element) {
|
||||||
return getGlobalFixedPointForBindableElement(
|
const fixedGlobalPoint = getGlobalFixedPointForBindableElement(
|
||||||
fixedPointRatio || [0, 0],
|
fixedPointRatio || [0, 0],
|
||||||
element,
|
element,
|
||||||
elementsMap ?? arrayToMap([element]),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// NOTE: Resize scales the binding position point too, so we need to update it
|
||||||
|
return Math.abs(
|
||||||
|
distanceToBindableElement(element, fixedGlobalPoint) -
|
||||||
|
FIXED_BINDING_DISTANCE,
|
||||||
|
) > 0.01
|
||||||
|
? bindPointToSnapToElementOutline(arrow, element, startOrEnd)
|
||||||
|
: fixedGlobalPoint;
|
||||||
}
|
}
|
||||||
|
|
||||||
return initialPoint;
|
return initialPoint;
|
||||||
@@ -2243,8 +2249,6 @@ const getBindPointHeading = (
|
|||||||
otherPoint: GlobalPoint,
|
otherPoint: GlobalPoint,
|
||||||
hoveredElement: ExcalidrawBindableElement | null | undefined,
|
hoveredElement: ExcalidrawBindableElement | null | undefined,
|
||||||
origPoint: GlobalPoint,
|
origPoint: GlobalPoint,
|
||||||
elementsMap: ElementsMap,
|
|
||||||
zoom?: AppState["zoom"],
|
|
||||||
): Heading =>
|
): Heading =>
|
||||||
getHeadingForElbowArrowSnap(
|
getHeadingForElbowArrowSnap(
|
||||||
p,
|
p,
|
||||||
@@ -2253,8 +2257,7 @@ const getBindPointHeading = (
|
|||||||
hoveredElement &&
|
hoveredElement &&
|
||||||
aabbForElement(
|
aabbForElement(
|
||||||
hoveredElement,
|
hoveredElement,
|
||||||
elementsMap,
|
Array(4).fill(distanceToBindableElement(hoveredElement, p)) as [
|
||||||
Array(4).fill(distanceToElement(hoveredElement, elementsMap, p)) as [
|
|
||||||
number,
|
number,
|
||||||
number,
|
number,
|
||||||
number,
|
number,
|
||||||
@@ -2262,21 +2265,21 @@ const getBindPointHeading = (
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
origPoint,
|
origPoint,
|
||||||
elementsMap,
|
|
||||||
zoom,
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const getHoveredElement = (
|
const getHoveredElement = (
|
||||||
origPoint: GlobalPoint,
|
origPoint: GlobalPoint,
|
||||||
elementsMap: NonDeletedSceneElementsMap,
|
elementsMap: NonDeletedSceneElementsMap,
|
||||||
elements: readonly Ordered<NonDeletedExcalidrawElement>[],
|
elements: readonly NonDeletedExcalidrawElement[],
|
||||||
zoom?: AppState["zoom"],
|
zoom?: AppState["zoom"],
|
||||||
) => {
|
) => {
|
||||||
return getHoveredElementForBinding(
|
return getHoveredElementForBinding(
|
||||||
origPoint,
|
tupleToCoors(origPoint),
|
||||||
elements,
|
elements,
|
||||||
elementsMap,
|
elementsMap,
|
||||||
(element) => maxBindingDistance_simple(zoom),
|
zoom,
|
||||||
|
true,
|
||||||
|
true,
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ type IframeDataWithSandbox = MarkRequired<IframeData, "sandbox">;
|
|||||||
const embeddedLinkCache = new Map<string, IframeDataWithSandbox>();
|
const embeddedLinkCache = new Map<string, IframeDataWithSandbox>();
|
||||||
|
|
||||||
const RE_YOUTUBE =
|
const RE_YOUTUBE =
|
||||||
/^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)/;
|
/^(?:http(?:s)?:\/\/)?(?:www\.)?youtu(?:be\.com|\.be)\/(embed\/|watch\?v=|shorts\/|playlist\?list=|embed\/videoseries\?list=)?([a-zA-Z0-9_-]+)(?:\?t=|&t=|\?start=|&start=)?([a-zA-Z0-9_-]+)?[^\s]*$/;
|
||||||
|
|
||||||
const RE_VIMEO =
|
const RE_VIMEO =
|
||||||
/^(?:http(?:s)?:\/\/)?(?:(?:w){3}\.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/;
|
/^(?:http(?:s)?:\/\/)?(?:(?:w){3}\.)?(?:player\.)?vimeo\.com\/(?:video\/)?([^?\s]+)(?:\?.*)?$/;
|
||||||
@@ -33,8 +33,6 @@ const RE_GH_GIST = /^https:\/\/gist\.github\.com\/([\w_-]+)\/([\w_-]+)/;
|
|||||||
const RE_GH_GIST_EMBED =
|
const RE_GH_GIST_EMBED =
|
||||||
/^<script[\s\S]*?\ssrc=["'](https:\/\/gist\.github\.com\/.*?)\.js["']/i;
|
/^<script[\s\S]*?\ssrc=["'](https:\/\/gist\.github\.com\/.*?)\.js["']/i;
|
||||||
|
|
||||||
const RE_MSFORMS = /^(?:https?:\/\/)?forms\.microsoft\.com\//;
|
|
||||||
|
|
||||||
// not anchored to start to allow <blockquote> twitter embeds
|
// not anchored to start to allow <blockquote> twitter embeds
|
||||||
const RE_TWITTER =
|
const RE_TWITTER =
|
||||||
/(?:https?:\/\/)?(?:(?:w){3}\.)?(?:twitter|x)\.com\/[^/]+\/status\/(\d+)/;
|
/(?:https?:\/\/)?(?:(?:w){3}\.)?(?:twitter|x)\.com\/[^/]+\/status\/(\d+)/;
|
||||||
@@ -56,35 +54,6 @@ const RE_REDDIT =
|
|||||||
const RE_REDDIT_EMBED =
|
const RE_REDDIT_EMBED =
|
||||||
/^<blockquote[\s\S]*?\shref=["'](https?:\/\/(?:www\.)?reddit\.com\/[^"']*)/i;
|
/^<blockquote[\s\S]*?\shref=["'](https?:\/\/(?:www\.)?reddit\.com\/[^"']*)/i;
|
||||||
|
|
||||||
const parseYouTubeTimestamp = (url: string): number => {
|
|
||||||
let timeParam: string | null | undefined;
|
|
||||||
|
|
||||||
try {
|
|
||||||
const urlObj = new URL(url.startsWith("http") ? url : `https://${url}`);
|
|
||||||
timeParam =
|
|
||||||
urlObj.searchParams.get("t") || urlObj.searchParams.get("start");
|
|
||||||
} catch (error) {
|
|
||||||
const timeMatch = url.match(/[?&#](?:t|start)=([^&#\s]+)/);
|
|
||||||
timeParam = timeMatch?.[1];
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!timeParam) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (/^\d+$/.test(timeParam)) {
|
|
||||||
return parseInt(timeParam, 10);
|
|
||||||
}
|
|
||||||
|
|
||||||
const timeMatch = timeParam.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);
|
|
||||||
if (!timeMatch) {
|
|
||||||
return 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
const [, hours = "0", minutes = "0", seconds = "0"] = timeMatch;
|
|
||||||
return parseInt(hours) * 3600 + parseInt(minutes) * 60 + parseInt(seconds);
|
|
||||||
};
|
|
||||||
|
|
||||||
const ALLOWED_DOMAINS = new Set([
|
const ALLOWED_DOMAINS = new Set([
|
||||||
"youtube.com",
|
"youtube.com",
|
||||||
"youtu.be",
|
"youtu.be",
|
||||||
@@ -100,7 +69,6 @@ const ALLOWED_DOMAINS = new Set([
|
|||||||
"val.town",
|
"val.town",
|
||||||
"giphy.com",
|
"giphy.com",
|
||||||
"reddit.com",
|
"reddit.com",
|
||||||
"forms.microsoft.com",
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const ALLOW_SAME_ORIGIN = new Set([
|
const ALLOW_SAME_ORIGIN = new Set([
|
||||||
@@ -114,7 +82,6 @@ const ALLOW_SAME_ORIGIN = new Set([
|
|||||||
"*.simplepdf.eu",
|
"*.simplepdf.eu",
|
||||||
"stackblitz.com",
|
"stackblitz.com",
|
||||||
"reddit.com",
|
"reddit.com",
|
||||||
"forms.microsoft.com",
|
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const createSrcDoc = (body: string) => {
|
export const createSrcDoc = (body: string) => {
|
||||||
@@ -142,8 +109,7 @@ export const getEmbedLink = (
|
|||||||
let aspectRatio = { w: 560, h: 840 };
|
let aspectRatio = { w: 560, h: 840 };
|
||||||
const ytLink = link.match(RE_YOUTUBE);
|
const ytLink = link.match(RE_YOUTUBE);
|
||||||
if (ytLink?.[2]) {
|
if (ytLink?.[2]) {
|
||||||
const startTime = parseYouTubeTimestamp(originalLink);
|
const time = ytLink[3] ? `&start=${ytLink[3]}` : ``;
|
||||||
const time = startTime > 0 ? `&start=${startTime}` : ``;
|
|
||||||
const isPortrait = link.includes("shorts");
|
const isPortrait = link.includes("shorts");
|
||||||
type = "video";
|
type = "video";
|
||||||
switch (ytLink[1]) {
|
switch (ytLink[1]) {
|
||||||
@@ -240,10 +206,6 @@ export const getEmbedLink = (
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (RE_MSFORMS.test(link) && !link.includes("embed=true")) {
|
|
||||||
link += link.includes("?") ? "&embed=true" : "?embed=true";
|
|
||||||
}
|
|
||||||
|
|
||||||
if (RE_TWITTER.test(link)) {
|
if (RE_TWITTER.test(link)) {
|
||||||
const postId = link.match(RE_TWITTER)![1];
|
const postId = link.match(RE_TWITTER)![1];
|
||||||
// the embed srcdoc still supports twitter.com domain only.
|
// the embed srcdoc still supports twitter.com domain only.
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import type {
|
|||||||
PendingExcalidrawElements,
|
PendingExcalidrawElements,
|
||||||
} from "@excalidraw/excalidraw/types";
|
} from "@excalidraw/excalidraw/types";
|
||||||
|
|
||||||
import { bindBindingElement } from "./binding";
|
import { bindLinearElement } from "./binding";
|
||||||
import { updateElbowArrowPoints } from "./elbowArrow";
|
import { updateElbowArrowPoints } from "./elbowArrow";
|
||||||
import {
|
import {
|
||||||
HEADING_DOWN,
|
HEADING_DOWN,
|
||||||
@@ -21,7 +21,7 @@ import {
|
|||||||
import { LinearElementEditor } from "./linearElementEditor";
|
import { LinearElementEditor } from "./linearElementEditor";
|
||||||
import { mutateElement } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
import { newArrowElement, newElement } from "./newElement";
|
import { newArrowElement, newElement } from "./newElement";
|
||||||
import { aabbForElement } from "./bounds";
|
import { aabbForElement } from "./shapes";
|
||||||
import { elementsAreInFrameBounds, elementOverlapsWithFrame } from "./frame";
|
import { elementsAreInFrameBounds, elementOverlapsWithFrame } from "./frame";
|
||||||
import {
|
import {
|
||||||
isBindableElement,
|
isBindableElement,
|
||||||
@@ -39,7 +39,7 @@ import {
|
|||||||
type OrderedExcalidrawElement,
|
type OrderedExcalidrawElement,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
import type { Scene } from "./Scene";
|
import type Scene from "./Scene";
|
||||||
|
|
||||||
type LinkDirection = "up" | "right" | "down" | "left";
|
type LinkDirection = "up" | "right" | "down" | "left";
|
||||||
|
|
||||||
@@ -95,11 +95,10 @@ const getNodeRelatives = (
|
|||||||
type === "predecessors" ? el.points[el.points.length - 1] : [0, 0]
|
type === "predecessors" ? el.points[el.points.length - 1] : [0, 0]
|
||||||
) as Readonly<LocalPoint>;
|
) as Readonly<LocalPoint>;
|
||||||
|
|
||||||
const heading = headingForPointFromElement(
|
const heading = headingForPointFromElement(node, aabbForElement(node), [
|
||||||
node,
|
edgePoint[0] + el.x,
|
||||||
aabbForElement(node, elementsMap),
|
edgePoint[1] + el.y,
|
||||||
[edgePoint[0] + el.x, edgePoint[1] + el.y] as Readonly<GlobalPoint>,
|
] as Readonly<GlobalPoint>);
|
||||||
);
|
|
||||||
|
|
||||||
acc.push({
|
acc.push({
|
||||||
relative,
|
relative,
|
||||||
@@ -446,14 +445,8 @@ const createBindingArrow = (
|
|||||||
|
|
||||||
const elementsMap = scene.getNonDeletedElementsMap();
|
const elementsMap = scene.getNonDeletedElementsMap();
|
||||||
|
|
||||||
bindBindingElement(
|
bindLinearElement(bindingArrow, startBindingElement, "start", scene);
|
||||||
bindingArrow,
|
bindLinearElement(bindingArrow, endBindingElement, "end", scene);
|
||||||
startBindingElement,
|
|
||||||
"orbit",
|
|
||||||
"start",
|
|
||||||
scene,
|
|
||||||
);
|
|
||||||
bindBindingElement(bindingArrow, endBindingElement, "orbit", "end", scene);
|
|
||||||
|
|
||||||
const changedElements = new Map<string, OrderedExcalidrawElement>();
|
const changedElements = new Map<string, OrderedExcalidrawElement>();
|
||||||
changedElements.set(
|
changedElements.set(
|
||||||
@@ -469,18 +462,12 @@ const createBindingArrow = (
|
|||||||
bindingArrow as OrderedExcalidrawElement,
|
bindingArrow as OrderedExcalidrawElement,
|
||||||
);
|
);
|
||||||
|
|
||||||
LinearElementEditor.movePoints(
|
LinearElementEditor.movePoints(bindingArrow, scene, [
|
||||||
bindingArrow,
|
{
|
||||||
scene,
|
index: 1,
|
||||||
new Map([
|
point: bindingArrow.points[1],
|
||||||
[
|
},
|
||||||
1,
|
]);
|
||||||
{
|
|
||||||
point: bindingArrow.points[1],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
]),
|
|
||||||
);
|
|
||||||
|
|
||||||
const update = updateElbowArrowPoints(
|
const update = updateElbowArrowPoints(
|
||||||
bindingArrow,
|
bindingArrow,
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { generateNKeysBetween } from "fractional-indexing";
|
|||||||
|
|
||||||
import { arrayToMap } from "@excalidraw/common";
|
import { arrayToMap } from "@excalidraw/common";
|
||||||
|
|
||||||
import { mutateElement, newElementWith } from "./mutateElement";
|
import { mutateElement } from "./mutateElement";
|
||||||
import { getBoundTextElement } from "./textElement";
|
import { getBoundTextElement } from "./textElement";
|
||||||
import { hasBoundTextElement } from "./typeChecks";
|
import { hasBoundTextElement } from "./typeChecks";
|
||||||
|
|
||||||
@@ -11,7 +11,6 @@ import type {
|
|||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
FractionalIndex,
|
FractionalIndex,
|
||||||
OrderedExcalidrawElement,
|
OrderedExcalidrawElement,
|
||||||
SceneElementsMap,
|
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export class InvalidFractionalIndexError extends Error {
|
export class InvalidFractionalIndexError extends Error {
|
||||||
@@ -162,15 +161,9 @@ export const syncMovedIndices = (
|
|||||||
|
|
||||||
// try generatating indices, throws on invalid movedElements
|
// try generatating indices, throws on invalid movedElements
|
||||||
const elementsUpdates = generateIndices(elements, indicesGroups);
|
const elementsUpdates = generateIndices(elements, indicesGroups);
|
||||||
const elementsCandidates = elements.map((x) => {
|
const elementsCandidates = elements.map((x) =>
|
||||||
const elementUpdates = elementsUpdates.get(x);
|
elementsUpdates.has(x) ? { ...x, ...elementsUpdates.get(x) } : x,
|
||||||
|
);
|
||||||
if (elementUpdates) {
|
|
||||||
return { ...x, index: elementUpdates.index };
|
|
||||||
}
|
|
||||||
|
|
||||||
return x;
|
|
||||||
});
|
|
||||||
|
|
||||||
// ensure next indices are valid before mutation, throws on invalid ones
|
// ensure next indices are valid before mutation, throws on invalid ones
|
||||||
validateFractionalIndices(
|
validateFractionalIndices(
|
||||||
@@ -184,8 +177,8 @@ export const syncMovedIndices = (
|
|||||||
);
|
);
|
||||||
|
|
||||||
// split mutation so we don't end up in an incosistent state
|
// split mutation so we don't end up in an incosistent state
|
||||||
for (const [element, { index }] of elementsUpdates) {
|
for (const [element, update] of elementsUpdates) {
|
||||||
mutateElement(element, elementsMap, { index });
|
mutateElement(element, elementsMap, update);
|
||||||
}
|
}
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
// fallback to default sync
|
// fallback to default sync
|
||||||
@@ -196,7 +189,7 @@ export const syncMovedIndices = (
|
|||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Synchronizes all invalid fractional indices within the array order by mutating elements in the passed array.
|
* Synchronizes all invalid fractional indices with the array order by mutating passed elements.
|
||||||
*
|
*
|
||||||
* WARN: in edge cases it could modify the elements which were not moved, as it's impossible to guess the actually moved elements from the elements array itself.
|
* WARN: in edge cases it could modify the elements which were not moved, as it's impossible to guess the actually moved elements from the elements array itself.
|
||||||
*/
|
*/
|
||||||
@@ -207,32 +200,13 @@ export const syncInvalidIndices = (
|
|||||||
const indicesGroups = getInvalidIndicesGroups(elements);
|
const indicesGroups = getInvalidIndicesGroups(elements);
|
||||||
const elementsUpdates = generateIndices(elements, indicesGroups);
|
const elementsUpdates = generateIndices(elements, indicesGroups);
|
||||||
|
|
||||||
for (const [element, { index }] of elementsUpdates) {
|
for (const [element, update] of elementsUpdates) {
|
||||||
mutateElement(element, elementsMap, { index });
|
mutateElement(element, elementsMap, update);
|
||||||
}
|
}
|
||||||
|
|
||||||
return elements as OrderedExcalidrawElement[];
|
return elements as OrderedExcalidrawElement[];
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Synchronizes all invalid fractional indices within the array order by creating new instances of elements with corrected indices.
|
|
||||||
*
|
|
||||||
* WARN: in edge cases it could modify the elements which were not moved, as it's impossible to guess the actually moved elements from the elements array itself.
|
|
||||||
*/
|
|
||||||
export const syncInvalidIndicesImmutable = (
|
|
||||||
elements: readonly ExcalidrawElement[],
|
|
||||||
): SceneElementsMap | undefined => {
|
|
||||||
const syncedElements = arrayToMap(elements);
|
|
||||||
const indicesGroups = getInvalidIndicesGroups(elements);
|
|
||||||
const elementsUpdates = generateIndices(elements, indicesGroups);
|
|
||||||
|
|
||||||
for (const [element, { index }] of elementsUpdates) {
|
|
||||||
syncedElements.set(element.id, newElementWith(element, { index }));
|
|
||||||
}
|
|
||||||
|
|
||||||
return syncedElements as SceneElementsMap;
|
|
||||||
};
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get contiguous groups of indices of passed moved elements.
|
* Get contiguous groups of indices of passed moved elements.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -905,16 +905,13 @@ export const shouldApplyFrameClip = (
|
|||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_FRAME_NAME = "Frame";
|
|
||||||
const DEFAULT_AI_FRAME_NAME = "AI Frame";
|
|
||||||
|
|
||||||
export const getDefaultFrameName = (element: ExcalidrawFrameLikeElement) => {
|
|
||||||
// TODO name frames "AI" only if specific to AI frames
|
|
||||||
return isFrameElement(element) ? DEFAULT_FRAME_NAME : DEFAULT_AI_FRAME_NAME;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const getFrameLikeTitle = (element: ExcalidrawFrameLikeElement) => {
|
export const getFrameLikeTitle = (element: ExcalidrawFrameLikeElement) => {
|
||||||
return element.name === null ? getDefaultFrameName(element) : element.name;
|
// TODO name frames "AI" only if specific to AI frames
|
||||||
|
return element.name === null
|
||||||
|
? isFrameElement(element)
|
||||||
|
? "Frame"
|
||||||
|
: "AI Frame"
|
||||||
|
: element.name;
|
||||||
};
|
};
|
||||||
|
|
||||||
export const getElementsOverlappingFrame = (
|
export const getElementsOverlappingFrame = (
|
||||||
|
|||||||
@@ -7,8 +7,6 @@ import type { Mutable } from "@excalidraw/common/utility-types";
|
|||||||
|
|
||||||
import { getBoundTextElement } from "./textElement";
|
import { getBoundTextElement } from "./textElement";
|
||||||
|
|
||||||
import { isBoundToContainer } from "./typeChecks";
|
|
||||||
|
|
||||||
import { makeNextSelectedElementIds, getSelectedElements } from "./selection";
|
import { makeNextSelectedElementIds, getSelectedElements } from "./selection";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
@@ -404,78 +402,3 @@ export const getNewGroupIdsForDuplication = (
|
|||||||
|
|
||||||
return copy;
|
return copy;
|
||||||
};
|
};
|
||||||
|
|
||||||
// given a list of selected elements, return the element grouped by their immediate group selected state
|
|
||||||
// in the case if only one group is selected and all elements selected are within the group, it will respect group hierarchy in accordance to their nested grouping order
|
|
||||||
export const getSelectedElementsByGroup = (
|
|
||||||
selectedElements: ExcalidrawElement[],
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
appState: Readonly<AppState>,
|
|
||||||
): ExcalidrawElement[][] => {
|
|
||||||
const selectedGroupIds = getSelectedGroupIds(appState);
|
|
||||||
const unboundElements = selectedElements.filter(
|
|
||||||
(element) => !isBoundToContainer(element),
|
|
||||||
);
|
|
||||||
const groups: Map<string, ExcalidrawElement[]> = new Map();
|
|
||||||
const elements: Map<string, ExcalidrawElement[]> = new Map();
|
|
||||||
|
|
||||||
// helper function to add an element to the elements map
|
|
||||||
const addToElementsMap = (element: ExcalidrawElement) => {
|
|
||||||
// elements
|
|
||||||
const currentElementMembers = elements.get(element.id) || [];
|
|
||||||
const boundTextElement = getBoundTextElement(element, elementsMap);
|
|
||||||
|
|
||||||
if (boundTextElement) {
|
|
||||||
currentElementMembers.push(boundTextElement);
|
|
||||||
}
|
|
||||||
elements.set(element.id, [...currentElementMembers, element]);
|
|
||||||
};
|
|
||||||
|
|
||||||
// helper function to add an element to the groups map
|
|
||||||
const addToGroupsMap = (element: ExcalidrawElement, groupId: string) => {
|
|
||||||
// groups
|
|
||||||
const currentGroupMembers = groups.get(groupId) || [];
|
|
||||||
const boundTextElement = getBoundTextElement(element, elementsMap);
|
|
||||||
|
|
||||||
if (boundTextElement) {
|
|
||||||
currentGroupMembers.push(boundTextElement);
|
|
||||||
}
|
|
||||||
groups.set(groupId, [...currentGroupMembers, element]);
|
|
||||||
};
|
|
||||||
|
|
||||||
// helper function to handle the case where a single group is selected
|
|
||||||
// and all elements selected are within the group, it will respect group hierarchy in accordance to
|
|
||||||
// their nested grouping order
|
|
||||||
const handleSingleSelectedGroupCase = (
|
|
||||||
element: ExcalidrawElement,
|
|
||||||
selectedGroupId: GroupId,
|
|
||||||
) => {
|
|
||||||
const indexOfSelectedGroupId = element.groupIds.indexOf(selectedGroupId, 0);
|
|
||||||
const nestedGroupCount = element.groupIds.slice(
|
|
||||||
0,
|
|
||||||
indexOfSelectedGroupId,
|
|
||||||
).length;
|
|
||||||
return nestedGroupCount > 0
|
|
||||||
? addToGroupsMap(element, element.groupIds[indexOfSelectedGroupId - 1])
|
|
||||||
: addToElementsMap(element);
|
|
||||||
};
|
|
||||||
|
|
||||||
const isAllInSameGroup = selectedElements.every((element) =>
|
|
||||||
isSelectedViaGroup(appState, element),
|
|
||||||
);
|
|
||||||
|
|
||||||
unboundElements.forEach((element) => {
|
|
||||||
const selectedGroupId = getSelectedGroupIdForElement(
|
|
||||||
element,
|
|
||||||
appState.selectedGroupIds,
|
|
||||||
);
|
|
||||||
if (!selectedGroupId) {
|
|
||||||
addToElementsMap(element);
|
|
||||||
} else if (selectedGroupIds.length === 1 && isAllInSameGroup) {
|
|
||||||
handleSingleSelectedGroupCase(element, selectedGroupId);
|
|
||||||
} else {
|
|
||||||
addToGroupsMap(element, selectedGroupId);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
return Array.from(groups.values()).concat(Array.from(elements.values()));
|
|
||||||
};
|
|
||||||
|
|||||||
@@ -1,9 +1,4 @@
|
|||||||
import {
|
import { invariant, isDevEnv, isTestEnv } from "@excalidraw/common";
|
||||||
invariant,
|
|
||||||
isDevEnv,
|
|
||||||
isTestEnv,
|
|
||||||
type Bounds,
|
|
||||||
} from "@excalidraw/common";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
pointFrom,
|
pointFrom,
|
||||||
@@ -24,7 +19,7 @@ import type {
|
|||||||
Vector,
|
Vector,
|
||||||
} from "@excalidraw/math";
|
} from "@excalidraw/math";
|
||||||
|
|
||||||
import { getCenterForBounds } from "./bounds";
|
import { getCenterForBounds, type Bounds } from "./bounds";
|
||||||
|
|
||||||
import type { ExcalidrawBindableElement } from "./types";
|
import type { ExcalidrawBindableElement } from "./types";
|
||||||
|
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
import { toIterable } from "@excalidraw/common";
|
|
||||||
|
|
||||||
import { isInvisiblySmallElement } from "./sizeHelpers";
|
import { isInvisiblySmallElement } from "./sizeHelpers";
|
||||||
|
import { isLinearElementType } from "./typeChecks";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
NonDeletedExcalidrawElement,
|
NonDeletedExcalidrawElement,
|
||||||
NonDeleted,
|
NonDeleted,
|
||||||
ElementsMapOrArray,
|
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -18,19 +16,18 @@ export const getSceneVersion = (elements: readonly ExcalidrawElement[]) =>
|
|||||||
/**
|
/**
|
||||||
* Hashes elements' versionNonce (using djb2 algo). Order of elements matters.
|
* Hashes elements' versionNonce (using djb2 algo). Order of elements matters.
|
||||||
*/
|
*/
|
||||||
export const hashElementsVersion = (elements: ElementsMapOrArray): number => {
|
export const hashElementsVersion = (
|
||||||
|
elements: readonly ExcalidrawElement[],
|
||||||
|
): number => {
|
||||||
let hash = 5381;
|
let hash = 5381;
|
||||||
for (const element of toIterable(elements)) {
|
for (let i = 0; i < elements.length; i++) {
|
||||||
hash = (hash << 5) + hash + element.versionNonce;
|
hash = (hash << 5) + hash + elements[i].versionNonce;
|
||||||
}
|
}
|
||||||
return hash >>> 0; // Ensure unsigned 32-bit integer
|
return hash >>> 0; // Ensure unsigned 32-bit integer
|
||||||
};
|
};
|
||||||
|
|
||||||
// string hash function (using djb2). Not cryptographically secure, use only
|
// string hash function (using djb2). Not cryptographically secure, use only
|
||||||
// for versioning and such.
|
// for versioning and such.
|
||||||
// note: hashes individual code units (not code points),
|
|
||||||
// but for hashing purposes this is fine as it iterates through every code unit
|
|
||||||
// (as such, no need to encode to byte string first)
|
|
||||||
export const hashString = (s: string): number => {
|
export const hashString = (s: string): number => {
|
||||||
let hash: number = 5381;
|
let hash: number = 5381;
|
||||||
for (let i = 0; i < s.length; i++) {
|
for (let i = 0; i < s.length; i++) {
|
||||||
@@ -54,46 +51,23 @@ export const isNonDeletedElement = <T extends ExcalidrawElement>(
|
|||||||
element: T,
|
element: T,
|
||||||
): element is NonDeleted<T> => !element.isDeleted;
|
): element is NonDeleted<T> => !element.isDeleted;
|
||||||
|
|
||||||
export * from "./align";
|
const _clearElements = (
|
||||||
export * from "./binding";
|
elements: readonly ExcalidrawElement[],
|
||||||
export * from "./bounds";
|
): ExcalidrawElement[] =>
|
||||||
export * from "./collision";
|
getNonDeletedElements(elements).map((element) =>
|
||||||
export * from "./comparisons";
|
isLinearElementType(element.type)
|
||||||
export * from "./containerCache";
|
? { ...element, lastCommittedPoint: null }
|
||||||
export * from "./cropElement";
|
: element,
|
||||||
export * from "./delta";
|
);
|
||||||
export * from "./distance";
|
|
||||||
export * from "./distribute";
|
export const clearElementsForDatabase = (
|
||||||
export * from "./dragElements";
|
elements: readonly ExcalidrawElement[],
|
||||||
export * from "./duplicate";
|
) => _clearElements(elements);
|
||||||
export * from "./elbowArrow";
|
|
||||||
export * from "./elementLink";
|
export const clearElementsForExport = (
|
||||||
export * from "./embeddable";
|
elements: readonly ExcalidrawElement[],
|
||||||
export * from "./flowchart";
|
) => _clearElements(elements);
|
||||||
export * from "./fractionalIndex";
|
|
||||||
export * from "./frame";
|
export const clearElementsForLocalStorage = (
|
||||||
export * from "./groups";
|
elements: readonly ExcalidrawElement[],
|
||||||
export * from "./heading";
|
) => _clearElements(elements);
|
||||||
export * from "./image";
|
|
||||||
export * from "./linearElementEditor";
|
|
||||||
export * from "./mutateElement";
|
|
||||||
export * from "./newElement";
|
|
||||||
export * from "./positionElementsOnGrid";
|
|
||||||
export * from "./renderElement";
|
|
||||||
export * from "./resizeElements";
|
|
||||||
export * from "./resizeTest";
|
|
||||||
export * from "./Scene";
|
|
||||||
export * from "./selection";
|
|
||||||
export * from "./shape";
|
|
||||||
export * from "./showSelectedShapeActions";
|
|
||||||
export * from "./sizeHelpers";
|
|
||||||
export * from "./sortElements";
|
|
||||||
export * from "./store";
|
|
||||||
export * from "./textElement";
|
|
||||||
export * from "./textMeasurements";
|
|
||||||
export * from "./textWrapping";
|
|
||||||
export * from "./transform";
|
|
||||||
export * from "./transformHandles";
|
|
||||||
export * from "./typeChecks";
|
|
||||||
export * from "./utils";
|
|
||||||
export * from "./zindex";
|
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -8,7 +8,7 @@ import type { Radians } from "@excalidraw/math";
|
|||||||
|
|
||||||
import type { Mutable } from "@excalidraw/common/utility-types";
|
import type { Mutable } from "@excalidraw/common/utility-types";
|
||||||
|
|
||||||
import { ShapeCache } from "./shape";
|
import { ShapeCache } from "./ShapeCache";
|
||||||
|
|
||||||
import { updateElbowArrowPoints } from "./elbowArrow";
|
import { updateElbowArrowPoints } from "./elbowArrow";
|
||||||
|
|
||||||
@@ -23,7 +23,7 @@ import type {
|
|||||||
|
|
||||||
export type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
|
export type ElementUpdate<TElement extends ExcalidrawElement> = Omit<
|
||||||
Partial<TElement>,
|
Partial<TElement>,
|
||||||
"id" | "updated"
|
"id" | "version" | "versionNonce" | "updated"
|
||||||
>;
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -46,13 +46,16 @@ export const mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
|
|||||||
|
|
||||||
// casting to any because can't use `in` operator
|
// casting to any because can't use `in` operator
|
||||||
// (see https://github.com/microsoft/TypeScript/issues/21732)
|
// (see https://github.com/microsoft/TypeScript/issues/21732)
|
||||||
const { points, fixedSegments, fileId } = updates as any;
|
const { points, fixedSegments, startBinding, endBinding, fileId } =
|
||||||
|
updates as any;
|
||||||
|
|
||||||
if (
|
if (
|
||||||
isElbowArrow(element) &&
|
isElbowArrow(element) &&
|
||||||
(Object.keys(updates).length === 0 || // normalization case
|
(Object.keys(updates).length === 0 || // normalization case
|
||||||
typeof points !== "undefined" || // repositioning
|
typeof points !== "undefined" || // repositioning
|
||||||
typeof fixedSegments !== "undefined") // segment fixing
|
typeof fixedSegments !== "undefined" || // segment fixing
|
||||||
|
typeof startBinding !== "undefined" ||
|
||||||
|
typeof endBinding !== "undefined") // manual binding to element
|
||||||
) {
|
) {
|
||||||
updates = {
|
updates = {
|
||||||
...updates,
|
...updates,
|
||||||
@@ -134,8 +137,8 @@ export const mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
|
|||||||
ShapeCache.delete(element);
|
ShapeCache.delete(element);
|
||||||
}
|
}
|
||||||
|
|
||||||
element.version = updates.version ?? element.version + 1;
|
element.version++;
|
||||||
element.versionNonce = updates.versionNonce ?? randomInteger();
|
element.versionNonce = randomInteger();
|
||||||
element.updated = getUpdatedTimestamp();
|
element.updated = getUpdatedTimestamp();
|
||||||
|
|
||||||
return element;
|
return element;
|
||||||
@@ -169,9 +172,9 @@ export const newElementWith = <TElement extends ExcalidrawElement>(
|
|||||||
return {
|
return {
|
||||||
...element,
|
...element,
|
||||||
...updates,
|
...updates,
|
||||||
version: updates.version ?? element.version + 1,
|
|
||||||
versionNonce: updates.versionNonce ?? randomInteger(),
|
|
||||||
updated: getUpdatedTimestamp(),
|
updated: getUpdatedTimestamp(),
|
||||||
|
version: element.version + 1,
|
||||||
|
versionNonce: randomInteger(),
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -21,12 +21,10 @@ import {
|
|||||||
getResizedElementAbsoluteCoords,
|
getResizedElementAbsoluteCoords,
|
||||||
} from "./bounds";
|
} from "./bounds";
|
||||||
import { newElementWith } from "./mutateElement";
|
import { newElementWith } from "./mutateElement";
|
||||||
import { getBoundTextMaxWidth, getInitialTextMetrics } from "./textElement";
|
import { getBoundTextMaxWidth } from "./textElement";
|
||||||
import { normalizeText, measureText } from "./textMeasurements";
|
import { normalizeText, measureText } from "./textMeasurements";
|
||||||
import { wrapText } from "./textWrapping";
|
import { wrapText } from "./textWrapping";
|
||||||
|
|
||||||
import { isLineElement } from "./typeChecks";
|
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
ExcalidrawImageElement,
|
ExcalidrawImageElement,
|
||||||
@@ -46,8 +44,8 @@ import type {
|
|||||||
ExcalidrawIframeElement,
|
ExcalidrawIframeElement,
|
||||||
ElementsMap,
|
ElementsMap,
|
||||||
ExcalidrawArrowElement,
|
ExcalidrawArrowElement,
|
||||||
|
FixedSegment,
|
||||||
ExcalidrawElbowArrowElement,
|
ExcalidrawElbowArrowElement,
|
||||||
ExcalidrawLineElement,
|
|
||||||
} from "./types";
|
} from "./types";
|
||||||
|
|
||||||
export type ElementConstructorOpts = MarkOptional<
|
export type ElementConstructorOpts = MarkOptional<
|
||||||
@@ -236,30 +234,27 @@ const getTextElementPositionOffsets = (
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
export type NewTextElementOptions = {
|
|
||||||
text: string;
|
|
||||||
originalText?: string;
|
|
||||||
fontSize?: number;
|
|
||||||
fontFamily?: FontFamilyValues;
|
|
||||||
textAlign?: TextAlign;
|
|
||||||
verticalAlign?: VerticalAlign;
|
|
||||||
containerId?: ExcalidrawTextContainer["id"] | null;
|
|
||||||
lineHeight?: ExcalidrawTextElement["lineHeight"];
|
|
||||||
autoResize?: ExcalidrawTextElement["autoResize"];
|
|
||||||
} & ElementConstructorOpts;
|
|
||||||
|
|
||||||
export const newTextElement = (
|
export const newTextElement = (
|
||||||
opts: NewTextElementOptions,
|
opts: {
|
||||||
|
text: string;
|
||||||
|
originalText?: string;
|
||||||
|
fontSize?: number;
|
||||||
|
fontFamily?: FontFamilyValues;
|
||||||
|
textAlign?: TextAlign;
|
||||||
|
verticalAlign?: VerticalAlign;
|
||||||
|
containerId?: ExcalidrawTextContainer["id"] | null;
|
||||||
|
lineHeight?: ExcalidrawTextElement["lineHeight"];
|
||||||
|
autoResize?: ExcalidrawTextElement["autoResize"];
|
||||||
|
} & ElementConstructorOpts,
|
||||||
): NonDeleted<ExcalidrawTextElement> => {
|
): NonDeleted<ExcalidrawTextElement> => {
|
||||||
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
|
const fontFamily = opts.fontFamily || DEFAULT_FONT_FAMILY;
|
||||||
const fontSize = opts.fontSize || DEFAULT_FONT_SIZE;
|
const fontSize = opts.fontSize || DEFAULT_FONT_SIZE;
|
||||||
const lineHeight = opts.lineHeight || getLineHeight(fontFamily);
|
const lineHeight = opts.lineHeight || getLineHeight(fontFamily);
|
||||||
const normalizedText = normalizeText(opts.text);
|
const text = normalizeText(opts.text);
|
||||||
const originalText = opts.originalText ?? normalizedText;
|
const metrics = measureText(
|
||||||
const metrics = getInitialTextMetrics(
|
text,
|
||||||
{ ...opts, text: normalizedText },
|
getFontString({ fontFamily, fontSize }),
|
||||||
fontFamily,
|
lineHeight,
|
||||||
fontSize,
|
|
||||||
);
|
);
|
||||||
const textAlign = opts.textAlign || DEFAULT_TEXT_ALIGN;
|
const textAlign = opts.textAlign || DEFAULT_TEXT_ALIGN;
|
||||||
const verticalAlign = opts.verticalAlign || DEFAULT_VERTICAL_ALIGN;
|
const verticalAlign = opts.verticalAlign || DEFAULT_VERTICAL_ALIGN;
|
||||||
@@ -270,7 +265,7 @@ export const newTextElement = (
|
|||||||
|
|
||||||
const textElementProps: ExcalidrawTextElement = {
|
const textElementProps: ExcalidrawTextElement = {
|
||||||
..._newElementBase<ExcalidrawTextElement>("text", opts),
|
..._newElementBase<ExcalidrawTextElement>("text", opts),
|
||||||
text: normalizedText,
|
text,
|
||||||
fontSize,
|
fontSize,
|
||||||
fontFamily,
|
fontFamily,
|
||||||
textAlign,
|
textAlign,
|
||||||
@@ -280,7 +275,7 @@ export const newTextElement = (
|
|||||||
width: metrics.width,
|
width: metrics.width,
|
||||||
height: metrics.height,
|
height: metrics.height,
|
||||||
containerId: opts.containerId || null,
|
containerId: opts.containerId || null,
|
||||||
originalText,
|
originalText: opts.originalText ?? text,
|
||||||
autoResize: opts.autoResize ?? true,
|
autoResize: opts.autoResize ?? true,
|
||||||
lineHeight,
|
lineHeight,
|
||||||
};
|
};
|
||||||
@@ -455,6 +450,7 @@ export const newFreeDrawElement = (
|
|||||||
points: opts.points || [],
|
points: opts.points || [],
|
||||||
pressures: opts.pressures || [],
|
pressures: opts.pressures || [],
|
||||||
simulatePressure: opts.simulatePressure,
|
simulatePressure: opts.simulatePressure,
|
||||||
|
lastCommittedPoint: null,
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -462,29 +458,17 @@ export const newLinearElement = (
|
|||||||
opts: {
|
opts: {
|
||||||
type: ExcalidrawLinearElement["type"];
|
type: ExcalidrawLinearElement["type"];
|
||||||
points?: ExcalidrawLinearElement["points"];
|
points?: ExcalidrawLinearElement["points"];
|
||||||
polygon?: ExcalidrawLineElement["polygon"];
|
|
||||||
} & ElementConstructorOpts,
|
} & ElementConstructorOpts,
|
||||||
): NonDeleted<ExcalidrawLinearElement> => {
|
): NonDeleted<ExcalidrawLinearElement> => {
|
||||||
const element = {
|
return {
|
||||||
..._newElementBase<ExcalidrawLinearElement>(opts.type, opts),
|
..._newElementBase<ExcalidrawLinearElement>(opts.type, opts),
|
||||||
points: opts.points || [],
|
points: opts.points || [],
|
||||||
|
lastCommittedPoint: null,
|
||||||
startBinding: null,
|
startBinding: null,
|
||||||
endBinding: null,
|
endBinding: null,
|
||||||
startArrowhead: null,
|
startArrowhead: null,
|
||||||
endArrowhead: null,
|
endArrowhead: null,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (isLineElement(element)) {
|
|
||||||
const lineElement: NonDeleted<ExcalidrawLineElement> = {
|
|
||||||
...element,
|
|
||||||
polygon: opts.polygon ?? false,
|
|
||||||
};
|
|
||||||
|
|
||||||
return lineElement;
|
|
||||||
}
|
|
||||||
|
|
||||||
return element;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const newArrowElement = <T extends boolean>(
|
export const newArrowElement = <T extends boolean>(
|
||||||
@@ -494,7 +478,7 @@ export const newArrowElement = <T extends boolean>(
|
|||||||
endArrowhead?: Arrowhead | null;
|
endArrowhead?: Arrowhead | null;
|
||||||
points?: ExcalidrawArrowElement["points"];
|
points?: ExcalidrawArrowElement["points"];
|
||||||
elbowed?: T;
|
elbowed?: T;
|
||||||
fixedSegments?: ExcalidrawElbowArrowElement["fixedSegments"] | null;
|
fixedSegments?: FixedSegment[] | null;
|
||||||
} & ElementConstructorOpts,
|
} & ElementConstructorOpts,
|
||||||
): T extends true
|
): T extends true
|
||||||
? NonDeleted<ExcalidrawElbowArrowElement>
|
? NonDeleted<ExcalidrawElbowArrowElement>
|
||||||
@@ -503,6 +487,7 @@ export const newArrowElement = <T extends boolean>(
|
|||||||
return {
|
return {
|
||||||
..._newElementBase<ExcalidrawElbowArrowElement>(opts.type, opts),
|
..._newElementBase<ExcalidrawElbowArrowElement>(opts.type, opts),
|
||||||
points: opts.points || [],
|
points: opts.points || [],
|
||||||
|
lastCommittedPoint: null,
|
||||||
startBinding: null,
|
startBinding: null,
|
||||||
endBinding: null,
|
endBinding: null,
|
||||||
startArrowhead: opts.startArrowhead || null,
|
startArrowhead: opts.startArrowhead || null,
|
||||||
@@ -517,6 +502,7 @@ export const newArrowElement = <T extends boolean>(
|
|||||||
return {
|
return {
|
||||||
..._newElementBase<ExcalidrawArrowElement>(opts.type, opts),
|
..._newElementBase<ExcalidrawArrowElement>(opts.type, opts),
|
||||||
points: opts.points || [],
|
points: opts.points || [],
|
||||||
|
lastCommittedPoint: null,
|
||||||
startBinding: null,
|
startBinding: null,
|
||||||
endBinding: null,
|
endBinding: null,
|
||||||
startArrowhead: opts.startArrowhead || null,
|
startArrowhead: opts.startArrowhead || null,
|
||||||
|
|||||||
@@ -1,112 +0,0 @@
|
|||||||
import { getCommonBounds } from "./bounds";
|
|
||||||
import { type ElementUpdate, newElementWith } from "./mutateElement";
|
|
||||||
|
|
||||||
import type { ExcalidrawElement } from "./types";
|
|
||||||
|
|
||||||
// TODO rewrite (mostly vibe-coded)
|
|
||||||
export const positionElementsOnGrid = <TElement extends ExcalidrawElement>(
|
|
||||||
elements: TElement[] | TElement[][],
|
|
||||||
centerX: number,
|
|
||||||
centerY: number,
|
|
||||||
padding = 50,
|
|
||||||
): TElement[] => {
|
|
||||||
// Ensure there are elements to position
|
|
||||||
if (!elements || elements.length === 0) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
const res: TElement[] = [];
|
|
||||||
// Normalize input to work with atomic units (groups of elements)
|
|
||||||
// If elements is a flat array, treat each element as its own atomic unit
|
|
||||||
const atomicUnits: TElement[][] = Array.isArray(elements[0])
|
|
||||||
? (elements as TElement[][])
|
|
||||||
: (elements as TElement[]).map((element) => [element]);
|
|
||||||
|
|
||||||
// Determine the number of columns for atomic units
|
|
||||||
// A common approach for a "grid-like" layout without specific column constraints
|
|
||||||
// is to aim for a roughly square arrangement.
|
|
||||||
const numUnits = atomicUnits.length;
|
|
||||||
const numColumns = Math.max(1, Math.ceil(Math.sqrt(numUnits)));
|
|
||||||
|
|
||||||
// Group atomic units into rows based on the calculated number of columns
|
|
||||||
const rows: TElement[][][] = [];
|
|
||||||
for (let i = 0; i < numUnits; i += numColumns) {
|
|
||||||
rows.push(atomicUnits.slice(i, i + numColumns));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Calculate properties for each row (total width, max height)
|
|
||||||
// and the total actual height of all row content.
|
|
||||||
let totalGridActualHeight = 0; // Sum of max heights of rows, without inter-row padding
|
|
||||||
const rowProperties = rows.map((rowUnits) => {
|
|
||||||
let rowWidth = 0;
|
|
||||||
let maxUnitHeightInRow = 0;
|
|
||||||
|
|
||||||
const unitBounds = rowUnits.map((unit) => {
|
|
||||||
const [minX, minY, maxX, maxY] = getCommonBounds(unit);
|
|
||||||
return {
|
|
||||||
elements: unit,
|
|
||||||
bounds: [minX, minY, maxX, maxY] as const,
|
|
||||||
width: maxX - minX,
|
|
||||||
height: maxY - minY,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
unitBounds.forEach((unitBound, index) => {
|
|
||||||
rowWidth += unitBound.width;
|
|
||||||
// Add padding between units in the same row, but not after the last one
|
|
||||||
if (index < unitBounds.length - 1) {
|
|
||||||
rowWidth += padding;
|
|
||||||
}
|
|
||||||
if (unitBound.height > maxUnitHeightInRow) {
|
|
||||||
maxUnitHeightInRow = unitBound.height;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
totalGridActualHeight += maxUnitHeightInRow;
|
|
||||||
return {
|
|
||||||
unitBounds,
|
|
||||||
width: rowWidth,
|
|
||||||
maxHeight: maxUnitHeightInRow,
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
// Calculate the total height of the grid including padding between rows
|
|
||||||
const totalGridHeightWithPadding =
|
|
||||||
totalGridActualHeight + Math.max(0, rows.length - 1) * padding;
|
|
||||||
|
|
||||||
// Calculate the starting Y position to center the entire grid vertically around centerY
|
|
||||||
let currentY = centerY - totalGridHeightWithPadding / 2;
|
|
||||||
|
|
||||||
// Position atomic units row by row
|
|
||||||
rowProperties.forEach((rowProp) => {
|
|
||||||
const { unitBounds, width: rowWidth, maxHeight: rowMaxHeight } = rowProp;
|
|
||||||
|
|
||||||
// Calculate the starting X for the current row to center it horizontally around centerX
|
|
||||||
let currentX = centerX - rowWidth / 2;
|
|
||||||
|
|
||||||
unitBounds.forEach((unitBound) => {
|
|
||||||
// Calculate the offset needed to position this atomic unit
|
|
||||||
const [originalMinX, originalMinY] = unitBound.bounds;
|
|
||||||
const offsetX = currentX - originalMinX;
|
|
||||||
const offsetY = currentY - originalMinY;
|
|
||||||
|
|
||||||
// Apply the offset to all elements in this atomic unit
|
|
||||||
unitBound.elements.forEach((element) => {
|
|
||||||
res.push(
|
|
||||||
newElementWith(element, {
|
|
||||||
x: element.x + offsetX,
|
|
||||||
y: element.y + offsetY,
|
|
||||||
} as ElementUpdate<TElement>),
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
// Move X for the next unit in the row
|
|
||||||
currentX += unitBound.width + padding;
|
|
||||||
});
|
|
||||||
|
|
||||||
// Move Y to the starting position for the next row
|
|
||||||
// This accounts for the tallest unit in the current row and the inter-row padding
|
|
||||||
currentY += rowMaxHeight + padding;
|
|
||||||
});
|
|
||||||
return res;
|
|
||||||
};
|
|
||||||
@@ -1,14 +1,7 @@
|
|||||||
import rough from "roughjs/bin/rough";
|
import rough from "roughjs/bin/rough";
|
||||||
import { getStroke } from "perfect-freehand";
|
import { getStroke } from "perfect-freehand";
|
||||||
|
|
||||||
import {
|
import { isRightAngleRads } from "@excalidraw/math";
|
||||||
type GlobalPoint,
|
|
||||||
isRightAngleRads,
|
|
||||||
lineSegment,
|
|
||||||
pointFrom,
|
|
||||||
pointRotateRads,
|
|
||||||
type Radians,
|
|
||||||
} from "@excalidraw/math";
|
|
||||||
|
|
||||||
import {
|
import {
|
||||||
BOUND_TEXT_PADDING,
|
BOUND_TEXT_PADDING,
|
||||||
@@ -21,7 +14,6 @@ import {
|
|||||||
getFontString,
|
getFontString,
|
||||||
isRTL,
|
isRTL,
|
||||||
getVerticalOffset,
|
getVerticalOffset,
|
||||||
invariant,
|
|
||||||
} from "@excalidraw/common";
|
} from "@excalidraw/common";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
@@ -40,7 +32,7 @@ import type {
|
|||||||
InteractiveCanvasRenderConfig,
|
InteractiveCanvasRenderConfig,
|
||||||
} from "@excalidraw/excalidraw/scene/types";
|
} from "@excalidraw/excalidraw/scene/types";
|
||||||
|
|
||||||
import { getElementAbsoluteCoords, getElementBounds } from "./bounds";
|
import { getElementAbsoluteCoords } from "./bounds";
|
||||||
import { getUncroppedImageElement } from "./cropElement";
|
import { getUncroppedImageElement } from "./cropElement";
|
||||||
import { LinearElementEditor } from "./linearElementEditor";
|
import { LinearElementEditor } from "./linearElementEditor";
|
||||||
import {
|
import {
|
||||||
@@ -62,9 +54,9 @@ import {
|
|||||||
isImageElement,
|
isImageElement,
|
||||||
} from "./typeChecks";
|
} from "./typeChecks";
|
||||||
import { getContainingFrame } from "./frame";
|
import { getContainingFrame } from "./frame";
|
||||||
import { getCornerRadius } from "./utils";
|
import { getCornerRadius } from "./shapes";
|
||||||
|
|
||||||
import { ShapeCache } from "./shape";
|
import { ShapeCache } from "./ShapeCache";
|
||||||
|
|
||||||
import type {
|
import type {
|
||||||
ExcalidrawElement,
|
ExcalidrawElement,
|
||||||
@@ -98,7 +90,7 @@ const isPendingImageElement = (
|
|||||||
const shouldResetImageFilter = (
|
const shouldResetImageFilter = (
|
||||||
element: ExcalidrawElement,
|
element: ExcalidrawElement,
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
renderConfig: StaticCanvasRenderConfig,
|
||||||
appState: StaticCanvasAppState | InteractiveCanvasAppState,
|
appState: StaticCanvasAppState,
|
||||||
) => {
|
) => {
|
||||||
return (
|
return (
|
||||||
appState.theme === THEME.DARK &&
|
appState.theme === THEME.DARK &&
|
||||||
@@ -114,11 +106,6 @@ const getCanvasPadding = (element: ExcalidrawElement) => {
|
|||||||
return element.strokeWidth * 12;
|
return element.strokeWidth * 12;
|
||||||
case "text":
|
case "text":
|
||||||
return element.fontSize / 2;
|
return element.fontSize / 2;
|
||||||
case "arrow":
|
|
||||||
if (element.endArrowhead || element.endArrowhead) {
|
|
||||||
return 40;
|
|
||||||
}
|
|
||||||
return 20;
|
|
||||||
default:
|
default:
|
||||||
return 20;
|
return 20;
|
||||||
}
|
}
|
||||||
@@ -225,7 +212,7 @@ const generateElementCanvas = (
|
|||||||
elementsMap: NonDeletedSceneElementsMap,
|
elementsMap: NonDeletedSceneElementsMap,
|
||||||
zoom: Zoom,
|
zoom: Zoom,
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
renderConfig: StaticCanvasRenderConfig,
|
||||||
appState: StaticCanvasAppState | InteractiveCanvasAppState,
|
appState: StaticCanvasAppState,
|
||||||
): ExcalidrawElementWithCanvas | null => {
|
): ExcalidrawElementWithCanvas | null => {
|
||||||
const canvas = document.createElement("canvas");
|
const canvas = document.createElement("canvas");
|
||||||
const context = canvas.getContext("2d")!;
|
const context = canvas.getContext("2d")!;
|
||||||
@@ -277,7 +264,7 @@ const generateElementCanvas = (
|
|||||||
context.filter = IMAGE_INVERT_FILTER;
|
context.filter = IMAGE_INVERT_FILTER;
|
||||||
}
|
}
|
||||||
|
|
||||||
drawElementOnCanvas(element, rc, context, renderConfig);
|
drawElementOnCanvas(element, rc, context, renderConfig, appState);
|
||||||
|
|
||||||
context.restore();
|
context.restore();
|
||||||
|
|
||||||
@@ -364,20 +351,12 @@ const generateElementCanvas = (
|
|||||||
|
|
||||||
export const DEFAULT_LINK_SIZE = 14;
|
export const DEFAULT_LINK_SIZE = 14;
|
||||||
|
|
||||||
const IMAGE_PLACEHOLDER_IMG =
|
const IMAGE_PLACEHOLDER_IMG = document.createElement("img");
|
||||||
typeof document !== "undefined"
|
|
||||||
? document.createElement("img")
|
|
||||||
: ({ src: "" } as HTMLImageElement); // mock image element outside of browser
|
|
||||||
|
|
||||||
IMAGE_PLACEHOLDER_IMG.src = `data:${MIME_TYPES.svg},${encodeURIComponent(
|
IMAGE_PLACEHOLDER_IMG.src = `data:${MIME_TYPES.svg},${encodeURIComponent(
|
||||||
`<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="image" class="svg-inline--fa fa-image fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="#888" d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56zM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48z"></path></svg>`,
|
`<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="image" class="svg-inline--fa fa-image fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="#888" d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56zM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48z"></path></svg>`,
|
||||||
)}`;
|
)}`;
|
||||||
|
|
||||||
const IMAGE_ERROR_PLACEHOLDER_IMG =
|
const IMAGE_ERROR_PLACEHOLDER_IMG = document.createElement("img");
|
||||||
typeof document !== "undefined"
|
|
||||||
? document.createElement("img")
|
|
||||||
: ({ src: "" } as HTMLImageElement); // mock image element outside of browser
|
|
||||||
|
|
||||||
IMAGE_ERROR_PLACEHOLDER_IMG.src = `data:${MIME_TYPES.svg},${encodeURIComponent(
|
IMAGE_ERROR_PLACEHOLDER_IMG.src = `data:${MIME_TYPES.svg},${encodeURIComponent(
|
||||||
`<svg viewBox="0 0 668 668" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48ZM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56ZM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.81709 0 0 .81709 124.825 145.825)"/><path d="M256 8C119.034 8 8 119.033 8 256c0 136.967 111.034 248 248 248s248-111.034 248-248S392.967 8 256 8Zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676ZM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.30366 0 0 .30366 506.822 60.065)"/></svg>`,
|
`<svg viewBox="0 0 668 668" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48ZM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56ZM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.81709 0 0 .81709 124.825 145.825)"/><path d="M256 8C119.034 8 8 119.033 8 256c0 136.967 111.034 248 248 248s248-111.034 248-248S392.967 8 256 8Zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676ZM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.30366 0 0 .30366 506.822 60.065)"/></svg>`,
|
||||||
)}`;
|
)}`;
|
||||||
@@ -412,6 +391,7 @@ const drawElementOnCanvas = (
|
|||||||
rc: RoughCanvas,
|
rc: RoughCanvas,
|
||||||
context: CanvasRenderingContext2D,
|
context: CanvasRenderingContext2D,
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
renderConfig: StaticCanvasRenderConfig,
|
||||||
|
appState: StaticCanvasAppState,
|
||||||
) => {
|
) => {
|
||||||
switch (element.type) {
|
switch (element.type) {
|
||||||
case "rectangle":
|
case "rectangle":
|
||||||
@@ -557,7 +537,7 @@ const generateElementWithCanvas = (
|
|||||||
element: NonDeletedExcalidrawElement,
|
element: NonDeletedExcalidrawElement,
|
||||||
elementsMap: NonDeletedSceneElementsMap,
|
elementsMap: NonDeletedSceneElementsMap,
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
renderConfig: StaticCanvasRenderConfig,
|
||||||
appState: StaticCanvasAppState | InteractiveCanvasAppState,
|
appState: StaticCanvasAppState,
|
||||||
) => {
|
) => {
|
||||||
const zoom: Zoom = renderConfig
|
const zoom: Zoom = renderConfig
|
||||||
? appState.zoom
|
? appState.zoom
|
||||||
@@ -614,7 +594,7 @@ const drawElementFromCanvas = (
|
|||||||
elementWithCanvas: ExcalidrawElementWithCanvas,
|
elementWithCanvas: ExcalidrawElementWithCanvas,
|
||||||
context: CanvasRenderingContext2D,
|
context: CanvasRenderingContext2D,
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
renderConfig: StaticCanvasRenderConfig,
|
||||||
appState: StaticCanvasAppState | InteractiveCanvasAppState,
|
appState: StaticCanvasAppState,
|
||||||
allElementsMap: NonDeletedSceneElementsMap,
|
allElementsMap: NonDeletedSceneElementsMap,
|
||||||
) => {
|
) => {
|
||||||
const element = elementWithCanvas.element;
|
const element = elementWithCanvas.element;
|
||||||
@@ -732,7 +712,7 @@ export const renderElement = (
|
|||||||
rc: RoughCanvas,
|
rc: RoughCanvas,
|
||||||
context: CanvasRenderingContext2D,
|
context: CanvasRenderingContext2D,
|
||||||
renderConfig: StaticCanvasRenderConfig,
|
renderConfig: StaticCanvasRenderConfig,
|
||||||
appState: StaticCanvasAppState | InteractiveCanvasAppState,
|
appState: StaticCanvasAppState,
|
||||||
) => {
|
) => {
|
||||||
const reduceAlphaForSelection =
|
const reduceAlphaForSelection =
|
||||||
appState.openDialog?.name === "elementLinkSelector" &&
|
appState.openDialog?.name === "elementLinkSelector" &&
|
||||||
@@ -802,7 +782,7 @@ export const renderElement = (
|
|||||||
context.translate(cx, cy);
|
context.translate(cx, cy);
|
||||||
context.rotate(element.angle);
|
context.rotate(element.angle);
|
||||||
context.translate(-shiftX, -shiftY);
|
context.translate(-shiftX, -shiftY);
|
||||||
drawElementOnCanvas(element, rc, context, renderConfig);
|
drawElementOnCanvas(element, rc, context, renderConfig, appState);
|
||||||
context.restore();
|
context.restore();
|
||||||
} else {
|
} else {
|
||||||
const elementWithCanvas = generateElementWithCanvas(
|
const elementWithCanvas = generateElementWithCanvas(
|
||||||
@@ -895,7 +875,13 @@ export const renderElement = (
|
|||||||
|
|
||||||
tempCanvasContext.translate(-shiftX, -shiftY);
|
tempCanvasContext.translate(-shiftX, -shiftY);
|
||||||
|
|
||||||
drawElementOnCanvas(element, tempRc, tempCanvasContext, renderConfig);
|
drawElementOnCanvas(
|
||||||
|
element,
|
||||||
|
tempRc,
|
||||||
|
tempCanvasContext,
|
||||||
|
renderConfig,
|
||||||
|
appState,
|
||||||
|
);
|
||||||
|
|
||||||
tempCanvasContext.translate(shiftX, shiftY);
|
tempCanvasContext.translate(shiftX, shiftY);
|
||||||
|
|
||||||
@@ -934,7 +920,7 @@ export const renderElement = (
|
|||||||
}
|
}
|
||||||
|
|
||||||
context.translate(-shiftX, -shiftY);
|
context.translate(-shiftX, -shiftY);
|
||||||
drawElementOnCanvas(element, rc, context, renderConfig);
|
drawElementOnCanvas(element, rc, context, renderConfig, appState);
|
||||||
}
|
}
|
||||||
|
|
||||||
context.restore();
|
context.restore();
|
||||||
@@ -1040,66 +1026,6 @@ export function getFreeDrawPath2D(element: ExcalidrawFreeDrawElement) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function getFreeDrawSvgPath(element: ExcalidrawFreeDrawElement) {
|
export function getFreeDrawSvgPath(element: ExcalidrawFreeDrawElement) {
|
||||||
return getSvgPathFromStroke(getFreedrawOutlinePoints(element));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFreedrawOutlineAsSegments(
|
|
||||||
element: ExcalidrawFreeDrawElement,
|
|
||||||
points: [number, number][],
|
|
||||||
elementsMap: ElementsMap,
|
|
||||||
) {
|
|
||||||
const bounds = getElementBounds(
|
|
||||||
{
|
|
||||||
...element,
|
|
||||||
angle: 0 as Radians,
|
|
||||||
},
|
|
||||||
elementsMap,
|
|
||||||
);
|
|
||||||
const center = pointFrom<GlobalPoint>(
|
|
||||||
(bounds[0] + bounds[2]) / 2,
|
|
||||||
(bounds[1] + bounds[3]) / 2,
|
|
||||||
);
|
|
||||||
|
|
||||||
invariant(points.length >= 2, "Freepath outline must have at least 2 points");
|
|
||||||
|
|
||||||
return points.slice(2).reduce(
|
|
||||||
(acc, curr) => {
|
|
||||||
acc.push(
|
|
||||||
lineSegment<GlobalPoint>(
|
|
||||||
acc[acc.length - 1][1],
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(curr[0] + element.x, curr[1] + element.y),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
);
|
|
||||||
return acc;
|
|
||||||
},
|
|
||||||
[
|
|
||||||
lineSegment<GlobalPoint>(
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
points[0][0] + element.x,
|
|
||||||
points[0][1] + element.y,
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
pointRotateRads(
|
|
||||||
pointFrom<GlobalPoint>(
|
|
||||||
points[1][0] + element.x,
|
|
||||||
points[1][1] + element.y,
|
|
||||||
),
|
|
||||||
center,
|
|
||||||
element.angle,
|
|
||||||
),
|
|
||||||
),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFreedrawOutlinePoints(element: ExcalidrawFreeDrawElement) {
|
|
||||||
// If input points are empty (should they ever be?) return a dot
|
// If input points are empty (should they ever be?) return a dot
|
||||||
const inputPoints = element.simulatePressure
|
const inputPoints = element.simulatePressure
|
||||||
? element.points
|
? element.points
|
||||||
@@ -1115,10 +1041,10 @@ export function getFreedrawOutlinePoints(element: ExcalidrawFreeDrawElement) {
|
|||||||
smoothing: 0.5,
|
smoothing: 0.5,
|
||||||
streamline: 0.5,
|
streamline: 0.5,
|
||||||
easing: (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine
|
easing: (t) => Math.sin((t * Math.PI) / 2), // https://easings.net/#easeOutSine
|
||||||
last: true,
|
last: !!element.lastCommittedPoint, // LastCommittedPoint is added on pointerup
|
||||||
};
|
};
|
||||||
|
|
||||||
return getStroke(inputPoints as number[][], options) as [number, number][];
|
return getSvgPathFromStroke(getStroke(inputPoints as number[][], options));
|
||||||
}
|
}
|
||||||
|
|
||||||
function med(A: number[], B: number[]) {
|
function med(A: number[], B: number[]) {
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user