LogseqPortalShape.tsx 26 KB

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