use-log-events.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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. (id: string, suggestFix: boolean) => {
  21. window.setTimeout(() => {
  22. const logEntry = document.querySelector(
  23. `.log-entry[data-log-entry-id="${id}"]`
  24. )
  25. if (logEntry) {
  26. scrollIntoView(logEntry)
  27. const expandCollapseButton = logEntry.querySelector<HTMLElement>(
  28. '[data-action="expand-collapse"]'
  29. )
  30. const collapsed = expandCollapseButton?.dataset.collapsed === 'true'
  31. if (collapsed) {
  32. expandCollapseButton.click()
  33. }
  34. if (suggestFix) {
  35. if (hasSuggestionsLeft) {
  36. logEntry
  37. .querySelector<HTMLButtonElement>(
  38. 'button[data-action="suggest-fix"]'
  39. )
  40. ?.click()
  41. } else {
  42. window.dispatchEvent(
  43. new CustomEvent('aiAssist:showPaywall', {
  44. detail: { origin: 'suggest-fix' },
  45. })
  46. )
  47. }
  48. }
  49. }
  50. })
  51. },
  52. [hasSuggestionsLeft]
  53. )
  54. const openLogs = useCallback(() => {
  55. setShowLogs(true)
  56. if (pdfLayout === 'flat') {
  57. setView('pdf')
  58. }
  59. }, [pdfLayout, setView, setShowLogs])
  60. const handleViewCompileLogEntryEvent = useCallback(
  61. (event: Event) => {
  62. const { id, suggestFix } = (
  63. event as CustomEvent<{
  64. id: string
  65. suggestFix?: boolean
  66. }>
  67. ).detail
  68. openLogs()
  69. selectLogNewLogs(id, Boolean(suggestFix))
  70. },
  71. [openLogs, selectLogNewLogs]
  72. )
  73. useEventListener(
  74. 'editor:view-compile-log-entry',
  75. handleViewCompileLogEntryEvent
  76. )
  77. }