/
LogseqPortalShape.tsx
988 lines (910 loc) · 29.1 KB
/
LogseqPortalShape.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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
delay,
TLBoxShape,
TLBoxShapeProps,
TLResetBoundsInfo,
TLResizeInfo,
validUUID,
getComputedColor,
} from '@tldraw/core'
import { Virtuoso } from 'react-virtuoso'
import { HTMLContainer, TLComponentProps, useApp } from '@tldraw/react'
import { useDebouncedValue } from '@tldraw/react'
import Vec from '@tldraw/vec'
import { action, computed, makeObservable } from 'mobx'
import { observer } from 'mobx-react-lite'
import * as React from 'react'
import type { SizeLevel, Shape } from '.'
import { TablerIcon } from '../../components/icons'
import { TextInput } from '../../components/inputs/TextInput'
import { useCameraMovingRef } from '../../hooks/useCameraMoving'
import { LogseqContext, type SearchResult } from '../logseq-context'
import { BindingIndicator } from './BindingIndicator'
import { CustomStyleProps, withClampedStyles } from './style-props'
const HEADER_HEIGHT = 40
const AUTO_RESIZE_THRESHOLD = 1
export interface LogseqPortalShapeProps extends TLBoxShapeProps, CustomStyleProps {
type: 'logseq-portal'
pageId: string // page name or UUID
blockType?: 'P' | 'B'
collapsed?: boolean
compact?: boolean
borderRadius?: number
collapsedHeight?: number
scaleLevel?: SizeLevel
}
interface LogseqQuickSearchProps {
onChange: (id: string) => void
}
const levelToScale = {
xs: 0.5,
sm: 0.8,
md: 1,
lg: 1.5,
xl: 2,
xxl: 3,
}
const LogseqTypeTag = ({
type,
active,
}: {
type: 'B' | 'P' | 'BA' | 'PA' | 'WP' | 'BS' | 'PS'
active?: boolean
}) => {
const nameMapping = {
B: 'block',
P: 'page',
WP: 'whiteboard',
BA: 'new-block',
PA: 'new-page',
BS: 'block-search',
PS: 'page-search',
}
return (
<span className="tl-type-tag" data-active={active}>
<i className={`tie tie-${nameMapping[type]}`} />
</span>
)
}
const LogseqPortalShapeHeader = observer(
({
type,
fill,
opacity,
children,
}: {
type: 'P' | 'B'
fill: string
opacity: number
children: React.ReactNode
}) => {
const bgColor =
fill !== 'var(--ls-secondary-background-color)'
? getComputedColor(fill, 'background')
: 'var(--ls-tertiary-background-color)'
return (
<div
className={`tl-logseq-portal-header tl-logseq-portal-header-${
type === 'P' ? 'page' : 'block'
}`}
>
<div
className="absolute inset-0 tl-logseq-portal-header-bg"
style={{
opacity,
background: type === 'P' ? bgColor : `linear-gradient(0deg, transparent, ${bgColor}`,
}}
></div>
<div className="relative">{children}</div>
</div>
)
}
)
function escapeRegExp(text: string) {
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
}
const highlightedJSX = (input: string, keyword: string) => {
return (
<span>
{input
.split(new RegExp(`(${escapeRegExp(keyword)})`, 'gi'))
.map((part, index) => {
if (index % 2 === 1) {
return <mark className="tl-highlighted">{part}</mark>
}
return part
})
.map((frag, idx) => (
<React.Fragment key={idx}>{frag}</React.Fragment>
))}
</span>
)
}
const useSearch = (q: string, searchFilter: 'B' | 'P' | null) => {
const { handlers } = React.useContext(LogseqContext)
const [results, setResults] = React.useState<SearchResult | null>(null)
const dq = useDebouncedValue(q, 200)
React.useEffect(() => {
let canceled = false
if (dq.length > 0) {
const filter = { 'pages?': true, 'blocks?': true, 'files?': false }
if (searchFilter === 'B') {
filter['pages?'] = false
} else if (searchFilter === 'P') {
filter['blocks?'] = false
}
handlers.search(dq, filter).then(_results => {
if (!canceled) {
setResults(_results)
}
})
} else {
setResults(null)
}
return () => {
canceled = true
}
}, [dq, handlers?.search])
return results
}
const CircleButton = ({
active,
style,
icon,
otherIcon,
onClick,
}: {
active?: boolean
style?: React.CSSProperties
icon: string
otherIcon?: string
onClick: () => void
}) => {
const [recentlyChanged, setRecentlyChanged] = React.useState(false)
React.useEffect(() => {
setRecentlyChanged(true)
const timer = setTimeout(() => {
setRecentlyChanged(false)
}, 500)
return () => clearTimeout(timer)
}, [active])
return (
<button
data-active={active}
data-recently-changed={recentlyChanged}
style={style}
className="tl-circle-button"
onMouseDown={onClick}
>
<div className="tl-circle-button-icons-wrapper" data-icons-count={otherIcon ? 2 : 1}>
{otherIcon && <TablerIcon name={otherIcon} />}
<TablerIcon name={icon} />
</div>
</button>
)
}
export class LogseqPortalShape extends TLBoxShape<LogseqPortalShapeProps> {
static id = 'logseq-portal'
static defaultSearchQuery = ''
static defaultSearchFilter: 'B' | 'P' | null = null
static defaultProps: LogseqPortalShapeProps = {
id: 'logseq-portal',
type: 'logseq-portal',
parentId: 'page',
point: [0, 0],
size: [400, 50],
// collapsedHeight is the height before collapsing
collapsedHeight: 0,
stroke: '',
fill: '',
noFill: false,
borderRadius: 8,
strokeWidth: 2,
strokeType: 'line',
opacity: 1,
pageId: '',
collapsed: false,
compact: false,
scaleLevel: 'md',
isAutoResizing: true,
}
hideRotateHandle = true
canChangeAspectRatio = true
canFlip = true
canEdit = true
persist: ((replace?: boolean) => void) | null = null
// For quick add shapes, we want to calculate the page height dynamically
initialHeightCalculated = true
getInnerHeight: (() => number) | null = null // will be overridden in the hook
constructor(props = {} as Partial<LogseqPortalShapeProps>) {
super(props)
makeObservable(this)
if (props.collapsed) {
Object.assign(this.canResize, [true, false])
}
if (props.size?.[1] === 0) {
this.initialHeightCalculated = false
}
}
static isPageOrBlock(id: string): 'P' | 'B' | false {
const blockRefEg = '((62af02d0-0443-42e8-a284-946c162b0f89))'
if (id) {
return /^\(\(.*\)\)$/.test(id) && id.length === blockRefEg.length ? 'B' : 'P'
}
return false
}
@computed get collapsed() {
return this.props.blockType === 'B' ? this.props.compact : this.props.collapsed
}
@action setCollapsed = async (collapsed: boolean) => {
if (this.props.blockType === 'B') {
this.update({ compact: collapsed })
this.canResize[1] = !collapsed
if (!collapsed) {
// this will also persist the state, so we can skip persist call
await delay()
this.onResetBounds()
}
this.persist?.()
} else {
const originalHeight = this.props.size[1]
this.canResize[1] = !collapsed
console.log(
collapsed,
collapsed ? this.getHeaderHeight() : this.props.collapsedHeight,
this.getHeaderHeight(),
this.props.collapsedHeight
)
this.update({
isAutoResizing: !collapsed,
collapsed: collapsed,
size: [this.props.size[0], collapsed ? this.getHeaderHeight() : this.props.collapsedHeight],
collapsedHeight: collapsed ? originalHeight : this.props.collapsedHeight,
})
}
}
@computed get scaleLevel() {
return this.props.scaleLevel ?? 'md'
}
@action setScaleLevel = async (v?: SizeLevel) => {
const newSize = Vec.mul(
this.props.size,
levelToScale[(v as SizeLevel) ?? 'md'] / levelToScale[this.props.scaleLevel ?? 'md']
)
this.update({
scaleLevel: v,
})
await delay()
this.update({
size: newSize,
})
}
useComponentSize<T extends HTMLElement>(ref: React.RefObject<T> | null, selector = '') {
const [size, setSize] = React.useState<[number, number]>([0, 0])
const app = useApp<Shape>()
React.useEffect(() => {
if (ref?.current) {
const el = selector ? ref.current.querySelector<HTMLElement>(selector) : ref.current
if (el) {
const updateSize = () => {
const { width, height } = el.getBoundingClientRect()
const bound = Vec.div([width, height], app.viewport.camera.zoom) as [number, number]
setSize(bound)
return bound
}
updateSize()
// Hacky, I know 🤨
this.getInnerHeight = () => updateSize()[1]
const resizeObserver = new ResizeObserver(() => {
updateSize()
})
resizeObserver.observe(el)
return () => {
resizeObserver.disconnect()
}
}
}
return () => {}
}, [ref, selector])
return size
}
getHeaderHeight() {
const scale = levelToScale[this.props.scaleLevel ?? 'md']
return this.props.compact ? 0 : HEADER_HEIGHT * scale
}
getAutoResizeHeight() {
if (this.getInnerHeight) {
return this.getHeaderHeight() + this.getInnerHeight()
}
return null
}
onResetBounds = (info?: TLResetBoundsInfo) => {
const height = this.getAutoResizeHeight()
if (height !== null && Math.abs(height - this.props.size[1]) > AUTO_RESIZE_THRESHOLD) {
this.update({
size: [this.props.size[0], height],
})
this.initialHeightCalculated = true
}
return this
}
onResize = (initialProps: any, info: TLResizeInfo): this => {
const {
bounds,
rotation,
scale: [scaleX, scaleY],
} = info
const nextScale = [...this.scale]
if (scaleX < 0) nextScale[0] *= -1
if (scaleY < 0) nextScale[1] *= -1
let height = bounds.height
if (this.props.isAutoResizing) {
height = this.getAutoResizeHeight() ?? height
}
return this.update({
point: [bounds.minX, bounds.minY],
size: [Math.max(1, bounds.width), Math.max(1, height)],
scale: nextScale,
rotation,
})
}
LogseqQuickSearch = observer(({ onChange }: LogseqQuickSearchProps) => {
const [q, setQ] = React.useState(LogseqPortalShape.defaultSearchQuery)
const [searchFilter, setSearchFilter] = React.useState<'B' | 'P' | null>(
LogseqPortalShape.defaultSearchFilter
)
const rInput = React.useRef<HTMLInputElement>(null)
const { handlers, renderers } = React.useContext(LogseqContext)
const app = useApp<Shape>()
const finishCreating = React.useCallback((id: string) => {
onChange(id)
rInput.current?.blur()
if (id) {
LogseqPortalShape.defaultSearchQuery = ''
LogseqPortalShape.defaultSearchFilter = null
}
}, [])
const onAddBlock = React.useCallback((content: string) => {
const uuid = handlers?.addNewBlock(content)
if (uuid) {
finishCreating(uuid)
// wait until the editor is mounted
setTimeout(() => {
app.api.editShape(this)
window.logseq?.api?.edit_block?.(uuid)
})
}
return uuid
}, [])
const optionsWrapperRef = React.useRef<HTMLDivElement>(null)
const [focusedOptionIdx, setFocusedOptionIdx] = React.useState<number>(0)
const searchResult = useSearch(q, searchFilter)
const [prefixIcon, setPrefixIcon] = React.useState<string>('circle-plus')
React.useEffect(() => {
// autofocus seems not to be working
setTimeout(() => {
rInput.current?.focus()
})
}, [searchFilter])
React.useEffect(() => {
LogseqPortalShape.defaultSearchQuery = q
LogseqPortalShape.defaultSearchFilter = searchFilter
}, [q, searchFilter])
type Option = {
actionIcon: 'search' | 'circle-plus'
onChosen: () => boolean // return true if the action was handled
element: React.ReactNode
}
const options: Option[] = React.useMemo(() => {
const options: Option[] = []
const Breadcrumb = renderers?.Breadcrumb
if (!Breadcrumb || !handlers) {
return []
}
// New block option
options.push({
actionIcon: 'circle-plus',
onChosen: () => {
return !!onAddBlock(q)
},
element: (
<div className="tl-quick-search-option-row">
<LogseqTypeTag active type="BA" />
{q.length > 0 ? (
<>
<strong>New block:</strong>
{q}
</>
) : (
<strong>New block</strong>
)}
</div>
),
})
// New page option when no exact match
if (!searchResult?.pages?.some(p => p.toLowerCase() === q.toLowerCase()) && q) {
options.push({
actionIcon: 'circle-plus',
onChosen: () => {
finishCreating(q)
return true
},
element: (
<div className="tl-quick-search-option-row">
<LogseqTypeTag active type="PA" />
<strong>New page:</strong>
{q}
</div>
),
})
}
// search filters
if (q.length === 0 && searchFilter === null) {
options.push(
{
actionIcon: 'search',
onChosen: () => {
setSearchFilter('B')
return true
},
element: (
<div className="tl-quick-search-option-row">
<LogseqTypeTag type="BS" />
Search only blocks
</div>
),
},
{
actionIcon: 'search',
onChosen: () => {
setSearchFilter('P')
return true
},
element: (
<div className="tl-quick-search-option-row">
<LogseqTypeTag type="PS" />
Search only pages
</div>
),
}
)
}
// Page results
if ((!searchFilter || searchFilter === 'P') && searchResult && searchResult.pages) {
options.push(
...searchResult.pages.map(page => {
return {
actionIcon: 'search' as 'search',
onChosen: () => {
finishCreating(page)
return true
},
element: (
<div className="tl-quick-search-option-row">
<LogseqTypeTag type={handlers.isWhiteboardPage(page) ? 'WP' : 'P'} />
{highlightedJSX(page, q)}
</div>
),
}
})
)
}
// Block results
if ((!searchFilter || searchFilter === 'B') && searchResult && searchResult.blocks) {
options.push(
...searchResult.blocks
.filter(block => block.content && block.uuid)
.map(({ content, uuid }) => {
const block = handlers.queryBlockByUUID(uuid)
return {
actionIcon: 'search' as 'search',
onChosen: () => {
if (block) {
finishCreating(uuid)
window.logseq?.api?.set_blocks_id?.([uuid])
return true
}
return false
},
element: block ? (
<>
<div className="tl-quick-search-option-row">
<LogseqTypeTag type="B" />
<div className="tl-quick-search-option-breadcrumb">
<Breadcrumb blockId={uuid} />
</div>
</div>
<div className="tl-quick-search-option-row">
<div className="tl-quick-search-option-placeholder" />
{highlightedJSX(content, q)}
</div>
</>
) : (
<div className="tl-quick-search-option-row">
Cache is outdated. Please click the 'Re-index' button in the graph's dropdown
menu.
</div>
),
}
})
)
}
return options
}, [q, searchFilter, searchResult, renderers?.Breadcrumb, handlers])
React.useEffect(() => {
const keydownListener = (e: KeyboardEvent) => {
let newIndex = focusedOptionIdx
if (e.key === 'ArrowDown') {
newIndex = Math.min(options.length - 1, focusedOptionIdx + 1)
} else if (e.key === 'ArrowUp') {
newIndex = Math.max(0, focusedOptionIdx - 1)
} else if (e.key === 'Enter') {
options[focusedOptionIdx]?.onChosen()
e.stopPropagation()
e.preventDefault()
} else if (e.key === 'Backspace' && q.length === 0) {
setSearchFilter(null)
} else if (e.key === 'Escape') {
finishCreating('')
}
if (newIndex !== focusedOptionIdx) {
const option = options[newIndex]
setFocusedOptionIdx(newIndex)
setPrefixIcon(option.actionIcon)
e.stopPropagation()
e.preventDefault()
const optionElement = optionsWrapperRef.current?.querySelector(
'.tl-quick-search-option:nth-child(' + (newIndex + 1) + ')'
)
if (optionElement) {
// @ts-expect-error we are using scrollIntoViewIfNeeded, which is not in standards
optionElement?.scrollIntoViewIfNeeded(false)
}
}
}
document.addEventListener('keydown', keydownListener, true)
return () => {
document.removeEventListener('keydown', keydownListener, true)
}
}, [options, focusedOptionIdx, q])
return (
<div className="tl-quick-search">
<CircleButton
icon={prefixIcon}
onClick={() => {
options[focusedOptionIdx]?.onChosen()
}}
/>
<div className="tl-quick-search-input-container">
{searchFilter && (
<div className="tl-quick-search-input-filter">
<LogseqTypeTag type={searchFilter} />
{searchFilter === 'B' ? 'Search blocks' : 'Search pages'}
<div
className="tl-quick-search-input-filter-remove"
onClick={() => setSearchFilter(null)}
>
<TablerIcon name="x" />
</div>
</div>
)}
<TextInput
ref={rInput}
type="text"
value={q}
className="tl-quick-search-input"
placeholder="Create or search your graph..."
onChange={q => setQ(q.target.value)}
onKeyDown={e => {
if (e.key === 'Enter') {
finishCreating(q)
}
}}
/>
</div>
<div className="tl-quick-search-options" ref={optionsWrapperRef}>
<Virtuoso
style={{ height: Math.min(Math.max(1, options.length), 12) * 40 }}
totalCount={options.length}
itemContent={index => {
const { actionIcon, onChosen, element } = options[index]
return (
<div
key={index}
data-focused={index === focusedOptionIdx}
className="tl-quick-search-option"
tabIndex={0}
onMouseEnter={() => {
setPrefixIcon(actionIcon)
setFocusedOptionIdx(index)
}}
// we have to use mousedown && stop propagation EARLY, otherwise some
// default behavior of clicking the rendered elements will happen
onMouseDownCapture={e => {
if (onChosen()) {
e.stopPropagation()
e.preventDefault()
}
}}
>
{element}
</div>
)
}}
/>
</div>
</div>
)
})
PortalComponent = observer(({}: TLComponentProps) => {
const {
props: { pageId, fill, opacity },
} = this
const { renderers } = React.useContext(LogseqContext)
const app = useApp<Shape>()
const cpRefContainer = React.useRef<HTMLDivElement>(null)
const [, innerHeight] = this.useComponentSize(
cpRefContainer,
this.props.compact
? '.tl-logseq-cp-container > .single-block'
: '.tl-logseq-cp-container > .page'
)
if (!renderers?.Page) {
return null // not being correctly configured
}
const { Page, Block } = renderers
React.useEffect(() => {
if (this.props.isAutoResizing) {
const latestInnerHeight = this.getInnerHeight?.() ?? innerHeight
const newHeight = latestInnerHeight + this.getHeaderHeight()
if (innerHeight && Math.abs(newHeight - this.props.size[1]) > AUTO_RESIZE_THRESHOLD) {
this.update({
size: [this.props.size[0], newHeight],
})
app.persist(true)
}
}
}, [innerHeight, this.props.isAutoResizing])
React.useEffect(() => {
if (!this.initialHeightCalculated) {
setTimeout(() => {
this.onResetBounds()
app.persist(true)
})
}
}, [this.initialHeightCalculated])
return (
<>
<div
className="absolute inset-0 tl-logseq-cp-container-bg"
style={{
background:
fill && fill !== 'var(--ls-secondary-background-color)'
? `var(--ls-highlight-color-${fill})`
: 'var(--ls-secondary-background-color)',
opacity,
}}
></div>
<div
ref={cpRefContainer}
className="relative tl-logseq-cp-container"
style={{ overflow: this.props.isAutoResizing ? 'visible' : 'auto' }}
>
{this.props.blockType === 'B' && this.props.compact ? (
<Block blockId={pageId} />
) : (
<Page pageName={pageId} />
)}
</div>
</>
)
})
ReactComponent = observer((componentProps: TLComponentProps) => {
const { events, isErasing, isEditing, isBinding } = componentProps
const {
props: { opacity, pageId, stroke, fill, scaleLevel, strokeWidth, size },
} = this
const app = useApp<Shape>()
const { renderers, handlers } = React.useContext(LogseqContext)
this.persist = () => app.persist()
const isMoving = useCameraMovingRef()
const isSelected = app.selectedIds.has(this.id) && app.selectedIds.size === 1
const isCreating = app.isIn('logseq-portal.creating') && !pageId
const tlEventsEnabled =
(isMoving || (isSelected && !isEditing) || app.selectedTool.id !== 'select') && !isCreating
const stop = React.useCallback(
e => {
if (!tlEventsEnabled) {
// TODO: pinching inside Logseq Shape issue
e.stopPropagation()
}
},
[tlEventsEnabled]
)
// There are some other portal sharing the same page id are selected
const portalSelected =
app.selectedShapesArray.length === 1 &&
app.selectedShapesArray.some(
shape =>
shape.type === 'logseq-portal' &&
shape.props.id !== this.props.id &&
pageId &&
(shape as LogseqPortalShape).props['pageId'] === pageId
)
const scaleRatio = levelToScale[scaleLevel ?? 'md']
// It is a bit weird to update shapes here. Is there a better place?
React.useEffect(() => {
if (this.props.collapsed && isEditing) {
// Should temporarily disable collapsing
this.update({
size: [this.props.size[0], this.props.collapsedHeight],
})
return () => {
this.update({
size: [this.props.size[0], this.getHeaderHeight()],
})
}
}
return () => {
// no-ops
}
}, [isEditing, this.props.collapsed])
const onPageNameChanged = React.useCallback((id: string) => {
this.initialHeightCalculated = false
const blockType = validUUID(id) ? 'B' : 'P'
this.update({
pageId: id,
size: [400, 320],
blockType: blockType,
compact: blockType === 'B',
})
app.selectTool('select')
app.history.resume()
app.history.persist()
}, [])
const PortalComponent = this.PortalComponent
const LogseqQuickSearch = this.LogseqQuickSearch
const blockContent = React.useMemo(() => {
if (pageId && this.props.blockType === 'B') {
return handlers?.queryBlockByUUID(pageId)?.content
}
}, [handlers?.queryBlockByUUID, pageId])
const targetNotFound = this.props.blockType === 'B' && typeof blockContent !== 'string'
const showingPortal = (!this.props.collapsed || isEditing) && !targetNotFound
if (!renderers?.Page) {
return null // not being correctly configured
}
const { Breadcrumb, PageNameLink } = renderers
return (
<HTMLContainer
style={{
pointerEvents: 'all',
}}
{...events}
>
{isBinding && <BindingIndicator mode="html" strokeWidth={strokeWidth} size={size} />}
<div
onWheelCapture={stop}
onPointerDown={stop}
onPointerUp={stop}
style={{
width: '100%',
height: '100%',
pointerEvents: !isMoving && (isEditing || isSelected) ? 'all' : 'none',
}}
>
{isCreating ? (
<LogseqQuickSearch onChange={onPageNameChanged} />
) : (
<>
<div
className="tl-logseq-portal-container"
data-collapsed={this.collapsed}
data-page-id={pageId}
data-portal-selected={portalSelected}
data-editing={isEditing}
style={{
width: `calc(100% / ${scaleRatio})`,
height: `calc(100% / ${scaleRatio})`,
transform: `scale(${scaleRatio})`,
opacity: isErasing ? 0.2 : 1,
}}
>
{!this.props.compact && !targetNotFound && (
<LogseqPortalShapeHeader
type={this.props.blockType ?? 'P'}
fill={fill}
opacity={opacity}
>
{this.props.blockType === 'P' ? (
<PageNameLink pageName={pageId} />
) : (
<Breadcrumb blockId={pageId} />
)}
</LogseqPortalShapeHeader>
)}
{targetNotFound && <div className="tl-target-not-found">Target not found</div>}
{showingPortal && <PortalComponent {...componentProps} />}
</div>
<CircleButton
active={!!this.collapsed}
style={{ opacity: isSelected ? 1 : 0 }}
icon={this.props.blockType === 'B' ? 'block' : 'page'}
onClick={() => this.setCollapsed(!this.collapsed)}
otherIcon={'whiteboard-element'}
/>
</>
)}
</div>
</HTMLContainer>
)
})
ReactIndicator = observer(() => {
const bounds = this.getBounds()
const app = useApp<Shape>()
if (app.selectedShapesArray.length === 1) {
return null
}
return <rect width={bounds.width} height={bounds.height} fill="transparent" rx={8} ry={8} />
})
validateProps = (props: Partial<LogseqPortalShapeProps>) => {
if (props.size !== undefined) {
const scale = levelToScale[this.props.scaleLevel ?? 'md']
props.size[0] = Math.max(props.size[0], 60 * scale)
props.size[1] = Math.max(props.size[1], HEADER_HEIGHT * scale)
}
return withClampedStyles(this, props)
}
getShapeSVGJsx({ preview }: any) {
// Do not need to consider the original point here
const bounds = this.getBounds()
return (
<>
<rect
fill={
this.props.fill && this.props.fill !== 'var(--ls-secondary-background-color)'
? `var(--ls-highlight-color-${this.props.fill})`
: 'var(--ls-secondary-background-color)'
}
stroke={getComputedColor(this.props.fill, 'background')}
strokeWidth={this.props.strokeWidth ?? 2}
fillOpacity={this.props.opacity ?? 0.2}
width={bounds.width}
rx={8}
ry={8}
height={bounds.height}
/>
{!this.props.compact && (
<rect
fill={
this.props.fill && this.props.fill !== 'var(--ls-secondary-background-color)'
? getComputedColor(this.props.fill, 'background')
: 'var(--ls-tertiary-background-color)'
}
fillOpacity={this.props.opacity ?? 0.2}
x={1}
y={1}
width={bounds.width - 2}
height={HEADER_HEIGHT - 2}
rx={8}
ry={8}
/>
)}
<text
style={{
transformOrigin: 'top left',
}}
transform={`translate(${bounds.width / 2}, ${10 + bounds.height / 2})`}
textAnchor="middle"
fontFamily="var(--ls-font-family)"
fontSize="32"
fill="var(--ls-secondary-text-color)"
stroke="var(--ls-secondary-text-color)"
>
{this.props.blockType === 'P' ? this.props.pageId : ''}
</text>
</>
)
}
}