Improved duplication (#2480)

Improves duplication. It will now remember the offset and shapes of your
`alt + drag` duplication and use that if you use the duplicate action
immediately after this.


![duplicate](https://github.com/tldraw/tldraw/assets/2523721/6fbfd455-d179-4eae-8aba-399b0781f633)

Fixes https://github.com/tldraw/tldraw/issues/2264

### Change Type

- [ ] `patch` — Bug fix
- [x] `minor` — New feature
- [ ] `major` — Breaking change
- [ ] `dependencies` — Changes to package dependencies[^1]
- [ ] `documentation` — Changes to the documentation only[^2]
- [ ] `tests` — Changes to any test code only[^2]
- [ ] `internal` — Any other changes that don't affect the published
package[^2]
- [ ] I don't know

[^1]: publishes a `patch` release, for devDependencies use `internal`
[^2]: will not publish a new version

### Test Plan

1. Add a step-by-step description of how to test your PR here.
2.

- [ ] Unit Tests
- [ ] End to end tests

### Release Notes

- Add a brief release note for your PR here.

---------

Co-authored-by: Taha <98838967+Taha-Hassan-Git@users.noreply.github.com>
Co-authored-by: David Sheldrick <d.j.sheldrick@gmail.com>
Co-authored-by: Steve Ruiz <steveruizok@gmail.com>
This commit is contained in:
Mitja Bezenšek 2024-01-26 15:54:52 +01:00 committed by GitHub
parent c3ae981c2d
commit 3f453569f6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 271 additions and 13 deletions

View file

@ -1086,7 +1086,11 @@ export class SelectTool extends StateNode {
// (undocumented)
static initial: string;
// (undocumented)
onEnter: () => void;
// (undocumented)
onExit: () => void;
// (undocumented)
reactor: (() => void) | undefined;
}
// @public (undocumented)

View file

@ -12809,6 +12809,36 @@
"isProtected": false,
"isAbstract": false
},
{
"kind": "Property",
"canonicalReference": "@tldraw/tldraw!SelectTool#onEnter:member",
"docComment": "",
"excerptTokens": [
{
"kind": "Content",
"text": "onEnter: "
},
{
"kind": "Content",
"text": "() => void"
},
{
"kind": "Content",
"text": ";"
}
],
"isReadonly": false,
"isOptional": false,
"releaseTag": "Public",
"name": "onEnter",
"propertyTypeTokenRange": {
"startIndex": 1,
"endIndex": 2
},
"isStatic": false,
"isProtected": false,
"isAbstract": false
},
{
"kind": "Property",
"canonicalReference": "@tldraw/tldraw!SelectTool#onExit:member",
@ -12838,6 +12868,36 @@
"isStatic": false,
"isProtected": false,
"isAbstract": false
},
{
"kind": "Property",
"canonicalReference": "@tldraw/tldraw!SelectTool#reactor:member",
"docComment": "",
"excerptTokens": [
{
"kind": "Content",
"text": "reactor: "
},
{
"kind": "Content",
"text": "(() => void) | undefined"
},
{
"kind": "Content",
"text": ";"
}
],
"isReadonly": false,
"isOptional": false,
"releaseTag": "Public",
"name": "reactor",
"propertyTypeTokenRange": {
"startIndex": 1,
"endIndex": 2
},
"isStatic": false,
"isProtected": false,
"isAbstract": false
}
],
"extendsTokenRange": {

View file

@ -1,4 +1,4 @@
import { StateNode } from '@tldraw/editor'
import { StateNode, react } from '@tldraw/editor'
import { Brushing } from './childStates/Brushing'
import { Crop } from './childStates/Crop/Crop'
import { Cropping } from './childStates/Cropping'
@ -21,6 +21,8 @@ import { Translating } from './childStates/Translating'
export class SelectTool extends StateNode {
static override id = 'select'
static override initial = 'idle'
reactor: undefined | (() => void) = undefined
static override children = () => [
Crop,
Cropping,
@ -41,7 +43,39 @@ export class SelectTool extends StateNode {
DraggingHandle,
]
// We want to clean up the duplicate props when the selection changes
private cleanUpDuplicateProps = () => {
const selectedShapeIds = this.editor.getSelectedShapeIds()
const instance = this.editor.getInstanceState()
if (!instance.duplicateProps) return
const duplicatedShapes = new Set(instance.duplicateProps.shapeIds)
if (
selectedShapeIds.length === duplicatedShapes.size &&
selectedShapeIds.every((shapeId) => duplicatedShapes.has(shapeId))
) {
return
}
this.editor.updateInstanceState({
duplicateProps: null,
})
}
override onEnter = () => {
this.reactor = react('clean duplicate props', () => {
try {
this.cleanUpDuplicateProps()
} catch (e) {
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'test') {
// ignore errors at test time
} else {
console.error(e)
}
}
})
}
override onExit = () => {
this.reactor?.()
if (this.editor.getCurrentPageState().editingShapeId) {
this.editor.setEditingShape(null)
}

View file

@ -213,6 +213,19 @@ export class Translating extends StateNode {
protected handleEnd() {
const { movingShapes } = this.snapshot
if (this.isCloning) {
const currentAveragePagePoint = Vec.Average(
movingShapes.map((s) => this.editor.getShapePageTransform(s.id)!.point())
)
const offset = Vec.Sub(currentAveragePagePoint, this.selectionSnapshot.averagePagePoint)
this.editor.updateInstanceState({
duplicateProps: {
shapeIds: movingShapes.map((s) => s.id),
offset: { x: offset.x, y: offset.y },
},
})
}
const changes: TLShapePartial[] = []
movingShapes.forEach((shape) => {

View file

@ -406,19 +406,39 @@ export function ActionsProvider({ overrides, children }: ActionsProviderProps) {
if (mustGoBackToSelectToolFirst()) return
trackEvent('duplicate-shapes', { source })
const ids = editor.getSelectedShapeIds()
const commonBounds = Box.Common(compact(ids.map((id) => editor.getShapePageBounds(id))))
const offset = editor.getInstanceState().canMoveCamera
? {
x: commonBounds.width + 10,
y: 0,
}
: {
x: 16 / editor.getZoomLevel(),
y: 16 / editor.getZoomLevel(),
}
const instanceState = editor.getInstanceState()
let ids: TLShapeId[]
let offset: { x: number; y: number }
if (instanceState.duplicateProps) {
ids = instanceState.duplicateProps.shapeIds
offset = instanceState.duplicateProps.offset
} else {
ids = editor.getSelectedShapeIds()
const commonBounds = Box.Common(compact(ids.map((id) => editor.getShapePageBounds(id))))
offset = instanceState.canMoveCamera
? {
x: commonBounds.width + 10,
y: 0,
}
: {
x: 16 / editor.getZoomLevel(),
y: 16 / editor.getZoomLevel(),
}
}
editor.mark('duplicate shapes')
editor.duplicateShapes(ids, offset)
if (instanceState.duplicateProps) {
// If we are using duplicate props then we update the shape ids to the
// ids of the newly created shapes to keep the duplication going
editor.updateInstanceState({
duplicateProps: {
...instanceState.duplicateProps,
shapeIds: editor.getSelectedShapeIds(),
},
})
}
},
},
{

View file

@ -215,3 +215,45 @@ describe('When duplicating shapes that include arrows', () => {
// expect(editor.selectionRotatedBounds).toCloselyMatchObject(boundsBefore)
})
})
describe('When duplicating shapes after cloning', () => {
beforeEach(() => {
editor
.selectAll()
.deleteShapes(editor.getSelectedShapeIds())
.createShape({ id: ids.box1, type: 'geo', x: 0, y: 0, props: { w: 100, h: 100 } })
})
it('preserves the cloning properties (offset and shapes)', () => {
// Clone the shape by alt dragging it to a new location
expect(editor.getCurrentPageShapeIds().size).toBe(1)
editor.keyDown('Alt')
editor.select(ids.box1).pointerDown(50, 50, ids.box1).pointerMove(30, 40).pointerUp(30, 40) // [-20, -10]
editor.keyUp('Alt')
const shape = editor.getSelectedShapes()[0]
expect(editor.getCurrentPageShapeIds().size).toBe(2)
expect(shape.id).not.toBe(ids.box1)
expect(shape.x).toBe(-20)
expect(shape.y).toBe(-10)
// Make sure the duplicate props are set
let instance = editor.getInstanceState()
let duplicateProps = instance?.duplicateProps
if (!duplicateProps) throw new Error('duplicateProps should be set')
expect(duplicateProps.shapeIds).toEqual([shape.id])
expect(duplicateProps.offset).toEqual({ x: -20, y: -10 })
// Make sure duplication with these props works (we can't invoke the duplicate action directly since it's a hook)
editor.duplicateShapes(duplicateProps.shapeIds, duplicateProps.offset)
const newShapes = editor.getSelectedShapes()
expect(newShapes.length).toBe(1)
expect(newShapes[0].x).toBe(-40)
expect(newShapes[0].y).toBe(-20)
// Make sure the duplicate props are cleared when we select a different shape
editor.select(ids.box1)
instance = editor.getInstanceState()
duplicateProps = instance?.duplicateProps
expect(duplicateProps).toBe(null)
})
})

View file

@ -1015,6 +1015,14 @@ export interface TLInstance extends BaseRecord<'instance', TLInstanceId> {
// (undocumented)
devicePixelRatio: number;
// (undocumented)
duplicateProps: {
shapeIds: TLShapeId[];
offset: {
x: number;
y: number;
};
} | null;
// (undocumented)
exportBackground: boolean;
// (undocumented)
followingUserId: null | string;

View file

@ -6681,6 +6681,42 @@
"endIndex": 2
}
},
{
"kind": "PropertySignature",
"canonicalReference": "@tldraw/tlschema!TLInstance#duplicateProps:member",
"docComment": "",
"excerptTokens": [
{
"kind": "Content",
"text": "duplicateProps: "
},
{
"kind": "Content",
"text": "{\n shapeIds: "
},
{
"kind": "Reference",
"text": "TLShapeId",
"canonicalReference": "@tldraw/tlschema!TLShapeId:type"
},
{
"kind": "Content",
"text": "[];\n offset: {\n x: number;\n y: number;\n };\n } | null"
},
{
"kind": "Content",
"text": ";"
}
],
"isReadonly": false,
"isOptional": false,
"releaseTag": "Public",
"name": "duplicateProps",
"propertyTypeTokenRange": {
"startIndex": 1,
"endIndex": 4
}
},
{
"kind": "PropertySignature",
"canonicalReference": "@tldraw/tlschema!TLInstance#exportBackground:member",

View file

@ -1834,6 +1834,16 @@ describe('Make urls valid for all the assets', () => {
}
})
describe('Add duplicate props to instance', () => {
const { up, down } = instanceMigrations.migrators[instanceVersions.AddDuplicateProps]
it('up works as expected', () => {
expect(up({})).toEqual({ duplicateProps: null })
})
it('down works as expected', () => {
expect(down({ duplicateProps: null })).toEqual({})
})
})
/* --- PUT YOUR MIGRATIONS TESTS ABOVE HERE --- */
for (const migrator of allMigrators) {

View file

@ -8,6 +8,7 @@ import { opacityValidator, TLOpacityType } from '../misc/TLOpacity'
import { scribbleValidator, TLScribble } from '../misc/TLScribble'
import { StyleProp } from '../styles/StyleProp'
import { pageIdValidator, TLPageId } from './TLPage'
import { TLShapeId } from './TLShape'
/**
* TLInstance
@ -55,6 +56,13 @@ export interface TLInstance extends BaseRecord<'instance', TLInstanceId> {
isChangingStyle: boolean
isReadonly: boolean
meta: JsonObject
duplicateProps: {
shapeIds: TLShapeId[]
offset: {
x: number
y: number
}
} | null
}
/** @public */
@ -102,6 +110,13 @@ export function createInstanceRecordType(stylesById: Map<string, StyleProp<unkno
isChangingStyle: T.boolean,
isReadonly: T.boolean,
meta: T.jsonValue as T.ObjectValidator<JsonObject>,
duplicateProps: T.object({
shapeIds: T.arrayOf(idValidator<TLShapeId>('shape')),
offset: T.object({
x: T.number,
y: T.number,
}),
}).nullable(),
})
)
@ -141,6 +156,7 @@ export function createInstanceRecordType(stylesById: Map<string, StyleProp<unkno
isChangingStyle: false,
isReadonly: false,
meta: {},
duplicateProps: null,
})
)
}
@ -170,11 +186,12 @@ export const instanceVersions = {
AddHoveringCanvas: 21,
AddScribbles: 22,
AddInset: 23,
AddDuplicateProps: 24,
} as const
/** @public */
export const instanceMigrations = defineMigrations({
currentVersion: instanceVersions.AddInset,
currentVersion: instanceVersions.AddDuplicateProps,
migrators: {
[instanceVersions.AddTransparentExportBgs]: {
up: (instance: TLInstance) => {
@ -508,6 +525,19 @@ export const instanceMigrations = defineMigrations({
}
},
},
[instanceVersions.AddDuplicateProps]: {
up: (record) => {
return {
...record,
duplicateProps: null,
}
},
down: ({ duplicateProps: _, ...record }) => {
return {
...record,
}
},
},
},
})

View file

@ -582,6 +582,7 @@ export class TLSyncClient<R extends UnknownRecord, S extends Store<R> = Store<R>
this.lastServerClock = diffs.at(-1)?.serverClock ?? this.lastServerClock
} catch (e) {
console.error(e)
this.store.ensureStoreIsUsable()
this.resetConnection()
}
}