Tldraw/packages/tldraw/src/lib/defaultExternalContentHandl...

532 wiersze
14 KiB
TypeScript
Czysty Zwykły widok Historia

import {
AssetRecordType,
Editor,
FileHelpers,
MediaHelpers,
TLAsset,
TLAssetId,
TLBookmarkShape,
TLEmbedShape,
TLShapeId,
TLShapePartial,
TLTextShape,
TLTextShapeProps,
Vec,
VecLike,
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
assert,
compact,
createShapeId,
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
getHashForBuffer,
getHashForString,
} from '@tldraw/editor'
import { FONT_FAMILIES, FONT_SIZES, TEXT_PROPS } from './shapes/shared/default-shape-constants'
import { TLUiToastsContextType } from './ui/context/toasts'
import { useTranslation } from './ui/hooks/useTranslation/useTranslation'
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
import { containBoxSize, downsizeImage, isGifAnimated } from './utils/assets/assets'
import { getEmbedInfo } from './utils/embeds/embeds'
import { cleanupText, isRightToLeftLanguage, truncateStringWithEllipsis } from './utils/text/text'
/** @public */
export type TLExternalContentProps = {
// The maximum dimension (width or height) of an image. Images larger than this will be rescaled to fit. Defaults to infinity.
maxImageDimension: number
// The maximum size (in bytes) of an asset. Assets larger than this will be rejected. Defaults to 10mb (10 * 1024 * 1024).
maxAssetSize: number
// The mime types of images that are allowed to be handled. Defaults to ['image/jpeg', 'image/png', 'image/gif', 'image/svg+xml'].
Composable custom UI (#2796) This PR refactors our menu systems and provides an interface to hide or replace individual user interface elements. # Background Previously, we've had two types of overrides: - "schema" overrides that would allow insertion or replacement of items in the different menus - "component" overrides that would replace components in the editor's user interface This PR is an attempt to unify the two and to provide for additional cases where the "schema-based" user interface had begun to break down. # Approach This PR makes no attempt to change the `actions` or `tools` overrides—the current system seems to be correct for those because they are not reactive. The challenge with the other ui schemas is that they _are_ reactive, and thus the overrides both need to a) be fed in from outside of the editor as props, and b) react to changes from the editor, which is an impossible situation. The new approach is to use React to declare menu items. (Surprise!) ```tsx function CustomHelpMenuContent() { return ( <> <DefaultHelpMenuContent /> <TldrawUiMenuGroup id="custom stuff"> <TldrawUiMenuItem id="about" label="Like my posts" icon="external-link" readonlyOk onSelect={() => { window.open('https://x.com/tldraw', '_blank') }} /> </TldrawUiMenuGroup> </> ) } const components: TLComponents = { HelpMenuContent: CustomHelpMenuContent, } export default function CustomHelpMenuContentExample() { return ( <div className="tldraw__editor"> <Tldraw components={components} /> </div> ) } ``` We use a `components` prop with the combined editor and ui components. - [ ] Create a "layout" component? - [ ] Make UI components more isolated? If possible, they shouldn't depend on styles outside of themselves, so that they can be used in other layouts. Maybe we wait on this because I'm feeling a slippery slope toward presumptions about configurability. - [ ] OTOH maybe we go hard and consider these things as separate components, even packages, with their own interfaces for customizability / configurability, just go all the way with it, and see what that looks like. # Pros Top line: you can customize tldraw's user interface in a MUCH more granular / powerful way than before. It solves a case where menu items could not be made stateful from outside of the editor context, and provides the option to do things in the menus that we couldn't allow previously with the "schema-based" approach. It also may (who knows) be more performant because we can locate the state inside of the components for individual buttons and groups, instead of all at the top level above the "schema". Because items / groups decide their own state, we don't have to have big checks on how many items are selected, or whether we have a flippable state. Items and groups themselves are allowed to re-build as part of the regular React lifecycle. Menus aren't constantly being rebuilt, if that were ever an issue. Menu items can be shared between different menu types. We'll are sometimes able to re-use items between, for example, the menu and the context menu and the actions menu. Our overrides no longer mutate anything, so there's less weird searching and finding. # Cons This approach can make customization menu contents significantly more complex, as an end user would need to re-declare most of a menu in order to make any change to it. Luckily a user can add things to the top or bottom of the context menu fairly easily. (And who knows, folks may actually want to do deep customization, and this allows for it.) It's more code. We are shipping more react components, basically one for each menu item / group. Currently this PR does not export the subcomponents, i.e. menu items. If we do want to export these, then heaven help us, it's going to be a _lot_ of exports. # Progress - [x] Context menu - [x] Main menu - [x] Zoom menu - [x] Help menu - [x] Actions menu - [x] Keyboard shortcuts menu - [x] Quick actions in main menu? (new) - [x] Helper buttons? (new) - [x] Debug Menu And potentially - [x] Toolbar - [x] Style menu - [ ] Share zone - [x] Navigation zone - [ ] Other zones ### Change Type - [x] `major` — Breaking change ### Test Plan 1. use the context menu 2. use the custom context menu example 3. use cursor chat in the context menu - [x] Unit Tests - [ ] End to end tests ### Release Notes - Add a brief release note for your PR here.
2024-02-15 12:10:09 +00:00
acceptedImageMimeTypes: readonly string[]
// The mime types of videos that are allowed to be handled. Defaults to ['video/mp4', 'video/webm', 'video/quicktime'].
Composable custom UI (#2796) This PR refactors our menu systems and provides an interface to hide or replace individual user interface elements. # Background Previously, we've had two types of overrides: - "schema" overrides that would allow insertion or replacement of items in the different menus - "component" overrides that would replace components in the editor's user interface This PR is an attempt to unify the two and to provide for additional cases where the "schema-based" user interface had begun to break down. # Approach This PR makes no attempt to change the `actions` or `tools` overrides—the current system seems to be correct for those because they are not reactive. The challenge with the other ui schemas is that they _are_ reactive, and thus the overrides both need to a) be fed in from outside of the editor as props, and b) react to changes from the editor, which is an impossible situation. The new approach is to use React to declare menu items. (Surprise!) ```tsx function CustomHelpMenuContent() { return ( <> <DefaultHelpMenuContent /> <TldrawUiMenuGroup id="custom stuff"> <TldrawUiMenuItem id="about" label="Like my posts" icon="external-link" readonlyOk onSelect={() => { window.open('https://x.com/tldraw', '_blank') }} /> </TldrawUiMenuGroup> </> ) } const components: TLComponents = { HelpMenuContent: CustomHelpMenuContent, } export default function CustomHelpMenuContentExample() { return ( <div className="tldraw__editor"> <Tldraw components={components} /> </div> ) } ``` We use a `components` prop with the combined editor and ui components. - [ ] Create a "layout" component? - [ ] Make UI components more isolated? If possible, they shouldn't depend on styles outside of themselves, so that they can be used in other layouts. Maybe we wait on this because I'm feeling a slippery slope toward presumptions about configurability. - [ ] OTOH maybe we go hard and consider these things as separate components, even packages, with their own interfaces for customizability / configurability, just go all the way with it, and see what that looks like. # Pros Top line: you can customize tldraw's user interface in a MUCH more granular / powerful way than before. It solves a case where menu items could not be made stateful from outside of the editor context, and provides the option to do things in the menus that we couldn't allow previously with the "schema-based" approach. It also may (who knows) be more performant because we can locate the state inside of the components for individual buttons and groups, instead of all at the top level above the "schema". Because items / groups decide their own state, we don't have to have big checks on how many items are selected, or whether we have a flippable state. Items and groups themselves are allowed to re-build as part of the regular React lifecycle. Menus aren't constantly being rebuilt, if that were ever an issue. Menu items can be shared between different menu types. We'll are sometimes able to re-use items between, for example, the menu and the context menu and the actions menu. Our overrides no longer mutate anything, so there's less weird searching and finding. # Cons This approach can make customization menu contents significantly more complex, as an end user would need to re-declare most of a menu in order to make any change to it. Luckily a user can add things to the top or bottom of the context menu fairly easily. (And who knows, folks may actually want to do deep customization, and this allows for it.) It's more code. We are shipping more react components, basically one for each menu item / group. Currently this PR does not export the subcomponents, i.e. menu items. If we do want to export these, then heaven help us, it's going to be a _lot_ of exports. # Progress - [x] Context menu - [x] Main menu - [x] Zoom menu - [x] Help menu - [x] Actions menu - [x] Keyboard shortcuts menu - [x] Quick actions in main menu? (new) - [x] Helper buttons? (new) - [x] Debug Menu And potentially - [x] Toolbar - [x] Style menu - [ ] Share zone - [x] Navigation zone - [ ] Other zones ### Change Type - [x] `major` — Breaking change ### Test Plan 1. use the context menu 2. use the custom context menu example 3. use cursor chat in the context menu - [x] Unit Tests - [ ] End to end tests ### Release Notes - Add a brief release note for your PR here.
2024-02-15 12:10:09 +00:00
acceptedVideoMimeTypes: readonly string[]
}
export function registerDefaultExternalContentHandlers(
editor: Editor,
{
maxImageDimension,
maxAssetSize,
acceptedImageMimeTypes,
acceptedVideoMimeTypes,
}: TLExternalContentProps,
{ toasts, msg }: { toasts: TLUiToastsContextType; msg: ReturnType<typeof useTranslation> }
) {
// files -> asset
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
editor.registerExternalAssetHandler('file', async ({ file: _file }) => {
const name = _file.name
let file: Blob = _file
const isImageType = acceptedImageMimeTypes.includes(file.type)
const isVideoType = acceptedVideoMimeTypes.includes(file.type)
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
assert(isImageType || isVideoType, `File type not allowed: ${file.type}`)
assert(
file.size <= maxAssetSize,
`File size too big: ${(file.size / 1024).toFixed()}kb > ${(maxAssetSize / 1024).toFixed()}kb`
)
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
if (file.type === 'video/quicktime') {
// hack to make .mov videos work
file = new Blob([file], { type: 'video/mp4' })
}
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
let size = isImageType
? await MediaHelpers.getImageSize(file)
: await MediaHelpers.getVideoSize(file)
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
const isAnimated = file.type === 'image/gif' ? await isGifAnimated(file) : isVideoType
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
const hash = await getHashForBuffer(await file.arrayBuffer())
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
if (isFinite(maxImageDimension)) {
const resizedSize = containBoxSize(size, { w: maxImageDimension, h: maxImageDimension })
if (size !== resizedSize && (file.type === 'image/jpeg' || file.type === 'image/png')) {
size = resizedSize
}
}
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
// Always rescale the image
if (file.type === 'image/jpeg' || file.type === 'image/png') {
file = await downsizeImage(file, size.w, size.h, {
type: file.type,
quality: 0.92,
})
}
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
const assetId: TLAssetId = AssetRecordType.createId(hash)
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
const asset = AssetRecordType.create({
id: assetId,
type: isImageType ? 'image' : 'video',
typeName: 'asset',
props: {
name,
src: await FileHelpers.blobToDataUrl(file),
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
w: size.w,
h: size.h,
mimeType: file.type,
isAnimated,
},
})
faster image processing in default asset handler (#2441) ![Kapture 2024-01-10 at 13 42 06](https://github.com/tldraw/tldraw/assets/1489520/616bcda7-c05b-46f1-b985-3a36bb5c9476) (gif is with 6x CPU throttling to make the effect more visible) This is the first of a few diffs I'm working on to make dropping images onto the canvas feel a lot faster. There are three main changes here: 1. We operate on `Blob`s and `File`s rather than data urls. This saves a fair bit on converting to/from base64 all the time. I've updated our `MediaHelper` APIs to encourage the same in consumers. 2. We only check the max canvas size (slow) if images are above a certain dimension that we consider "safe" (8k x 8k) 3. Switching from the `downscale` npm library to canvas native downscaling. that library claims to give better results than the browser, but hasn't been updated in ~7 years. in modern browsers, we can opt-in to native high-quality image smoothing to achieve similar results much faster than with an algorithm implemented in pure JS. I want to follow this up with a system to show image placeholders whilst we're waiting for long-running operations like resizing etc but i'm going to split that out into its own diff as it'll involve some fairly complex changes to the history management API. ### Change Type - [x] `major` — Breaking change [^1]: publishes a `patch` release, for devDependencies use `internal` [^2]: will not publish a new version ### Test Plan 1. Tested manually, unit tests & end-to-end tests pass
2024-01-10 14:41:18 +00:00
return asset
})
// urls -> bookmark asset
editor.registerExternalAssetHandler('url', async ({ url }) => {
let meta: { image: string; title: string; description: string }
try {
const resp = await fetch(url, { method: 'GET', mode: 'no-cors' })
const html = await resp.text()
const doc = new DOMParser().parseFromString(html, 'text/html')
meta = {
image: doc.head.querySelector('meta[property="og:image"]')?.getAttribute('content') ?? '',
title:
doc.head.querySelector('meta[property="og:title"]')?.getAttribute('content') ??
truncateStringWithEllipsis(url, 32),
description:
doc.head.querySelector('meta[property="og:description"]')?.getAttribute('content') ?? '',
}
} catch (error) {
console.error(error)
toasts.addToast({
title: msg('assets.url.failed'),
severity: 'error',
})
meta = { image: '', title: truncateStringWithEllipsis(url, 32), description: '' }
}
// Create the bookmark asset from the meta
return {
id: AssetRecordType.createId(getHashForString(url)),
typeName: 'asset',
type: 'bookmark',
props: {
src: url,
description: meta.description,
image: meta.image,
title: meta.title,
},
meta: {},
}
})
// svg text
editor.registerExternalContentHandler('svg-text', async ({ point, text }) => {
const position =
point ??
(editor.inputs.shiftKey ? editor.inputs.currentPagePoint : editor.getViewportPageCenter())
const svg = new DOMParser().parseFromString(text, 'image/svg+xml').querySelector('svg')
if (!svg) {
throw new Error('No <svg/> element present')
}
let width = parseFloat(svg.getAttribute('width') || '0')
let height = parseFloat(svg.getAttribute('height') || '0')
if (!(width && height)) {
document.body.appendChild(svg)
const box = svg.getBoundingClientRect()
document.body.removeChild(svg)
width = box.width
height = box.height
}
const asset = await editor.getAssetForExternalContent({
type: 'file',
file: new File([text], 'asset.svg', { type: 'image/svg+xml' }),
})
if (!asset) throw Error('Could not create an asset')
createShapesForAssets(editor, [asset], position)
})
// embeds
editor.registerExternalContentHandler('embed', ({ point, url, embed }) => {
const position =
point ??
(editor.inputs.shiftKey ? editor.inputs.currentPagePoint : editor.getViewportPageCenter())
const { width, height } = embed
const id = createShapeId()
const shapePartial: TLShapePartial<TLEmbedShape> = {
id,
type: 'embed',
x: position.x - (width || 450) / 2,
y: position.y - (height || 450) / 2,
props: {
w: width,
h: height,
url,
},
}
editor.createShapes([shapePartial]).select(id)
})
// files
editor.registerExternalContentHandler('files', async ({ point, files }) => {
const position =
point ??
(editor.inputs.shiftKey ? editor.inputs.currentPagePoint : editor.getViewportPageCenter())
const pagePoint = new Vec(position.x, position.y)
const assets: TLAsset[] = []
await Promise.all(
files.map(async (file, i) => {
if (file.size > maxAssetSize) {
console.warn(
`File size too big: ${(file.size / 1024).toFixed()}kb > ${(
maxAssetSize / 1024
).toFixed()}kb`
)
return null
}
// Use mime type instead of file ext, this is because
// window.navigator.clipboard does not preserve file names
// of copied files.
if (!file.type) {
throw new Error('No mime type')
}
// We can only accept certain extensions (either images or a videos)
if (!acceptedImageMimeTypes.concat(acceptedVideoMimeTypes).includes(file.type)) {
console.warn(`${file.name} not loaded - Extension not allowed.`)
return null
}
try {
const asset = await editor.getAssetForExternalContent({ type: 'file', file })
if (!asset) {
throw Error('Could not create an asset')
}
assets[i] = asset
} catch (error) {
toasts.addToast({
title: msg('assets.files.upload-failed'),
severity: 'error',
})
console.error(error)
return null
}
})
)
createShapesForAssets(editor, compact(assets), pagePoint)
})
// text
editor.registerExternalContentHandler('text', async ({ point, text }) => {
const p =
point ??
(editor.inputs.shiftKey ? editor.inputs.currentPagePoint : editor.getViewportPageCenter())
const defaultProps = editor.getShapeUtil<TLTextShape>('text').getDefaultProps()
const textToPaste = cleanupText(text)
// Measure the text with default values
let w: number
let h: number
let autoSize: boolean
let align = 'middle' as TLTextShapeProps['align']
const isMultiLine = textToPaste.split('\n').length > 1
// check whether the text contains the most common characters in RTL languages
const isRtl = isRightToLeftLanguage(textToPaste)
if (isMultiLine) {
align = isMultiLine ? (isRtl ? 'end' : 'start') : 'middle'
}
const rawSize = editor.textMeasure.measureText(textToPaste, {
...TEXT_PROPS,
fontFamily: FONT_FAMILIES[defaultProps.font],
fontSize: FONT_SIZES[defaultProps.size],
maxWidth: null,
})
const minWidth = Math.min(
isMultiLine ? editor.getViewportPageBounds().width * 0.9 : 920,
Math.max(200, editor.getViewportPageBounds().width * 0.9)
)
if (rawSize.w > minWidth) {
const shrunkSize = editor.textMeasure.measureText(textToPaste, {
...TEXT_PROPS,
fontFamily: FONT_FAMILIES[defaultProps.font],
fontSize: FONT_SIZES[defaultProps.size],
maxWidth: minWidth,
})
w = shrunkSize.w
h = shrunkSize.h
autoSize = false
align = isRtl ? 'end' : 'start'
} else {
// autosize is fine
w = rawSize.w
h = rawSize.h
autoSize = true
}
if (p.y - h / 2 < editor.getViewportPageBounds().minY + 40) {
p.y = editor.getViewportPageBounds().minY + 40 + h / 2
}
editor.createShapes<TLTextShape>([
{
id: createShapeId(),
type: 'text',
x: p.x - w / 2,
y: p.y - h / 2,
props: {
text: textToPaste,
// if the text has more than one line, align it to the left
align,
autoSize,
w,
},
},
])
})
// url
editor.registerExternalContentHandler('url', async ({ point, url }) => {
// try to paste as an embed first
const embedInfo = getEmbedInfo(url)
if (embedInfo) {
return editor.putExternalContent({
type: 'embed',
url: embedInfo.url,
point,
embed: embedInfo.definition,
})
}
const position =
point ??
(editor.inputs.shiftKey ? editor.inputs.currentPagePoint : editor.getViewportPageCenter())
const assetId: TLAssetId = AssetRecordType.createId(getHashForString(url))
const shape = createEmptyBookmarkShape(editor, url, position)
// Use an existing asset if we have one, or else else create a new one
let asset = editor.getAsset(assetId) as TLAsset
let shouldAlsoCreateAsset = false
if (!asset) {
shouldAlsoCreateAsset = true
try {
const bookmarkAsset = await editor.getAssetForExternalContent({ type: 'url', url })
if (!bookmarkAsset) throw Error('Could not create an asset')
asset = bookmarkAsset
} catch (e) {
toasts.addToast({
title: msg('assets.url.failed'),
severity: 'error',
})
return
}
}
editor.batch(() => {
if (shouldAlsoCreateAsset) {
editor.createAssets([asset])
}
editor.updateShapes([
{
id: shape.id,
type: shape.type,
props: {
assetId: asset.id,
},
},
])
})
})
}
export async function createShapesForAssets(
editor: Editor,
assets: TLAsset[],
position: VecLike
): Promise<TLShapeId[]> {
if (!assets.length) return []
const currentPoint = Vec.From(position)
const partials: TLShapePartial[] = []
for (const asset of assets) {
switch (asset.type) {
case 'bookmark': {
partials.push({
id: createShapeId(),
type: 'bookmark',
x: currentPoint.x - 150,
y: currentPoint.y - 160,
opacity: 1,
props: {
assetId: asset.id,
url: asset.props.src,
},
})
currentPoint.x += 300
break
}
case 'image': {
partials.push({
id: createShapeId(),
type: 'image',
x: currentPoint.x - asset.props.w / 2,
y: currentPoint.y - asset.props.h / 2,
opacity: 1,
props: {
assetId: asset.id,
w: asset.props.w,
h: asset.props.h,
},
})
currentPoint.x += asset.props.w
break
}
case 'video': {
partials.push({
id: createShapeId(),
type: 'video',
x: currentPoint.x - asset.props.w / 2,
y: currentPoint.y - asset.props.h / 2,
opacity: 1,
props: {
assetId: asset.id,
w: asset.props.w,
h: asset.props.h,
},
})
currentPoint.x += asset.props.w
}
}
}
editor.batch(() => {
// Create any assets
const assetsToCreate = assets.filter((asset) => !editor.getAsset(asset.id))
if (assetsToCreate.length) {
editor.createAssets(assetsToCreate)
}
// Create the shapes
editor.createShapes(partials).select(...partials.map((p) => p.id))
// Re-position shapes so that the center of the group is at the provided point
centerSelectionAroundPoint(editor, position)
})
return partials.map((p) => p.id)
}
function centerSelectionAroundPoint(editor: Editor, position: VecLike) {
// Re-position shapes so that the center of the group is at the provided point
const viewportPageBounds = editor.getViewportPageBounds()
let selectionPageBounds = editor.getSelectionPageBounds()
if (selectionPageBounds) {
const offset = selectionPageBounds!.center.sub(position)
editor.updateShapes(
editor.getSelectedShapes().map((shape) => {
const localRotation = editor.getShapeParentTransform(shape).decompose().rotation
const localDelta = Vec.Rot(offset, -localRotation)
return {
id: shape.id,
type: shape.type,
x: shape.x! - localDelta.x,
y: shape.y! - localDelta.y,
}
})
)
}
// Zoom out to fit the shapes, if necessary
selectionPageBounds = editor.getSelectionPageBounds()
if (selectionPageBounds && !viewportPageBounds.contains(selectionPageBounds)) {
editor.zoomToSelection()
}
}
export function createEmptyBookmarkShape(
editor: Editor,
url: string,
position: VecLike
): TLBookmarkShape {
const partial: TLShapePartial = {
id: createShapeId(),
type: 'bookmark',
x: position.x - 150,
y: position.y - 160,
opacity: 1,
props: {
assetId: null,
url,
},
}
editor.batch(() => {
editor.createShapes([partial]).select(partial.id)
centerSelectionAroundPoint(editor, position)
})
return editor.getShape(partial.id) as TLBookmarkShape
}