Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

17.1 KB
Raw Blame
import '../PdfViewer/pdf_viewer.css';

import type { PDFViewer } from '@block-pdf/PdfViewer';
import { ZOOM_MAX, ZOOM_MIN } from '@block-pdf/PdfViewer/zoom';
import { useGoToLocationHash } from '@block-pdf/signal/tab';
import { usePdfCommentEffects } from '@block-pdf/store/comments/commentEffect';
import { getPdfPageRect } from '@block-pdf/util/pdfjsUtils';
import {
  extractSelectionText,
  isMultiPageSelection,
  useResetSelection,
} from '@block-pdf/util/selectionUtils';
import { LoadingSpinner } from '@core/component/LoadingSpinner';
import {
  ENABLE_PDF_LOCATION_AUTOSAVE,
  ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE,
} from '@core/constant/featureFlags';
import { IS_MAC } from '@core/constant/isMac';
import { observedSize } from '@core/directive/observedSize';
import { fireAndForget } from '@core/util/fireAndForget';
import { isInDOMRect } from '@core/util/rect';
import { Telemetry } from '@macro-inc/observability';
import { createCallback } from '@solid-primitives/rootless';
import { debounce } from '@solid-primitives/scheduled';
import { cn } from '@ui';
import {
  batch,
  createDeferred,
  createEffect,
  createMemo,
  createRenderEffect,
  createSignal,
  For,
  type JSX,
  on,
  onCleanup,
  onMount,
  Show,
  untrack,
} from 'solid-js';
import { Portal } from 'solid-js/web';
import { usePdfComments } from '../context/pdf-comments-context';
import { usePdfDocument } from '../context/pdf-document-context';
import { usePdfViewer } from '../context/pdf-viewer-context';
import { PageModel } from '../model/Page';
import {
  initializePdfViewer,
  useIsPopup,
  ViewerPopupProvider,
} from '../signal/pdfViewer';
import { usePdfSaveLocation, useSaveModificationData } from '../signal/save';
import { useLoadAnnotations } from '../store/annotations';
import { useSetSelectionHighlights } from '../store/highlight';
import { PayloadMode } from '../type/placeables';
import { type IPageOverlayProps, PageOverlay } from './PageOverlay';
import { RightMarginLayout } from './RightMarginLayout';
import { SimpleSearch } from './SimpleSearch';

false && observedSize;

const CSS = 96.0;
const PDF = 72.0;
const PDF_TO_CSS_UNITS = CSS / PDF;

function InnerDocument() {
  const pdfViewer = usePdfViewer();
  const isPopup = useIsPopup();
  const viewer = isPopup ? pdfViewer.popup : pdfViewer.root;
  const getViewer = viewer.instance;

  const goToLocationHash = useGoToLocationHash();

  // TODO (seamus) : Chatted with Rithy. Manual cleanup should not be
  // needed here, but currently a new 'openInNewTab' subscriber is created
  // everytime we nevigate from pdf block -> pdf block without old ones being
  // removed.
  let cleanupNewTabHandler: () => void = () => {};
  createEffect(() => {
    const viewer = getViewer();
    if (!viewer) return;
    cleanupNewTabHandler = viewer.handlePDFEvent('openNewTab', (event) => {
      goToLocationHash(event.locationHash, true);
    });
  });

  onCleanup(() => {
    cleanupNewTabHandler();
    cleanupNewTabHandler = () => {};
  });

  createEffect(() => {
    const overlays = pdfViewer.overlays();
    if (!overlays || overlays.length === 0) return;
    getViewer()?.setOverlays(overlays);
  });

  if (!isPopup) {
    usePdfCommentEffects();
  }
  const showOverlays = createMemo(
    () => (isPopup ? pdfViewer.isPopupOpen() : true) && pdfViewer.root.isReady()
  );
  const overlayViewsChanged = isPopup
    ? pdfViewer.popup.overlayViews
    : pdfViewer.root.overlayViews;

  const pageOverlays = () => {
    const pageViews = createMemo<IPageOverlayProps[]>(
      (prev) => {
        const event = overlayViewsChanged();
        if (!event) return [];

        const newPageViews: IPageOverlayProps[] = [];
        event.views.forEach((view) => {
          const pageIndex = view.id - 1;
          const cachedPageView = prev[pageIndex];
          const pageViewDiv = view.div;
          const viewport = view.textLayer?.viewport ?? view.viewport;

          if (
            cachedPageView &&
            cachedPageView.pageViewDiv === pageViewDiv &&
            cachedPageView.viewport === viewport
          ) {
            newPageViews[pageIndex] = cachedPageView;
            return;
          }

          newPageViews[pageIndex] = {
            pageIndex,
            pageViewDiv,
            viewport,
          };
        });

        return newPageViews;
      },
      [],
      { equals: false }
    );

    return (
      <For each={pageViews()}>
        {(pageView) => {
          if (!pageView) return '';
          const { pageIndex, pageViewDiv, viewport } = pageView;
          const container = getViewer()?.pageOverlayContainersByPage[pageIndex];
          if (!container) return '';

          return (
            <>
              <Portal mount={container}>
                <PageOverlay
                  pageIndex={pageIndex}
                  viewport={viewport}
                  pageViewDiv={pageViewDiv}
                />
              </Portal>
              <Show when={!isPopup}>
                <Portal mount={container}>
                  <RightMarginLayout pageIndex={pageIndex} />
                </Portal>
              </Show>
            </>
          );
        }}
      </For>
    );
  };

  return <Show when={showOverlays()}>{pageOverlays()}</Show>;
}

