Tldraw/packages/tldraw/src/lib/ui/components/Minimap/MinimapManager.ts

380 wiersze
8.9 KiB
TypeScript
Czysty Zwykły widok Historia

tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
import {
Box,
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
Editor,
PI2,
TLInstancePresence,
TLShapeId,
Vec,
tldraw zero - package shuffle (#1710) This PR moves code between our packages so that: - @tldraw/editor is a “core” library with the engine and canvas but no shapes, tools, or other things - @tldraw/tldraw contains everything particular to the experience we’ve built for tldraw At first look, this might seem like a step away from customization and configuration, however I believe it greatly increases the configuration potential of the @tldraw/editor while also providing a more accurate reflection of what configuration options actually exist for @tldraw/tldraw. ## Library changes @tldraw/editor re-exports its dependencies and @tldraw/tldraw re-exports @tldraw/editor. - users of @tldraw/editor WITHOUT @tldraw/tldraw should almost always only import things from @tldraw/editor. - users of @tldraw/tldraw should almost always only import things from @tldraw/tldraw. - @tldraw/polyfills is merged into @tldraw/editor - @tldraw/indices is merged into @tldraw/editor - @tldraw/primitives is merged mostly into @tldraw/editor, partially into @tldraw/tldraw - @tldraw/file-format is merged into @tldraw/tldraw - @tldraw/ui is merged into @tldraw/tldraw Many (many) utils and other code is moved from the editor to tldraw. For example, embeds now are entirely an feature of @tldraw/tldraw. The only big chunk of code left in core is related to arrow handling. ## API Changes The editor can now be used without tldraw's assets. We load them in @tldraw/tldraw instead, so feel free to use whatever fonts or images or whatever that you like with the editor. All tools and shapes (except for the `Group` shape) are moved to @tldraw/tldraw. This includes the `select` tool. You should use the editor with at least one tool, however, so you now also need to send in an `initialState` prop to the Editor / <TldrawEditor> component indicating which state the editor should begin in. The `components` prop now also accepts `SelectionForeground`. The complex selection component that we use for tldraw is moved to @tldraw/tldraw. The default component is quite basic but can easily be replaced via the `components` prop. We pass down our tldraw-flavored SelectionFg via `components`. Likewise with the `Scribble` component: the `DefaultScribble` no longer uses our freehand tech and is a simple path instead. We pass down the tldraw-flavored scribble via `components`. The `ExternalContentManager` (`Editor.externalContentManager`) is removed and replaced with a mapping of types to handlers. - Register new content handlers with `Editor.registerExternalContentHandler`. - Register new asset creation handlers (for files and URLs) with `Editor.registerExternalAssetHandler` ### Change Type - [x] `major` — Breaking change ### Test Plan - [x] Unit Tests - [x] End to end tests ### Release Notes - [@tldraw/editor] lots, wip - [@tldraw/ui] gone, merged to tldraw/tldraw - [@tldraw/polyfills] gone, merged to tldraw/editor - [@tldraw/primitives] gone, merged to tldraw/editor / tldraw/tldraw - [@tldraw/indices] gone, merged to tldraw/editor - [@tldraw/file-format] gone, merged to tldraw/tldraw --------- Co-authored-by: alex <alex@dytry.ch>
2023-07-17 21:22:34 +00:00
clamp,
uniqueId,
} from '@tldraw/editor'
2023-04-25 11:01:25 +00:00
export class MinimapManager {
constructor(public editor: Editor) {}
dpr = 1
2023-04-25 11:01:25 +00:00
colors = {
shapeFill: 'rgba(144, 144, 144, .1)',
selectFill: '#2f80ed',
viewportFill: 'rgba(144, 144, 144, .1)',
}
id = uniqueId()
cvs: HTMLCanvasElement | null = null
pageBounds: (Box & { id: TLShapeId })[] = []
collaborators: TLInstancePresence[] = []
2023-04-25 11:01:25 +00:00
canvasScreenBounds = new Box()
canvasPageBounds = new Box()
2023-04-25 11:01:25 +00:00
contentPageBounds = new Box()
contentScreenBounds = new Box()
2023-04-25 11:01:25 +00:00
originPagePoint = new Vec()
originPageCenter = new Vec()
2023-04-25 11:01:25 +00:00
isInViewport = false
debug = false
setDpr(dpr: number) {
this.dpr = +dpr.toFixed(2)
}
updateContentScreenBounds = () => {
const { contentScreenBounds, contentPageBounds: content, canvasScreenBounds: canvas } = this
let { x, y, w, h } = contentScreenBounds
if (content.w > content.h) {
const sh = canvas.w / (content.w / content.h)
if (sh > canvas.h) {
x = (canvas.w - canvas.w * (canvas.h / sh)) / 2
y = 0
w = canvas.w * (canvas.h / sh)
h = canvas.h
} else {
x = 0
y = (canvas.h - sh) / 2
w = canvas.w
h = sh
}
} else if (content.w < content.h) {
const sw = canvas.h / (content.h / content.w)
x = (canvas.w - sw) / 2
y = 0
w = sw
h = canvas.h
} else {
x = canvas.h / 2
y = 0
w = canvas.h
h = canvas.h
}
contentScreenBounds.set(x, y, w, h)
}
/** Get the canvas's true bounds converted to page bounds. */
updateCanvasPageBounds = () => {
const { canvasPageBounds, canvasScreenBounds, contentPageBounds, contentScreenBounds } = this
canvasPageBounds.set(
0,
0,
contentPageBounds.width / (contentScreenBounds.width / canvasScreenBounds.width),
contentPageBounds.height / (contentScreenBounds.height / canvasScreenBounds.height)
)
canvasPageBounds.center = contentPageBounds.center
}
getScreenPoint = (x: number, y: number) => {
const { canvasScreenBounds } = this
const screenX = (x - canvasScreenBounds.minX) * this.dpr
const screenY = (y - canvasScreenBounds.minY) * this.dpr
return { x: screenX, y: screenY }
}
getPagePoint = (x: number, y: number) => {
const { contentPageBounds, contentScreenBounds, canvasPageBounds } = this
const { x: screenX, y: screenY } = this.getScreenPoint(x, y)
return new Vec(
canvasPageBounds.minX + (screenX * contentPageBounds.width) / contentScreenBounds.width,
canvasPageBounds.minY + (screenY * contentPageBounds.height) / contentScreenBounds.height,
1
)
2023-04-25 11:01:25 +00:00
}
minimapScreenPointToPagePoint = (
x: number,
y: number,
shiftKey = false,
clampToBounds = false
) => {
const { editor } = this
const viewportPageBounds = editor.getViewportPageBounds()
2023-04-25 11:01:25 +00:00
let { x: px, y: py } = this.getPagePoint(x, y)
if (clampToBounds) {
const shapesPageBounds = this.editor.getCurrentPageBounds()
2023-04-25 11:01:25 +00:00
const vpPageBounds = viewportPageBounds
const minX = (shapesPageBounds?.minX ?? 0) - vpPageBounds.width / 2
const maxX = (shapesPageBounds?.maxX ?? 0) + vpPageBounds.width / 2
const minY = (shapesPageBounds?.minY ?? 0) - vpPageBounds.height / 2
const maxY = (shapesPageBounds?.maxY ?? 0) + vpPageBounds.height / 2
const lx = Math.max(0, minX + vpPageBounds.width - px)
const rx = Math.max(0, -(maxX - vpPageBounds.width - px))
const ly = Math.max(0, minY + vpPageBounds.height - py)
const ry = Math.max(0, -(maxY - vpPageBounds.height - py))
const ql = Math.max(0, lx - rx)
const qr = Math.max(0, rx - lx)
const qt = Math.max(0, ly - ry)
const qb = Math.max(0, ry - ly)
if (ql && ql > qr) {
px += ql / 2
} else if (qr) {
px -= qr / 2
}
if (qt && qt > qb) {
py += qt / 2
} else if (qb) {
py -= qb / 2
}
px = clamp(px, minX, maxX)
py = clamp(py, minY, maxY)
}
if (shiftKey) {
const { originPagePoint } = this
const dx = Math.abs(px - originPagePoint.x)
const dy = Math.abs(py - originPagePoint.y)
if (dx > dy) {
py = originPagePoint.y
} else {
px = originPagePoint.x
}
}
return new Vec(px, py)
2023-04-25 11:01:25 +00:00
}
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
updateColors = () => {
const style = getComputedStyle(this.editor.getContainer())
this.colors = {
shapeFill: style.getPropertyValue('--color-text-3').trim(),
selectFill: style.getPropertyValue('--color-selected').trim(),
viewportFill: style.getPropertyValue('--color-muted-1').trim(),
}
}
render = () => {
2023-04-25 11:01:25 +00:00
const { cvs, pageBounds } = this
this.updateCanvasPageBounds()
const { editor, canvasScreenBounds, canvasPageBounds, contentPageBounds, contentScreenBounds } =
2023-04-25 11:01:25 +00:00
this
const { width: cw, height: ch } = canvasScreenBounds
const selectedShapeIds = new Set(editor.getSelectedShapeIds())
const viewportPageBounds = editor.getViewportPageBounds()
2023-04-25 11:01:25 +00:00
if (!cvs || !pageBounds) {
return
}
const ctx = cvs.getContext('2d')!
if (!ctx) {
throw new Error('Minimap (shapes): Could not get context')
}
ctx.resetTransform()
ctx.globalAlpha = 1
ctx.clearRect(0, 0, cw, ch)
// Transform canvas
const sx = contentScreenBounds.width / contentPageBounds.width
const sy = contentScreenBounds.height / contentPageBounds.height
ctx.translate((cw - contentScreenBounds.width) / 2, (ch - contentScreenBounds.height) / 2)
ctx.scale(sx, sy)
ctx.translate(-contentPageBounds.minX, -contentPageBounds.minY)
// shapes
const shapesPath = new Path2D()
const selectedPath = new Path2D()
const { shapeFill, selectFill, viewportFill } = this.colors
// When there are many shapes, don't draw rounded rectangles;
// consider using the shape's size instead.
let pb: Box & { id: TLShapeId }
2023-04-25 11:01:25 +00:00
for (let i = 0, n = pageBounds.length; i < n; i++) {
pb = pageBounds[i]
;(selectedShapeIds.has(pb.id) ? selectedPath : shapesPath).rect(
2023-04-25 11:01:25 +00:00
pb.minX,
pb.minY,
pb.width,
pb.height
2023-04-25 11:01:25 +00:00
)
}
2023-04-25 11:01:25 +00:00
// Fill the shapes paths
ctx.fillStyle = shapeFill
ctx.fill(shapesPath)
// Fill the selected paths
ctx.fillStyle = selectFill
ctx.fill(selectedPath)
if (this.debug) {
// Page bounds
const commonBounds = Box.Common(pageBounds)
2023-04-25 11:01:25 +00:00
const { minX, minY, width, height } = commonBounds
ctx.strokeStyle = 'green'
ctx.lineWidth = 2 / sx
ctx.strokeRect(minX + 1 / sx, minY + 1 / sy, width - 2 / sx, height - 2 / sy)
}
// Brush
{
const { brush } = editor.getInstanceState()
2023-04-25 11:01:25 +00:00
if (brush) {
const { x, y, w, h } = brush
ctx.beginPath()
MinimapManager.sharpRect(ctx, x, y, w, h)
ctx.closePath()
ctx.fillStyle = viewportFill
ctx.fill()
}
}
// Viewport
{
const { minX, minY, width, height } = viewportPageBounds
ctx.beginPath()
const rx = 12 / sx
const ry = 12 / sx
MinimapManager.roundedRect(
ctx,
minX,
minY,
width,
height,
Math.min(width / 4, rx),
Math.min(height / 4, ry)
)
ctx.closePath()
ctx.fillStyle = viewportFill
ctx.fill()
if (this.debug) {
ctx.strokeStyle = 'orange'
ctx.strokeRect(minX + 1 / sx, minY + 1 / sy, width - 2 / sx, height - 2 / sy)
}
}
// Show collaborator cursors
// Padding for canvas bounds edges
const px = 2.5 / sx
const py = 2.5 / sy
const currentPageId = editor.getCurrentPageId()
2023-04-25 11:01:25 +00:00
let collaborator: TLInstancePresence
2023-04-25 11:01:25 +00:00
for (let i = 0; i < this.collaborators.length; i++) {
collaborator = this.collaborators[i]
if (collaborator.currentPageId !== currentPageId) {
2023-04-25 11:01:25 +00:00
continue
}
ctx.beginPath()
ctx.ellipse(
clamp(collaborator.cursor.x, canvasPageBounds.minX + px, canvasPageBounds.maxX - px),
clamp(collaborator.cursor.y, canvasPageBounds.minY + py, canvasPageBounds.maxY - py),
5 / sx,
5 / sy,
0,
0,
PI2
)
ctx.fillStyle = collaborator.color
ctx.fill()
}
if (this.debug) {
ctx.lineWidth = 2 / sx
{
// Minimap Bounds
const { minX, minY, width, height } = contentPageBounds
ctx.strokeStyle = 'red'
ctx.strokeRect(minX + 1 / sx, minY + 1 / sy, width - 2 / sx, height - 2 / sy)
}
{
// Canvas Bounds
const { minX, minY, width, height } = canvasPageBounds
ctx.strokeStyle = 'blue'
ctx.strokeRect(minX + 1 / sx, minY + 1 / sy, width - 2 / sx, height - 2 / sy)
}
}
}
2023-04-25 11:01:25 +00:00
static roundedRect(
ctx: CanvasRenderingContext2D | Path2D,
x: number,
y: number,
width: number,
height: number,
rx: number,
ry: number
) {
if (rx < 1 && ry < 1) {
ctx.rect(x, y, width, height)
return
}
ctx.moveTo(x + rx, y)
ctx.lineTo(x + width - rx, y)
ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
ctx.lineTo(x + width, y + height - ry)
ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
ctx.lineTo(x + rx, y + height)
ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
ctx.lineTo(x, y + ry)
ctx.quadraticCurveTo(x, y, x + rx, y)
}
static sharpRect(
ctx: CanvasRenderingContext2D | Path2D,
x: number,
y: number,
width: number,
height: number,
_rx?: number,
_ry?: number
) {
ctx.rect(x, y, width, height)
}
}