outline-container.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import { FC, memo, useEffect, useRef, useState } from 'react'
  2. import OutlinePane from '@/features/outline/components/outline-pane'
  3. import {
  4. FlatOutlineState,
  5. PartialFlatOutline,
  6. useOutlineContext,
  7. } from '@/features/ide-react/context/outline-context'
  8. import {
  9. nestOutline,
  10. Outline,
  11. } from '@/features/source-editor/utils/tree-operations/outline'
  12. import useScopeEventEmitter from '@/shared/hooks/use-scope-event-emitter'
  13. import { debugConsole } from '@/utils/debugging'
  14. export const OutlineContainer: FC = memo(() => {
  15. const {
  16. flatOutline,
  17. highlightedLine,
  18. canShowOutline,
  19. jumpToLine,
  20. outlineExpanded,
  21. toggleOutlineExpanded,
  22. } = useOutlineContext()
  23. const outlineToggledEmitter = useScopeEventEmitter('outline-toggled')
  24. const [outline, setOutline] = useState<{
  25. items: Outline[]
  26. partial: boolean
  27. }>(() => ({ items: [], partial: false }))
  28. const prevFlatOutlineRef = useRef<FlatOutlineState>(undefined)
  29. // when the flat outline changes, calculate the nested outline
  30. // TODO: only calculate when outlineExpanded is true
  31. useEffect(() => {
  32. const prevFlatOutline = prevFlatOutlineRef.current
  33. prevFlatOutlineRef.current = flatOutline
  34. if (flatOutline) {
  35. if (outlineChanged(prevFlatOutline?.items, flatOutline.items)) {
  36. debugConsole.log('Rebuilding changed outline')
  37. setOutline({
  38. items: nestOutline(flatOutline.items),
  39. partial: flatOutline.partial,
  40. })
  41. }
  42. } else {
  43. setOutline({ items: [], partial: false })
  44. }
  45. }, [flatOutline])
  46. return (
  47. <div className="outline-container">
  48. <OutlinePane
  49. outline={outline.items}
  50. onToggle={outlineToggledEmitter}
  51. isTexFile={canShowOutline}
  52. jumpToLine={jumpToLine}
  53. highlightedLine={highlightedLine}
  54. isPartial={outline.partial}
  55. expanded={outlineExpanded}
  56. toggleExpanded={toggleOutlineExpanded}
  57. />
  58. </div>
  59. )
  60. })
  61. OutlineContainer.displayName = 'OutlineContainer'
  62. const outlineChanged = (
  63. a: PartialFlatOutline | undefined,
  64. b: PartialFlatOutline
  65. ): boolean => {
  66. if (!a) {
  67. return true
  68. }
  69. if (a.length !== b.length) {
  70. return true
  71. }
  72. for (let i = 0; i < a.length; i++) {
  73. const aItem = a[i]
  74. const bItem = b[i]
  75. if (
  76. aItem.level !== bItem.level ||
  77. aItem.line !== bItem.line ||
  78. aItem.title !== bItem.title
  79. ) {
  80. return true
  81. }
  82. }
  83. return false
  84. }