function LoadingDocumentSpinnerEffect() {
  const hasVisiblePages = usePdfViewer().root.hasVisiblePages;
  return (
    <Show when={!hasVisiblePages()}>
      <div class="flex absolute size-full z-viewer-document-loading-spinner">
        <div class="absolute top-1/2 left-1/2 transform -translate-1/2">
          <LoadingSpinner />
        </div>
      </div>
    </Show>
  );
}

export function Document() {
  const pdf = usePdfDocument();
  const pdfViewer = usePdfViewer();
  const comments = usePdfComments();
  const [documentSize, setDocumentSize] = createSignal<DOMRect>();
  const [documentContainerRef, setDocumentContainerRef] =
    createSignal<HTMLDivElement>();
  const [destroying, setDestroying] = createSignal(false);
  const getRootViewer = pdfViewer.root.instance;
  const getPopupViewer = pdfViewer.popup.instance;
  const disableClick = () =>
    pdf.markup.mode() !== PayloadMode.NoMode || pdfViewer.textSelectionActive();
  const beginViewerTextSelection = () => {
    if (pdfViewer.textSelectionActive()) return;
    batch(() => {
      comments.clearSelectedThread();
      pdfViewer.beginTextSelection();
    });
  };
  const blockElement = pdfViewer.rootElement;

  let rootViewer: PDFViewer | undefined;
  let popupViewer: PDFViewer | undefined;

  createRenderEffect(() => {
    if (destroying()) return;

    if (getRootViewer() || getPopupViewer()) return;

    popupViewer = initializePdfViewer();
    rootViewer = initializePdfViewer(popupViewer);
    pdfViewer.installPair({
      root: rootViewer,
      popup: popupViewer,
    });
  });

  let mountRef: HTMLDivElement | undefined;
  createEffect(() => {
    const blockEl = blockElement();
    if (!blockEl) return;
    const viewer = getRootViewer();
    const size = documentSize();
    if (!size) return;
    if (size.width === 0 || size.height === 0) {
      return;
    }
    if (!mountRef || !viewer || viewer.isMounted) return;
    viewer.mount(mountRef, blockEl);
  });

  onCleanup(() => {
    setDestroying(true);

    if (!rootViewer) {
      console.warn('unable to detach viewer listeners');
      return;
    }

    pdfViewer.detachListeners();

    rootViewer
      .destroy()
      .then(() => {})
      .finally(() => {
        popupViewer = undefined;
        rootViewer = undefined;
        pdfViewer.clearPair();
        setDestroying(false);
      })
      .catch((error) => Telemetry.error(error, { surface: 'pdf-document' }));
  });

  const saveModificationData = useSaveModificationData();
  const canSaveModificationData = pdf.permissions.canEdit;

  const loadAnnotations = useLoadAnnotations();
  const updateModificationDataOnLoad = () =>
    canSaveModificationData() && !pdf.model.hasServerSnapshot();

  createEffect((prevDocumentId) => {
    const rootPdfViewer = getRootViewer();
    const popupPdfViewer = getPopupViewer();
    if (!rootPdfViewer || !popupPdfViewer) return;

    const documentProxy = pdf.documentProxy();

    if (documentProxy) {
      const annotationsPromise = loadAnnotations(documentProxy);

      if (updateModificationDataOnLoad()) {
        annotationsPromise
          .then(() => saveModificationData())
          .catch((error) =>
            Telemetry.error(error, { surface: 'pdf-document' })
          );
      }

      const documentId = pdf.documentId();
      if (documentId === prevDocumentId) return documentId;

      rootPdfViewer.load(documentProxy);
      popupPdfViewer.load(documentProxy);

      return documentId;
    }

    return prevDocumentId;
  });

  const resetSelection = useResetSelection();
  const setSelectionHighlights = useSetSelectionHighlights();

  const invalidSelection = (selection: Selection) =>
    selection.type !== 'Range' ||
    selection.isCollapsed ||
    !selection.anchorNode ||
    !selection.getRangeAt(0) ||
    selection.getRangeAt(0).collapsed;

  const isPopupOpen = pdfViewer.isPopupOpen;

  const handleSelection = async (selection: Selection, pageIndex: number) => {
    const viewer = getRootViewer();
    if (!viewer) return;

    if (isPopupOpen() || invalidSelection(selection)) {
      resetSelection(selection);
      return;
    }

    const overlay = viewer.generateOverlayForSelection(pageIndex, selection);
    if (!overlay) {
      resetSelection(selection);
      return;
    }

    const { element, location } = overlay;

    const pageNum = pageIndex + 1;
    const pdfPageRect = getPdfPageRect({ pageNum, viewer });
    const selectionRect = element.getBoundingClientRect();
    if (
      !pdfPageRect ||
      !isInDOMRect(
        pdfPageRect,
        selectionRect.x + selectionRect.width / 2,
        selectionRect.y + selectionRect.height / 2
      )
    ) {
      resetSelection(selection);
      return;
    }

    const selectionString = selection.toString();
    if (selectionString.trim().length === 0) {
      pdf.setShareLocation(undefined);
      return;
    }

    pdf.setShareLocation({
      type: 'precise',
      pageIndex: pageIndex + 1,
      ...location,
    });

    setSelectionHighlights(selection);

    pdf.openSelectionMenu({ pageIndex, element });
  };

  const selectionHandler: JSX.EventHandler<
    HTMLDivElement,
    MouseEvent | TouchEvent
  > = createCallback((e) => {
    pdfViewer.endTextSelection();

    if (!(e.target instanceof HTMLElement)) return;

    const sel = document.getSelection();
    if (!sel) return;

    const pageIndex = PageModel.getPageIndex(e.target);
    if (typeof pageIndex !== 'number') return;

    // Selection operations need to be delayed to avoid race conditions
    setTimeout(() => handleSelection(sel, pageIndex));
  });

  const onCopy = async (e: ClipboardEvent) => {
    e.preventDefault();
    e.stopPropagation();

    const selection = window.getSelection();

    if (selection) {
      let text: string = isMultiPageSelection(selection)
        ? extractSelectionText(selection)
        : selection.toString();
      await navigator.clipboard.writeText(text);
    }
  };

  const selectionChangeHandler = () => {
    const sel = document.getSelection();
    if (!sel || invalidSelection(sel)) {
      resetSelection();
    }
  };

  const zoomHandler = createCallback((e: KeyboardEvent) => {
    if (IS_MAC ? !e.metaKey : !e.ctrlKey) return;
    const viewer = getRootViewer();
    if (!viewer) return;

    switch (e.key) {
      case '+':
      case '=':
        e.preventDefault();
        if (pdfViewer.root.canZoomIn()) viewer.zoomIn();
        break;
      case '_':
      case '-':
        e.preventDefault();
        if (pdfViewer.root.canZoomOut()) viewer.zoomOut();
        break;
      case 'PageUp':
      case 'ArrowLeft':
        e.preventDefault();
        viewer.previousPage();
        break;
      case 'PageDown':
      case 'ArrowRight':
        e.preventDefault();
        viewer.nextPage();
        break;
    }
  });

  onMount(() => {
    if (pdf.isNested()) return;

    blockElement()?.addEventListener('selectionchange', selectionChangeHandler);
    onCleanup(() => {
      blockElement()?.removeEventListener(
        'selectionchange',
        selectionChangeHandler
      );
    });
  });

  createEffect(() => {
    if (pdf.isNested()) return;

    const element = blockElement();
    if (!element) return;

    element.addEventListener('copy', onCopy);
    element.addEventListener('keydown', zoomHandler);

    onCleanup(() => {
      element.removeEventListener('copy', onCopy);
      element.removeEventListener('keydown', zoomHandler);
    });
  });

  const [mouseDown, setMouseDown] = createSignal(false);
  createEffect(() => {
    if (pdf.isNested()) return;

    const element = documentContainerRef();
    if (!element) return;

    const mouseDownHandler = () => {
      setMouseDown(true);
    };

    const setMouseUp = () => {
      pdfViewer.endTextSelection();
      setMouseDown(false);
    };

    const selectStartHandler = () => {
      if (!mouseDown()) return;
      beginViewerTextSelection();
    };

    element.addEventListener('mousedown', mouseDownHandler);
    element.addEventListener('mousemove', selectStartHandler);
    blockElement()?.addEventListener('mouseup', setMouseUp);

    onCleanup(() => {
      element.removeEventListener('mousedown', mouseDownHandler);
      element.removeEventListener('mousemove', selectStartHandler);
      blockElement()?.removeEventListener('mouseup', setMouseUp);
    });
  });

  const [initialized, setInitialized] = createSignal(false);
  createEffect(
    on(
      documentSize,
      (currentSize, prevSize) => {
        const viewer = getRootViewer();
        if (
          !viewer ||
          !initialized() ||
          !currentSize ||
          !prevSize ||
          currentSize.width === 0 ||
          prevSize.width === 0
        )
          return;

        const currentPage = pdfViewer.root.currentPageNumber();
        const pdfDimensions = viewer.pageViewport(currentPage);
        if (!pdfDimensions) return;

        const ratio = pdfDimensions.width / prevSize.width;
        const { pageWidth, width } = pdfDimensions;
        let zoomScale =
          (currentSize.width / (pageWidth * PDF_TO_CSS_UNITS)) * ratio;
        if (
          currentSize.width > width + 30 &&
          currentSize.width < prevSize.width
        ) {
          return;
        } else if (currentSize.width < prevSize.width) {
          zoomScale = (currentSize.width - 30) / (pageWidth * PDF_TO_CSS_UNITS);
        }

        if (prevSize.width > 1000 && currentSize.width > prevSize.width) return;

        let fitWidthScale = Math.max(Math.min(zoomScale, ZOOM_MAX), ZOOM_MIN);

        // Huh? (seamus) – reduce the precision of this ratio to prevent it from
        // being treated as a to string somewhere in pdf.js internals. Without
        // this, viewer.location.scale is a string after this call is directed
        // to _viewer._setScale() as a number.
        fitWidthScale = Math.floor(fitWidthScale * 10e5) / 10e5;
        viewer.zoomReset(fitWidthScale, false);
      },
      { defer: true }
    )
  );

  if (ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE && !pdf.isNested()) {
    const isSaving = createDeferred(pdf.persistence.isSaving);
    const currentRevision = createDeferred(pdf.model.revision);
    const [savedRevision, setSavedRevision] = createSignal(0);
    createEffect(() => {
      if (isSaving()) return;

      const revision = currentRevision();
      if (revision <= savedRevision()) return;

      fireAndForget(
        saveModificationData().then(() => setSavedRevision(revision)),
        'pdf-document'
      );
    });
  }

  // TODO: hacky location autosave that works on page refresh
  // without requiring a confirm dialog
  if (ENABLE_PDF_LOCATION_AUTOSAVE && !pdf.isNested()) {
    const isSaving = createDeferred(pdf.persistence.isSaving);
    const viewChanged = createDeferred(pdfViewer.root.viewArea);
    const saveLocation = usePdfSaveLocation();
    const debouncedSaveLocation = debounce(saveLocation, 1000);

    createEffect(() => {
      viewChanged();

      if (untrack(isSaving)) return;

      debouncedSaveLocation();
    });
  }

  return (
    <>
      <Show when={!pdf.isNested()}>
        <div class="absolute top-4 right-4 z-simple-search">
          <SimpleSearch />
        </div>
      </Show>
      <LoadingDocumentSpinnerEffect />
      <ViewerPopupProvider>
        <div
          use:observedSize={{
            setSize: setDocumentSize,
            setInitialized: setInitialized,
          }}
          class={cn(
            'size-full relative outline-none',
            disableClick() && 'noClickParse'
          )}
          ref={(ref) => {
            mountRef = ref;
            setDocumentContainerRef(ref);
          }}
          onMouseUp={selectionHandler}
          onTouchEnd={selectionHandler}
        >
          This is where the document should go!
        </div>
        <InnerDocument />
        <Show when={!pdf.isNested()}>
          <ViewerPopupProvider isPopup>
            <InnerDocument />
          </ViewerPopupProvider>
        </Show>
      </ViewerPopupProvider>
    </>
  );
}

export default Document;

if (import.meta.hot) {
  import('./PageOverlay').catch((error) =>
    Telemetry.error(error, { surface: 'pdf-document' })
  );
}