LogseqPortalShape.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860
  1. /* eslint-disable @typescript-eslint/no-explicit-any */
  2. import {
  3. delay,
  4. TLBoxShape,
  5. TLBoxShapeProps,
  6. TLResetBoundsInfo,
  7. TLResizeInfo,
  8. validUUID,
  9. } from '@tldraw/core'
  10. import { HTMLContainer, TLComponentProps, useApp } from '@tldraw/react'
  11. import Vec from '@tldraw/vec'
  12. import { action, computed, makeObservable } from 'mobx'
  13. import { observer } from 'mobx-react-lite'
  14. import * as React from 'react'
  15. import type { SizeLevel, Shape } from '.'
  16. import { TablerIcon } from '../../components/icons'
  17. import { TextInput } from '../../components/inputs/TextInput'
  18. import { useCameraMovingRef } from '../../hooks/useCameraMoving'
  19. import { LogseqContext, type SearchResult } from '../logseq-context'
  20. import { CustomStyleProps, withClampedStyles } from './style-props'
  21. const HEADER_HEIGHT = 40
  22. const AUTO_RESIZE_THRESHOLD = 1
  23. export interface LogseqPortalShapeProps extends TLBoxShapeProps, CustomStyleProps {
  24. type: 'logseq-portal'
  25. pageId: string // page name or UUID
  26. blockType?: 'P' | 'B'
  27. collapsed?: boolean
  28. compact?: boolean
  29. collapsedHeight?: number
  30. scaleLevel?: SizeLevel
  31. }
  32. interface LogseqQuickSearchProps {
  33. onChange: (id: string) => void
  34. }
  35. const levelToScale = {
  36. xs: 0.5,
  37. sm: 0.8,
  38. md: 1,
  39. lg: 1.5,
  40. xl: 2,
  41. xxl: 3,
  42. }
  43. const LogseqTypeTag = ({
  44. type,
  45. active,
  46. }: {
  47. type: 'B' | 'P' | 'WP' | 'BS' | 'PS'
  48. active?: boolean
  49. }) => {
  50. const nameMapping = {
  51. B: 'block',
  52. P: 'page',
  53. WP: 'whiteboard',
  54. BS: 'block-search',
  55. PS: 'page-search',
  56. }
  57. return (
  58. <span className="tl-type-tag" data-active={active}>
  59. <i className={`tie tie-${nameMapping[type]}`} />
  60. </span>
  61. )
  62. }
  63. const LogseqPortalShapeHeader = observer(
  64. ({ type, children }: { type: 'P' | 'B'; children: React.ReactNode }) => {
  65. return (
  66. <div className="tl-logseq-portal-header">
  67. <LogseqTypeTag type={type} />
  68. {children}
  69. </div>
  70. )
  71. }
  72. )
  73. function escapeRegExp(text: string) {
  74. return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&')
  75. }
  76. const highlightedJSX = (input: string, keyword: string) => {
  77. return (
  78. <span>
  79. {input
  80. .split(new RegExp(`(${escapeRegExp(keyword)})`, 'gi'))
  81. .map((part, index) => {
  82. if (index % 2 === 1) {
  83. return <mark className="tl-highlighted">{part}</mark>
  84. }
  85. return part
  86. })
  87. .map((frag, idx) => (
  88. <React.Fragment key={idx}>{frag}</React.Fragment>
  89. ))}
  90. </span>
  91. )
  92. }
  93. const useSearch = (q: string, searchFilter: 'B' | 'P' | null) => {
  94. const { handlers } = React.useContext(LogseqContext)
  95. const [results, setResults] = React.useState<SearchResult | null>(null)
  96. React.useEffect(() => {
  97. let canceled = false
  98. if (q.length > 0) {
  99. const filter = { 'pages?': true, 'blocks?': true, 'files?': false }
  100. if (searchFilter === 'B') {
  101. filter['pages?'] = false
  102. } else if (searchFilter === 'P') {
  103. filter['blocks?'] = false
  104. }
  105. handlers.search(q, filter).then(_results => {
  106. if (!canceled) {
  107. setResults(_results)
  108. }
  109. })
  110. } else {
  111. setResults(null)
  112. }
  113. return () => {
  114. canceled = true
  115. }
  116. }, [q, handlers?.search])
  117. return results
  118. }
  119. export class LogseqPortalShape extends TLBoxShape<LogseqPortalShapeProps> {
  120. static id = 'logseq-portal'
  121. static defaultProps: LogseqPortalShapeProps = {
  122. id: 'logseq-portal',
  123. type: 'logseq-portal',
  124. parentId: 'page',
  125. point: [0, 0],
  126. size: [400, 50],
  127. // collapsedHeight is the height before collapsing
  128. collapsedHeight: 0,
  129. stroke: 'var(--ls-primary-text-color)',
  130. fill: 'var(--ls-secondary-background-color)',
  131. noFill: false,
  132. strokeWidth: 2,
  133. strokeType: 'line',
  134. opacity: 1,
  135. pageId: '',
  136. collapsed: false,
  137. compact: false,
  138. scaleLevel: 'md',
  139. isAutoResizing: true,
  140. }
  141. hideRotateHandle = true
  142. canChangeAspectRatio = true
  143. canFlip = true
  144. canEdit = true
  145. persist: ((replace?: boolean) => void) | null = null
  146. // For quick add shapes, we want to calculate the page height dynamically
  147. initialHeightCalculated = true
  148. getInnerHeight: (() => number) | null = null // will be overridden in the hook
  149. constructor(props = {} as Partial<LogseqPortalShapeProps>) {
  150. super(props)
  151. makeObservable(this)
  152. if (props.collapsed) {
  153. Object.assign(this.canResize, [true, false])
  154. }
  155. if (props.size?.[1] === 0) {
  156. this.initialHeightCalculated = false
  157. }
  158. }
  159. static isPageOrBlock(id: string): 'P' | 'B' | false {
  160. const blockRefEg = '((62af02d0-0443-42e8-a284-946c162b0f89))'
  161. if (id) {
  162. return /^\(\(.*\)\)$/.test(id) && id.length === blockRefEg.length ? 'B' : 'P'
  163. }
  164. return false
  165. }
  166. @computed get collapsed() {
  167. return this.props.blockType === 'B' ? this.props.compact : this.props.collapsed
  168. }
  169. @action setCollapsed = async (collapsed: boolean) => {
  170. if (this.props.blockType === 'B') {
  171. this.update({ compact: collapsed })
  172. this.canResize[1] = !collapsed
  173. if (!collapsed) {
  174. // this will also persist the state, so we can skip persist call
  175. await delay()
  176. this.onResetBounds()
  177. }
  178. this.persist?.()
  179. } else {
  180. const originalHeight = this.props.size[1]
  181. this.canResize[1] = !collapsed
  182. this.update({
  183. collapsed: collapsed,
  184. size: [this.props.size[0], collapsed ? this.getHeaderHeight() : this.props.collapsedHeight],
  185. collapsedHeight: collapsed ? originalHeight : this.props.collapsedHeight,
  186. })
  187. }
  188. }
  189. @computed get scaleLevel() {
  190. return this.props.scaleLevel ?? 'md'
  191. }
  192. @action setScaleLevel = async (v?: SizeLevel) => {
  193. const newSize = Vec.mul(
  194. this.props.size,
  195. levelToScale[(v as SizeLevel) ?? 'md'] / levelToScale[this.props.scaleLevel ?? 'md']
  196. )
  197. this.update({
  198. scaleLevel: v,
  199. })
  200. await delay()
  201. this.update({
  202. size: newSize,
  203. })
  204. }
  205. useComponentSize<T extends HTMLElement>(ref: React.RefObject<T> | null, selector = '') {
  206. const [size, setSize] = React.useState<[number, number]>([0, 0])
  207. const app = useApp<Shape>()
  208. React.useEffect(() => {
  209. if (ref?.current) {
  210. const el = selector ? ref.current.querySelector<HTMLElement>(selector) : ref.current
  211. if (el) {
  212. const updateSize = () => {
  213. const { width, height } = el.getBoundingClientRect()
  214. const bound = Vec.div([width, height], app.viewport.camera.zoom) as [number, number]
  215. setSize(bound)
  216. return bound
  217. }
  218. updateSize()
  219. // Hacky, I know 🤨
  220. this.getInnerHeight = () => updateSize()[1]
  221. const resizeObserver = new ResizeObserver(() => {
  222. updateSize()
  223. })
  224. resizeObserver.observe(el)
  225. return () => {
  226. resizeObserver.disconnect()
  227. }
  228. }
  229. }
  230. return () => {}
  231. }, [ref, selector])
  232. return size
  233. }
  234. getHeaderHeight() {
  235. const scale = levelToScale[this.props.scaleLevel ?? 'md']
  236. return this.props.compact ? 0 : HEADER_HEIGHT * scale
  237. }
  238. getAutoResizeHeight() {
  239. if (this.getInnerHeight) {
  240. return this.getHeaderHeight() + this.getInnerHeight()
  241. }
  242. return null
  243. }
  244. onResetBounds = (info?: TLResetBoundsInfo) => {
  245. const height = this.getAutoResizeHeight()
  246. if (height !== null && Math.abs(height - this.props.size[1]) > AUTO_RESIZE_THRESHOLD) {
  247. this.update({
  248. size: [this.props.size[0], height],
  249. })
  250. this.initialHeightCalculated = true
  251. }
  252. return this
  253. }
  254. onResize = (initialProps: any, info: TLResizeInfo): this => {
  255. const {
  256. bounds,
  257. rotation,
  258. scale: [scaleX, scaleY],
  259. } = info
  260. const nextScale = [...this.scale]
  261. if (scaleX < 0) nextScale[0] *= -1
  262. if (scaleY < 0) nextScale[1] *= -1
  263. let height = bounds.height
  264. if (this.props.isAutoResizing) {
  265. height = this.getAutoResizeHeight() ?? height
  266. }
  267. return this.update({
  268. point: [bounds.minX, bounds.minY],
  269. size: [Math.max(1, bounds.width), Math.max(1, height)],
  270. scale: nextScale,
  271. rotation,
  272. })
  273. }
  274. LogseqQuickSearch = observer(({ onChange }: LogseqQuickSearchProps) => {
  275. const [q, setQ] = React.useState('')
  276. const rInput = React.useRef<HTMLInputElement>(null)
  277. const { handlers, renderers } = React.useContext(LogseqContext)
  278. const app = useApp<Shape>()
  279. const finishCreating = React.useCallback((id: string) => {
  280. onChange(id)
  281. rInput.current?.blur()
  282. }, [])
  283. const onAddBlock = React.useCallback((content: string) => {
  284. const uuid = handlers?.addNewBlock(content)
  285. if (uuid) {
  286. finishCreating(uuid)
  287. // wait until the editor is mounted
  288. setTimeout(() => {
  289. app.api.editShape(this)
  290. window.logseq?.api?.edit_block?.(uuid)
  291. })
  292. }
  293. return uuid
  294. }, [])
  295. const optionsWrapperRef = React.useRef<HTMLDivElement>(null)
  296. const [focusedOptionIdx, setFocusedOptionIdx] = React.useState<number>(0)
  297. const [searchFilter, setSearchFilter] = React.useState<'B' | 'P' | null>(null)
  298. const searchResult = useSearch(q, searchFilter)
  299. const [prefixIcon, setPrefixIcon] = React.useState<string>('circle-plus')
  300. React.useEffect(() => {
  301. // autofocus seems not to be working
  302. setTimeout(() => {
  303. rInput.current?.focus()
  304. })
  305. }, [searchFilter])
  306. type Option = {
  307. actionIcon: 'search' | 'circle-plus'
  308. onChosen: () => boolean // return true if the action was handled
  309. element: React.ReactNode
  310. }
  311. const options: Option[] = React.useMemo(() => {
  312. const options: Option[] = []
  313. const Breadcrumb = renderers?.Breadcrumb
  314. if (!Breadcrumb || !handlers) {
  315. return []
  316. }
  317. // New block option
  318. options.push({
  319. actionIcon: 'circle-plus',
  320. onChosen: () => {
  321. return !!onAddBlock(q)
  322. },
  323. element: (
  324. <div className="tl-quick-search-option-row">
  325. <LogseqTypeTag active type="B" />
  326. {q.length > 0 ? (
  327. <>
  328. <strong>New whiteboard block:</strong>
  329. {q}
  330. </>
  331. ) : (
  332. <strong>New whiteboard block</strong>
  333. )}
  334. </div>
  335. ),
  336. })
  337. // New page option when no exact match
  338. if (!searchResult?.pages?.some(p => p.toLowerCase() === q.toLowerCase()) && q) {
  339. options.push({
  340. actionIcon: 'circle-plus',
  341. onChosen: () => {
  342. finishCreating(q)
  343. return true
  344. },
  345. element: (
  346. <div className="tl-quick-search-option-row">
  347. <LogseqTypeTag active type="P" />
  348. <strong>New page:</strong>
  349. {q}
  350. </div>
  351. ),
  352. })
  353. }
  354. // search filters
  355. if (q.length === 0 && searchFilter === null) {
  356. options.push(
  357. {
  358. actionIcon: 'search',
  359. onChosen: () => {
  360. setSearchFilter('B')
  361. return true
  362. },
  363. element: (
  364. <div className="tl-quick-search-option-row">
  365. <LogseqTypeTag type="BS" />
  366. Search only blocks
  367. </div>
  368. ),
  369. },
  370. {
  371. actionIcon: 'search',
  372. onChosen: () => {
  373. setSearchFilter('P')
  374. return true
  375. },
  376. element: (
  377. <div className="tl-quick-search-option-row">
  378. <LogseqTypeTag type="PS" />
  379. Search only pages
  380. </div>
  381. ),
  382. }
  383. )
  384. }
  385. // Page results
  386. if ((!searchFilter || searchFilter === 'P') && searchResult && searchResult.pages) {
  387. options.push(
  388. ...searchResult.pages.map(page => {
  389. return {
  390. actionIcon: 'search' as 'search',
  391. onChosen: () => {
  392. finishCreating(page)
  393. return true
  394. },
  395. element: (
  396. <div className="tl-quick-search-option-row">
  397. <LogseqTypeTag type={handlers.isWhiteboardPage(page) ? 'WP' : 'P'} />
  398. {highlightedJSX(page, q)}
  399. </div>
  400. ),
  401. }
  402. })
  403. )
  404. }
  405. // Block results
  406. if ((!searchFilter || searchFilter === 'B') && searchResult && searchResult.blocks) {
  407. options.push(
  408. ...searchResult.blocks
  409. .filter(block => block.content && block.uuid)
  410. .map(({ content, uuid }) => {
  411. const block = handlers.queryBlockByUUID(uuid)
  412. return {
  413. actionIcon: 'search' as 'search',
  414. onChosen: () => {
  415. if (block) {
  416. finishCreating(uuid)
  417. window.logseq?.api?.set_blocks_id?.([uuid])
  418. return true
  419. }
  420. return false
  421. },
  422. element: block ? (
  423. <>
  424. <div className="tl-quick-search-option-row">
  425. <LogseqTypeTag type="B" />
  426. <div className="tl-quick-search-option-breadcrumb">
  427. <Breadcrumb blockId={uuid} />
  428. </div>
  429. </div>
  430. <div className="tl-quick-search-option-row">
  431. <div className="tl-quick-search-option-placeholder" />
  432. {highlightedJSX(content, q)}
  433. </div>
  434. </>
  435. ) : (
  436. <div className="tl-quick-search-option-row">
  437. Cache is outdated. Please click the 'Re-index' button in the graph's dropdown
  438. menu.
  439. </div>
  440. ),
  441. }
  442. })
  443. )
  444. }
  445. return options
  446. }, [q, searchFilter, searchResult, renderers?.Breadcrumb, handlers])
  447. React.useEffect(() => {
  448. const keydownListener = (e: KeyboardEvent) => {
  449. let newIndex = focusedOptionIdx
  450. if (e.key === 'ArrowDown') {
  451. newIndex = Math.min(options.length - 1, focusedOptionIdx + 1)
  452. } else if (e.key === 'ArrowUp') {
  453. newIndex = Math.max(0, focusedOptionIdx - 1)
  454. } else if (e.key === 'Enter') {
  455. options[focusedOptionIdx]?.onChosen()
  456. e.stopPropagation()
  457. e.preventDefault()
  458. } else if (e.key === 'Backspace' && q.length === 0) {
  459. setSearchFilter(null)
  460. }
  461. if (newIndex !== focusedOptionIdx) {
  462. const option = options[newIndex]
  463. setFocusedOptionIdx(newIndex)
  464. setPrefixIcon(option.actionIcon)
  465. e.stopPropagation()
  466. e.preventDefault()
  467. const optionElement = optionsWrapperRef.current?.querySelector(
  468. '.tl-quick-search-option:nth-child(' + (newIndex + 1) + ')'
  469. )
  470. if (optionElement) {
  471. // @ts-expect-error we are using scrollIntoViewIfNeeded, which is not in standards
  472. optionElement?.scrollIntoViewIfNeeded(false)
  473. }
  474. }
  475. }
  476. document.addEventListener('keydown', keydownListener, true)
  477. return () => {
  478. document.removeEventListener('keydown', keydownListener, true)
  479. }
  480. }, [options, focusedOptionIdx, q])
  481. return (
  482. <div className="tl-quick-search">
  483. <div className="tl-quick-search-indicator">
  484. <TablerIcon name={prefixIcon} className="tl-quick-search-icon" />
  485. </div>
  486. <div className="tl-quick-search-input-container">
  487. {searchFilter && (
  488. <div className="tl-quick-search-input-filter">
  489. <LogseqTypeTag type={searchFilter} />
  490. {searchFilter === 'B' ? 'Search blocks' : 'Search pages'}
  491. <div
  492. className="tl-quick-search-input-filter-remove"
  493. onClick={() => setSearchFilter(null)}
  494. >
  495. <TablerIcon name="x" />
  496. </div>
  497. </div>
  498. )}
  499. <TextInput
  500. ref={rInput}
  501. type="text"
  502. value={q}
  503. className="tl-quick-search-input"
  504. placeholder="Create or search your graph..."
  505. onChange={q => setQ(q.target.value)}
  506. onKeyDown={e => {
  507. if (e.key === 'Enter') {
  508. finishCreating(q)
  509. }
  510. }}
  511. />
  512. </div>
  513. <div className="tl-quick-search-options" ref={optionsWrapperRef}>
  514. {options.map(({ actionIcon, onChosen, element }, index) => {
  515. return (
  516. <div
  517. key={index}
  518. data-focused={index === focusedOptionIdx}
  519. className="tl-quick-search-option"
  520. tabIndex={0}
  521. onMouseEnter={() => {
  522. setPrefixIcon(actionIcon)
  523. setFocusedOptionIdx(index)
  524. }}
  525. // we have to use mousedown && stop propagation, otherwise some
  526. // default behavior of clicking the rendered elements will happen
  527. onMouseDown={e => {
  528. if (onChosen()) {
  529. e.stopPropagation()
  530. e.preventDefault()
  531. }
  532. }}
  533. >
  534. {element}
  535. </div>
  536. )
  537. })}
  538. </div>
  539. </div>
  540. )
  541. })
  542. PortalComponent = observer(({}: TLComponentProps) => {
  543. const {
  544. props: { pageId },
  545. } = this
  546. const { renderers } = React.useContext(LogseqContext)
  547. const app = useApp<Shape>()
  548. const cpRefContainer = React.useRef<HTMLDivElement>(null)
  549. const [, innerHeight] = this.useComponentSize(
  550. cpRefContainer,
  551. this.props.compact
  552. ? '.tl-logseq-cp-container > .single-block'
  553. : '.tl-logseq-cp-container > .page'
  554. )
  555. if (!renderers?.Page) {
  556. return null // not being correctly configured
  557. }
  558. const { Page, Block } = renderers
  559. React.useEffect(() => {
  560. if (this.props.isAutoResizing) {
  561. const latestInnerHeight = this.getInnerHeight?.() ?? innerHeight
  562. const newHeight = latestInnerHeight + this.getHeaderHeight()
  563. if (innerHeight && Math.abs(newHeight - this.props.size[1]) > AUTO_RESIZE_THRESHOLD) {
  564. this.update({
  565. size: [this.props.size[0], newHeight],
  566. })
  567. app.persist(true)
  568. }
  569. }
  570. }, [innerHeight, this.props.isAutoResizing])
  571. React.useEffect(() => {
  572. if (!this.initialHeightCalculated) {
  573. setTimeout(() => {
  574. this.onResetBounds()
  575. app.persist(true)
  576. })
  577. }
  578. }, [this.initialHeightCalculated])
  579. return (
  580. <div
  581. ref={cpRefContainer}
  582. className="tl-logseq-cp-container"
  583. style={{
  584. overflow: this.props.isAutoResizing ? 'visible' : 'auto',
  585. }}
  586. >
  587. {this.props.blockType === 'B' && this.props.compact ? (
  588. <Block blockId={pageId} />
  589. ) : (
  590. <Page pageName={pageId} />
  591. )}
  592. </div>
  593. )
  594. })
  595. ReactComponent = observer((componentProps: TLComponentProps) => {
  596. const { events, isErasing, isEditing, isBinding } = componentProps
  597. const {
  598. props: { opacity, pageId, stroke, fill, scaleLevel },
  599. } = this
  600. const app = useApp<Shape>()
  601. const { renderers, handlers } = React.useContext(LogseqContext)
  602. this.persist = () => app.persist()
  603. const isMoving = useCameraMovingRef()
  604. const isSelected = app.selectedIds.has(this.id) && app.selectedIds.size === 1
  605. const isCreating = app.isIn('logseq-portal.creating') && !pageId
  606. const tlEventsEnabled =
  607. (isMoving || (isSelected && !isEditing) || app.selectedTool.id !== 'select') && !isCreating
  608. const stop = React.useCallback(
  609. e => {
  610. if (!tlEventsEnabled) {
  611. // TODO: pinching inside Logseq Shape issue
  612. e.stopPropagation()
  613. }
  614. },
  615. [tlEventsEnabled]
  616. )
  617. // There are some other portal sharing the same page id are selected
  618. const portalSelected =
  619. app.selectedShapesArray.length === 1 &&
  620. app.selectedShapesArray.some(
  621. shape =>
  622. shape.type === 'logseq-portal' &&
  623. shape.props.id !== this.props.id &&
  624. pageId &&
  625. (shape as LogseqPortalShape).props['pageId'] === pageId
  626. )
  627. const scaleRatio = levelToScale[scaleLevel ?? 'md']
  628. // It is a bit weird to update shapes here. Is there a better place?
  629. React.useEffect(() => {
  630. if (this.props.collapsed && isEditing) {
  631. // Should temporarily disable collapsing
  632. this.update({
  633. size: [this.props.size[0], this.props.collapsedHeight],
  634. })
  635. return () => {
  636. this.update({
  637. size: [this.props.size[0], this.getHeaderHeight()],
  638. })
  639. }
  640. }
  641. return () => {
  642. // no-ops
  643. }
  644. }, [isEditing, this.props.collapsed])
  645. const onPageNameChanged = React.useCallback((id: string) => {
  646. this.initialHeightCalculated = false
  647. const blockType = validUUID(id) ? 'B' : 'P'
  648. this.update({
  649. pageId: id,
  650. size: [400, 320],
  651. blockType: blockType,
  652. compact: blockType === 'B',
  653. })
  654. app.selectTool('select')
  655. app.history.resume()
  656. app.history.persist()
  657. }, [])
  658. const PortalComponent = this.PortalComponent
  659. const LogseqQuickSearch = this.LogseqQuickSearch
  660. const blockContent = React.useMemo(() => {
  661. if (pageId && this.props.blockType === 'B') {
  662. return handlers?.queryBlockByUUID(pageId)?.content
  663. }
  664. }, [handlers?.queryBlockByUUID, pageId])
  665. const targetNotFound = this.props.blockType === 'B' && typeof blockContent !== 'string'
  666. const showingPortal = (!this.props.collapsed || isEditing) && !targetNotFound
  667. if (!renderers?.Page) {
  668. return null // not being correctly configured
  669. }
  670. const { Breadcrumb, PageNameLink } = renderers
  671. return (
  672. <HTMLContainer
  673. style={{
  674. pointerEvents: 'all',
  675. opacity: isErasing ? 0.2 : opacity,
  676. }}
  677. {...events}
  678. >
  679. <div
  680. onWheelCapture={stop}
  681. onPointerDown={stop}
  682. onPointerUp={stop}
  683. style={{
  684. width: '100%',
  685. height: '100%',
  686. pointerEvents: !isMoving && (isEditing || isSelected) ? 'all' : 'none',
  687. }}
  688. >
  689. {isCreating ? (
  690. <LogseqQuickSearch onChange={onPageNameChanged} />
  691. ) : (
  692. <div
  693. className="tl-logseq-portal-container"
  694. data-collapsed={this.props.collapsed}
  695. data-page-id={pageId}
  696. data-portal-selected={portalSelected}
  697. style={{
  698. background: this.props.compact ? 'transparent' : fill,
  699. boxShadow: isBinding
  700. ? '0px 0px 0 var(--tl-binding-distance) var(--tl-binding)'
  701. : 'none',
  702. color: stroke,
  703. width: `calc(100% / ${scaleRatio})`,
  704. height: `calc(100% / ${scaleRatio})`,
  705. transform: `scale(${scaleRatio})`,
  706. // @ts-expect-error ???
  707. '--ls-primary-background-color': !fill?.startsWith('var') ? fill : undefined,
  708. '--ls-primary-text-color': !stroke?.startsWith('var') ? stroke : undefined,
  709. '--ls-title-text-color': !stroke?.startsWith('var') ? stroke : undefined,
  710. }}
  711. >
  712. {!this.props.compact && !targetNotFound && (
  713. <LogseqPortalShapeHeader type={this.props.blockType ?? 'P'}>
  714. {this.props.blockType === 'P' ? (
  715. <PageNameLink pageName={pageId} />
  716. ) : (
  717. <Breadcrumb blockId={pageId} />
  718. )}
  719. </LogseqPortalShapeHeader>
  720. )}
  721. {targetNotFound && <div className="tl-target-not-found">Target not found</div>}
  722. {showingPortal && <PortalComponent {...componentProps} />}
  723. </div>
  724. )}
  725. </div>
  726. </HTMLContainer>
  727. )
  728. })
  729. ReactIndicator = observer(() => {
  730. const bounds = this.getBounds()
  731. const app = useApp<Shape>()
  732. if (app.selectedShapesArray.length === 1) {
  733. return null
  734. }
  735. return <rect width={bounds.width} height={bounds.height} fill="transparent" rx={8} ry={8} />
  736. })
  737. validateProps = (props: Partial<LogseqPortalShapeProps>) => {
  738. if (props.size !== undefined) {
  739. const scale = levelToScale[this.props.scaleLevel ?? 'md']
  740. props.size[0] = Math.max(props.size[0], 240 * scale)
  741. props.size[1] = Math.max(props.size[1], HEADER_HEIGHT * scale)
  742. }
  743. return withClampedStyles(this, props)
  744. }
  745. getShapeSVGJsx({ preview }: any) {
  746. // Do not need to consider the original point here
  747. const bounds = this.getBounds()
  748. return (
  749. <>
  750. <rect
  751. fill={this.props.fill}
  752. stroke={this.props.stroke}
  753. strokeWidth={this.props.strokeWidth ?? 2}
  754. fillOpacity={this.props.opacity ?? 0.2}
  755. width={bounds.width}
  756. rx={8}
  757. ry={8}
  758. height={bounds.height}
  759. />
  760. {!this.props.compact && (
  761. <rect
  762. fill="#aaa"
  763. x={1}
  764. y={1}
  765. width={bounds.width - 2}
  766. height={HEADER_HEIGHT - 2}
  767. rx={8}
  768. ry={8}
  769. />
  770. )}
  771. <text
  772. style={{
  773. transformOrigin: 'top left',
  774. }}
  775. transform={`translate(${bounds.width / 2}, ${10 + bounds.height / 2})`}
  776. textAnchor="middle"
  777. fontFamily="var(--ls-font-family)"
  778. fontSize="32"
  779. fill={this.props.stroke}
  780. stroke={this.props.stroke}
  781. >
  782. {this.props.blockType === 'P' ? this.props.pageId : ''}
  783. </text>
  784. </>
  785. )
  786. }
  787. }