use-log-events.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { useCallback } from 'react'
  2. import { useLayoutContext } from '@/shared/context/layout-context'
  3. import { useEditorContext } from '@/shared/context/editor-context'
  4. import useEventListener from '@/shared/hooks/use-event-listener'
  5. function scrollIntoView(element: Element) {
  6. setTimeout(() => {
  7. element.scrollIntoView({
  8. block: 'start',
  9. inline: 'nearest',
  10. })
  11. })
  12. }
  13. /**
  14. * This hook adds an event listener for events dispatched from the editor to the compile logs pane
  15. */
  16. export const useLogEvents = (setShowLogs: (show: boolean) => void) => {
  17. const { pdfLayout, setView } = useLayoutContext()
  18. const { hasSuggestionsLeft } = useEditorContext()
  19. const selectLogNewLogs = useCallback(
  20. (
  21. id: string,
  22. suggestFix: boolean,
  23. showPaywallIfOutOfSuggestions: boolean
  24. ) => {
  25. window.setTimeout(() => {
  26. const logEntry = document.querySelector(
  27. `.log-entry[data-log-entry-id="${id}"]`
  28. )
  29. if (logEntry) {
  30. scrollIntoView(logEntry)
  31. const expandCollapseButton = logEntry.querySelector<HTMLElement>(
  32. '[data-action="expand-collapse"]'
  33. )
  34. const collapsed = expandCollapseButton?.dataset.collapsed === 'true'
  35. if (collapsed) {
  36. expandCollapseButton.click()
  37. }
  38. if (suggestFix) {
  39. if (hasSuggestionsLeft) {
  40. logEntry
  41. .querySelector<HTMLButtonElement>(
  42. 'button[data-action="suggest-fix"]'
  43. )
  44. ?.click()
  45. } else if (showPaywallIfOutOfSuggestions) {
  46. window.dispatchEvent(
  47. new CustomEvent('aiAssist:showPaywall', {
  48. detail: { origin: 'suggest-fix' },
  49. })
  50. )
  51. }
  52. }
  53. }
  54. })
  55. },
  56. [hasSuggestionsLeft]
  57. )
  58. const openLogs = useCallback(() => {
  59. setShowLogs(true)
  60. if (pdfLayout === 'flat') {
  61. setView('pdf')
  62. }
  63. }, [pdfLayout, setView, setShowLogs])
  64. const handleViewCompileLogEntryEvent = useCallback(
  65. (event: Event) => {
  66. const { id, suggestFix, showPaywallIfOutOfSuggestions } = (
  67. event as CustomEvent<{
  68. id: string
  69. suggestFix?: boolean
  70. showPaywallIfOutOfSuggestions?: boolean
  71. }>
  72. ).detail
  73. openLogs()
  74. selectLogNewLogs(
  75. id,
  76. Boolean(suggestFix),
  77. Boolean(showPaywallIfOutOfSuggestions)
  78. )
  79. },
  80. [openLogs, selectLogNewLogs]
  81. )
  82. useEventListener(
  83. 'editor:view-compile-log-entry',
  84. handleViewCompileLogEntryEvent
  85. )
  86. }