/
DefaultPageMenu.tsx
420 lines (378 loc) · 12.8 KB
/
DefaultPageMenu.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import {
MAX_PAGES,
PageRecordType,
TLPageId,
releasePointerCapture,
setPointerCapture,
useEditor,
useValue,
} from '@tldraw/editor'
import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { PORTRAIT_BREAKPOINT } from '../../constants'
import { useBreakpoint } from '../../context/breakpoints'
import { useMenuIsOpen } from '../../hooks/useMenuIsOpen'
import { useReadonly } from '../../hooks/useReadonly'
import { useTranslation } from '../../hooks/useTranslation/useTranslation'
import { TldrawUiButton } from '../primitives/Button/TldrawUiButton'
import { TldrawUiButtonCheck } from '../primitives/Button/TldrawUiButtonCheck'
import { TldrawUiButtonIcon } from '../primitives/Button/TldrawUiButtonIcon'
import { TldrawUiButtonLabel } from '../primitives/Button/TldrawUiButtonLabel'
import {
TldrawUiPopover,
TldrawUiPopoverContent,
TldrawUiPopoverTrigger,
} from '../primitives/TldrawUiPopover'
import { PageItemInput } from './PageItemInput'
import { PageItemSubmenu } from './PageItemSubmenu'
import { onMovePage } from './edit-pages-shared'
/** @public */
export const DefaultPageMenu = memo(function DefaultPageMenu() {
const editor = useEditor()
const msg = useTranslation()
const breakpoint = useBreakpoint()
const handleOpenChange = useCallback(() => setIsEditing(false), [])
const [isOpen, onOpenChange] = useMenuIsOpen('page-menu', handleOpenChange)
const ITEM_HEIGHT = 36
const rSortableContainer = useRef<HTMLDivElement>(null)
const pages = useValue('pages', () => editor.getPages(), [editor])
const currentPage = useValue('currentPage', () => editor.getCurrentPage(), [editor])
const currentPageId = useValue('currentPageId', () => editor.getCurrentPageId(), [editor])
// When in readonly mode, we don't allow a user to edit the pages
const isReadonlyMode = useReadonly()
// If the user has reached the max page count, we disable the "add page" button
const maxPageCountReached = useValue(
'maxPageCountReached',
() => editor.getPages().length >= MAX_PAGES,
[editor]
)
const isCoarsePointer = useValue(
'isCoarsePointer',
() => editor.getInstanceState().isCoarsePointer,
[editor]
)
// The component has an "editing state" that may be toggled to expose additional controls
const [isEditing, setIsEditing] = useState(false)
const toggleEditing = useCallback(() => {
if (isReadonlyMode) return
setIsEditing((s) => !s)
}, [isReadonlyMode])
const rMutables = useRef({
isPointing: false,
status: 'idle' as 'idle' | 'pointing' | 'dragging',
pointing: null as { id: string; index: number } | null,
startY: 0,
startIndex: 0,
dragIndex: 0,
})
const [sortablePositionItems, setSortablePositionItems] = useState(
Object.fromEntries(
pages.map((page, i) => [page.id, { y: i * ITEM_HEIGHT, offsetY: 0, isSelected: false }])
)
)
// Update the sortable position items when the pages change
useLayoutEffect(() => {
setSortablePositionItems(
Object.fromEntries(
pages.map((page, i) => [page.id, { y: i * ITEM_HEIGHT, offsetY: 0, isSelected: false }])
)
)
}, [ITEM_HEIGHT, pages])
// Scroll the current page into view when the menu opens / when current page changes
useEffect(() => {
if (!isOpen) return
requestAnimationFrame(() => {
const elm = document.querySelector(
`[data-testid="page-menu-item-${currentPageId}"]`
) as HTMLDivElement
if (elm) {
const container = rSortableContainer.current
if (!container) return
// Scroll into view is slightly borked on iOS Safari
// if top of less than top cuttoff, scroll into view at top
const elmTopPosition = elm.offsetTop
const containerScrollTopPosition = container.scrollTop
if (elmTopPosition < containerScrollTopPosition) {
container.scrollTo({ top: elmTopPosition })
}
// if bottom position is greater than bottom cutoff, scroll into view at bottom
const elmBottomPosition = elmTopPosition + ITEM_HEIGHT
const containerScrollBottomPosition = container.scrollTop + container.offsetHeight
if (elmBottomPosition > containerScrollBottomPosition) {
container.scrollTo({ top: elmBottomPosition - container.offsetHeight })
}
}
})
}, [ITEM_HEIGHT, currentPageId, isOpen])
const handlePointerDown = useCallback(
(e: React.PointerEvent<HTMLButtonElement>) => {
const { clientY, currentTarget } = e
const {
dataset: { id, index },
} = currentTarget
if (!id || !index) return
const mut = rMutables.current
setPointerCapture(e.currentTarget, e)
mut.status = 'pointing'
mut.pointing = { id, index: +index! }
const current = sortablePositionItems[id]
const dragY = current.y
mut.startY = clientY
mut.startIndex = Math.max(0, Math.min(Math.round(dragY / ITEM_HEIGHT), pages.length - 1))
},
[ITEM_HEIGHT, pages.length, sortablePositionItems]
)
const handlePointerMove = useCallback(
(e: React.PointerEvent<HTMLButtonElement>) => {
const mut = rMutables.current
if (mut.status === 'pointing') {
const { clientY } = e
const offset = clientY - mut.startY
if (Math.abs(offset) > 5) {
mut.status = 'dragging'
}
}
if (mut.status === 'dragging') {
const { clientY } = e
const offsetY = clientY - mut.startY
const current = sortablePositionItems[mut.pointing!.id]
const { startIndex, pointing } = mut
const dragY = current.y + offsetY
const dragIndex = Math.max(0, Math.min(Math.round(dragY / ITEM_HEIGHT), pages.length - 1))
const next = { ...sortablePositionItems }
next[pointing!.id] = {
y: current.y,
offsetY,
isSelected: true,
}
if (dragIndex !== mut.dragIndex) {
mut.dragIndex = dragIndex
for (let i = 0; i < pages.length; i++) {
const item = pages[i]
if (item.id === mut.pointing!.id) {
continue
}
let { y } = next[item.id]
if (dragIndex === startIndex) {
y = i * ITEM_HEIGHT
} else if (dragIndex < startIndex) {
if (dragIndex <= i && i < startIndex) {
y = (i + 1) * ITEM_HEIGHT
} else {
y = i * ITEM_HEIGHT
}
} else if (dragIndex > startIndex) {
if (dragIndex >= i && i > startIndex) {
y = (i - 1) * ITEM_HEIGHT
} else {
y = i * ITEM_HEIGHT
}
}
if (y !== next[item.id].y) {
next[item.id] = { y, offsetY: 0, isSelected: true }
}
}
}
setSortablePositionItems(next)
}
},
[ITEM_HEIGHT, pages, sortablePositionItems]
)
const handlePointerUp = useCallback(
(e: React.PointerEvent<HTMLButtonElement>) => {
const mut = rMutables.current
if (mut.status === 'dragging') {
const { id, index } = mut.pointing!
onMovePage(editor, id as TLPageId, index, mut.dragIndex)
}
releasePointerCapture(e.currentTarget, e)
mut.status = 'idle'
},
[editor]
)
const handleKeyDown = useCallback(
(e: React.KeyboardEvent<HTMLButtonElement>) => {
const mut = rMutables.current
// bail on escape
if (e.key === 'Escape') {
if (mut.status === 'dragging') {
setSortablePositionItems(
Object.fromEntries(
pages.map((page, i) => [
page.id,
{ y: i * ITEM_HEIGHT, offsetY: 0, isSelected: false },
])
)
)
}
mut.status = 'idle'
}
},
[ITEM_HEIGHT, pages]
)
const handleCreatePageClick = useCallback(() => {
if (isReadonlyMode) return
editor.batch(() => {
editor.mark('creating page')
const newPageId = PageRecordType.createId()
editor.createPage({ name: msg('page-menu.new-page-initial-name'), id: newPageId })
editor.setCurrentPage(newPageId)
setIsEditing(true)
})
}, [editor, msg, isReadonlyMode])
return (
<TldrawUiPopover id="pages" onOpenChange={onOpenChange} open={isOpen}>
<TldrawUiPopoverTrigger data-testid="main.page-menu">
<TldrawUiButton
type="menu"
title={currentPage.name}
data-testid="page-menu.button"
className="tlui-page-menu__trigger"
>
<div className="tlui-page-menu__name">{currentPage.name}</div>
<TldrawUiButtonIcon icon="chevron-down" small />
</TldrawUiButton>
</TldrawUiPopoverTrigger>
<TldrawUiPopoverContent side="bottom" align="start" sideOffset={6}>
<div className="tlui-page-menu__wrapper">
<div className="tlui-page-menu__header">
<div className="tlui-page-menu__header__title">{msg('page-menu.title')}</div>
{!isReadonlyMode && (
<div className="tlui-buttons__horizontal">
<TldrawUiButton
type="icon"
data-testid="page-menu.edit"
title={msg(isEditing ? 'page-menu.edit-done' : 'page-menu.edit-start')}
onClick={toggleEditing}
>
<TldrawUiButtonIcon icon={isEditing ? 'check' : 'edit'} />
</TldrawUiButton>
<TldrawUiButton
type="icon"
data-testid="page-menu.create"
title={msg(
maxPageCountReached
? 'page-menu.max-page-count-reached'
: 'page-menu.create-new-page'
)}
disabled={maxPageCountReached}
onClick={handleCreatePageClick}
>
<TldrawUiButtonIcon icon="plus" />
</TldrawUiButton>
</div>
)}
</div>
<div
data-testid="page-menu.list"
className="tlui-page-menu__list tlui-menu__group"
style={{ height: ITEM_HEIGHT * pages.length + 4 }}
ref={rSortableContainer}
>
{pages.map((page, index) => {
const position = sortablePositionItems[page.id] ?? {
position: index * 40,
offsetY: 0,
}
return isEditing ? (
<div
key={page.id + '_editing'}
data-testid="page-menu.item"
className="tlui-page_menu__item__sortable"
style={{
zIndex: page.id === currentPage.id ? 888 : index,
transform: `translate(0px, ${position.y + position.offsetY}px)`,
}}
>
<TldrawUiButton
type="icon"
tabIndex={-1}
className="tlui-page_menu__item__sortable__handle"
onPointerDown={handlePointerDown}
onPointerUp={handlePointerUp}
onPointerMove={handlePointerMove}
onKeyDown={handleKeyDown}
data-id={page.id}
data-index={index}
>
<TldrawUiButtonIcon icon="drag-handle-dots" />
</TldrawUiButton>
{breakpoint < PORTRAIT_BREAKPOINT.TABLET_SM && isCoarsePointer ? (
// sigh, this is a workaround for iOS Safari
// because the device and the radix popover seem
// to be fighting over scroll position. Nothing
// else seems to work!
<TldrawUiButton
type="normal"
className="tlui-page-menu__item__button"
onClick={() => {
const name = window.prompt('Rename page', page.name)
if (name && name !== page.name) {
editor.renamePage(page.id, name)
}
}}
onDoubleClick={toggleEditing}
>
<TldrawUiButtonCheck checked={page.id === currentPage.id} />
<TldrawUiButtonLabel>{page.name}</TldrawUiButtonLabel>
</TldrawUiButton>
) : (
<div
className="tlui-page_menu__item__sortable__title"
style={{ height: ITEM_HEIGHT }}
>
<PageItemInput
id={page.id}
name={page.name}
isCurrentPage={page.id === currentPage.id}
/>
</div>
)}
{!isReadonlyMode && (
<div className="tlui-page_menu__item__submenu" data-isediting={isEditing}>
<PageItemSubmenu index={index} item={page} listSize={pages.length} />
</div>
)}
</div>
) : (
<div key={page.id} data-testid="page-menu.item" className="tlui-page-menu__item">
<TldrawUiButton
type="normal"
className="tlui-page-menu__item__button"
onClick={() => editor.setCurrentPage(page.id)}
onDoubleClick={toggleEditing}
title={msg('page-menu.go-to-page')}
>
<TldrawUiButtonCheck checked={page.id === currentPage.id} />
<TldrawUiButtonLabel>{page.name}</TldrawUiButtonLabel>
</TldrawUiButton>
{!isReadonlyMode && (
<div className="tlui-page_menu__item__submenu">
<PageItemSubmenu
index={index}
item={page}
listSize={pages.length}
onRename={() => {
if (editor.environment.isIos) {
const name = window.prompt('Rename page', page.name)
if (name && name !== page.name) {
editor.renamePage(page.id, name)
}
} else {
editor.batch(() => {
setIsEditing(true)
editor.setCurrentPage(page.id)
})
}
}}
/>
</div>
)}
</div>
)
})}
</div>
</div>
</TldrawUiPopoverContent>
</TldrawUiPopover>
)
})