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.

refactor(web): deblockify PDF viewer (#6539)

dev-rb5436df44ad4e
diff --git a/apps/web/src/features/block-pdf/PdfViewer/TermDataStore.ts b/apps/web/src/features/block-pdf/PdfViewer/TermDataStore.ts
index eee32a0096..75bd411133 100644
--- a/apps/web/src/features/block-pdf/PdfViewer/TermDataStore.ts
+++ b/apps/web/src/features/block-pdf/PdfViewer/TermDataStore.ts
@@ -1,56 +1,15 @@
-import { useBlockId, useBlockOwner } from '@core/block';
-import { type Owner, onCleanup, runWithOwner } from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
import Term from '../model/Term';
import { cleanQuery } from '../util/StringUtils';
import { XMLUtils } from '../util/XMLUtils';
/**
* Returns a singleton instance of TermDataStore per document id
- * @throws if called outside of a block context
+ * @throws if called outside of a PDF document context
*/
-export const keyedTermDataStore = () => {
- const documentId = useBlockId();
- const blockOwner = useBlockOwner();
- if (!blockOwner) {
- throw new Error('term data store has no owner in block context');
- }
-
- const owners = documentIdToOwners.get(documentId);
- if (!owners) {
- documentIdToOwners.set(documentId, new Set([blockOwner]));
- } else {
- owners.add(blockOwner);
- }
-
- // This keeps the singleton TermDataStore alive for the lifetime of the block.
- // If there are multiple block references to the same TermDataStore, it will be
- // garbage collected when the last reference is removed.
- return runWithOwner(blockOwner, () => {
- onCleanup(() => {
- const owners = documentIdToOwners.get(documentId);
- owners?.delete(blockOwner);
-
- if (!owners || owners.size === 0) {
- documentIdToTermDataStore.delete(documentId);
- documentIdToOwners.delete(documentId);
- }
- });
-
- const instance = documentIdToTermDataStore.get(documentId);
- if (instance) {
- return instance;
- }
-
- const store = new TermDataStore();
- documentIdToTermDataStore.set(documentId, store);
- return store;
- });
-};
-
-const documentIdToOwners = new Map<string, Set<Owner>>();
-const documentIdToTermDataStore = new Map<string, TermDataStore>();
+export const keyedTermDataStore = () => usePdfDocument().state.termDataStore;
-class TermDataStore {
+export class TermDataStore {
terms: Term[] = [];
idToTerm: Map<string, Term> = new Map();
allTerms: Term[] = [];
diff --git a/apps/web/src/features/block-pdf/component/Block.tsx b/apps/web/src/features/block-pdf/component/Block.tsx
index 87f29bfaf6..12c8a36bc5 100644
--- a/apps/web/src/features/block-pdf/component/Block.tsx
+++ b/apps/web/src/features/block-pdf/component/Block.tsx
@@ -1,231 +1,116 @@
-import './block.css';
-
import { useBlockEntityCommands } from '@app/features/next-soup/actions';
-import {
- type LocationBlockParams,
- locationChangedSignal,
- pendingLocationParamsSignal,
-} from '@block-pdf/signal/location';
-import { showTabBarSignal } from '@block-pdf/signal/placeables';
import { SidePanel } from '@components/app/side-panel';
-import { useIsNestedBlock } from '@core/block';
+import { blockDataSignalAs, useBlockId, useIsNestedBlock } from '@core/block';
import { DocumentBlockContainer } from '@core/component/DocumentBlockContainer';
import { createMethodRegistration } from '@core/orchestrator';
+import { blockHotkeyScopeSignal } from '@core/signal/blockElement';
import { blockHandleSignal, blockMetadataSignal } from '@core/signal/load';
-import { createCallback } from '@solid-primitives/rootless';
-import { debounce, leading } from '@solid-primitives/scheduled';
-import { type BeforeLeaveEventArgs, useBeforeLeave } from '@solidjs/router';
-import {
- createEffect,
- createResource,
- onCleanup,
- onMount,
- Show,
-} from 'solid-js';
-import { reconcile } from 'solid-js/store';
-import { fromZodError } from 'zod-validation-error';
-import { keyedTermDataStore } from '../PdfViewer/TermDataStore';
-import {
- pdfDocumentProxy,
- pdfModificationDataStore,
- pdfOverlays,
- pdfViewLocation,
-} from '../signal/document';
-import { pdfBlockDataSignal } from '../signal/pdfBlockData';
-import {
- isSaving as isSavingSignal,
- serverModificationDataSignal,
- usePdfSave,
-} from '../signal/save';
-import { useUpdateColorsEffect } from '../signal/setting';
-import { useTableOfContentsUpdate } from '../store/tableOfContents';
import {
- IModificationDataOnServerSchema,
- transformModificationDataToClient,
-} from '../type/coParse';
-import { preprocess } from '../websocket/preprocess';
-import { Document } from './Document';
+ useCanComment,
+ useCanEdit,
+ useIsDocumentOwner,
+} from '@core/signal/permissions';
+import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
+import { useSearchParams } from '@solidjs/router';
+import { Show } from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
+import type { PdfBlockData } from '../definition';
+import { type LocationSearchParams, URL_PARAMS } from '../signal/location';
import { ModalsProvider } from './ModalsProvider';
+import {
+ PdfDocument,
+ PdfDocumentContent,
+ type PdfDocumentMethods,
+} from './PdfDocument';
import { PdfSidePanelSections } from './sidepanel/PdfSidePanelSections';
import { Tabs } from './Tabs';
import { TopBar } from './TopBar';
-function onKeyPress(e: KeyboardEvent) {
- if (
- (e.key.toLowerCase() === 's' || e.key === 'z') &&
- // TODO: This is deprecated be careful of updates as this may break
- (navigator.platform.includes('Mac') ? e.metaKey : e.ctrlKey)
- ) {
- e.preventDefault();
- }
- if (
- e.key === 'p' &&
- (navigator.platform.includes('Mac') ? e.metaKey : e.ctrlKey)
- ) {
- e.preventDefault();
- }
-}
-
export default function BlockPdf() {
useBlockEntityCommands();
- const isNestedBlock = useIsNestedBlock();
- const showTabBar = showTabBarSignal.get;
-
- const setPdfDocumentProxy = pdfDocumentProxy.set;
- const setPdfViewLocation = pdfViewLocation.set;
-
- const setPdfModificationData = pdfModificationDataStore.set;
- const setServerModificationData = serverModificationDataSignal.set;
-
- createEffect(async () => {
- const blockData = pdfBlockDataSignal();
- if (!blockData) return;
-
- setPdfDocumentProxy(blockData.documentProxy);
- setPdfViewLocation(isNestedBlock ? undefined : blockData.viewLocation);
-
- const modificationData = blockData.documentMetadata.modificationData;
- if (!modificationData) return;
-
- const parsedModificationData =
- IModificationDataOnServerSchema.safeParse(modificationData);
- if (parsedModificationData.success) {
- const serverModificationData = parsedModificationData.data;
- setServerModificationData(serverModificationData);
-
- const transformedModificationData = transformModificationDataToClient(
- serverModificationData
- );
- setPdfModificationData(reconcile(transformedModificationData));
- } else {
- console.error(
- 'Failed to parse modification data',
- fromZodError(parsedModificationData.error)
- );
- }
- });
-
- const [preprocessResource] = createResource(() => {
- const metadata = blockMetadataSignal();
- if (!metadata) return;
- const { documentId, documentVersionId } = metadata;
-
- return { documentId, documentVersionId };
- }, preprocess);
- const tableOfContentsDispatch = useTableOfContentsUpdate();
- const setPdfOverlays = pdfOverlays.set;
- createEffect(() => {
- const error = preprocessResource.error;
- if (error) return;
-
- const coparse = preprocessResource.latest;
- if (!coparse) return;
-
- const store = keyedTermDataStore();
- store?.load(coparse.defs ?? '');
- tableOfContentsDispatch({ type: 'LOAD_AI_TOC', coparse });
- setPdfOverlays(coparse.overlays);
- });
-
- const savePdf = usePdfSave();
- // use before leave is being called twice
- const debouncedSave = leading(
- debounce,
- (e: BeforeLeaveEventArgs) => {
- e.preventDefault();
- savePdf().then(() => e.retry(true));
- },
- 500
- );
-
- useBeforeLeave((e) => {
- if (isNestedBlock) return;
- debouncedSave(e);
- });
-
- const isSaving = isSavingSignal.get;
- let beforeUnloadHandler = (e: Event) => {
- if (isNestedBlock) return;
- if (isSaving()) {
- e.preventDefault();
- }
- };
-
- // used to keep the appearance color synced across tabs
- useUpdateColorsEffect();
-
- onMount(() => {
- if (isNestedBlock) return;
- window.addEventListener('keydown', onKeyPress);
- window.addEventListener('beforeunload', beforeUnloadHandler);
- onCleanup(() => {
- window.removeEventListener('keydown', onKeyPress);
- window.removeEventListener('beforeunload', beforeUnloadHandler);
- });
- });
+ const documentId = useBlockId();
+ const isNested = useIsNestedBlock();
+ const metadata = blockMetadataSignal.get;
+ const documentName = useBlockDocumentName('Unknown Filename');
+ const canComment = useCanComment();
+ const canEdit = useCanEdit();
+ const isOwner = useIsDocumentOwner();
+ const [searchParams] = useSearchParams();
const blockHandle = blockHandleSignal.get;
+ const data = blockDataSignalAs<PdfBlockData>('pdf');
- const setPendingLocationParamsSignal = pendingLocationParamsSignal.set;
- const setLocationChanged = locationChangedSignal.set;
- const goToLocationFromParams = createCallback(
- (params: LocationBlockParams) => {
- console.log('GO TO LOCATION FROM PARAMS', params);
-
- setLocationChanged(true);
+ const registerMethods = (methods: Partial<PdfDocumentMethods>) =>
+ createMethodRegistration(blockHandle, methods);
- // Note: structuredClone was failing here due to proxy nonsense.
- setPendingLocationParamsSignal(JSON.parse(JSON.stringify(params)));
- }
+ return (
+ <DocumentBlockContainer>
+ <PdfDocument
+ documentId={documentId}
+ documentVersionId={metadata()?.documentVersionId}
+ documentName={documentName()}
+ documentProxy={data()?.documentProxy}
+ viewLocation={data()?.viewLocation}
+ modificationData={data()?.documentMetadata.modificationData}
+ isNested={isNested}
+ hotkeyScope={blockHotkeyScopeSignal.get()}
+ portalScope="block"
+ permissions={{
+ canComment: canComment(),
+ canEdit: canEdit(),
+ isOwner: isOwner(),
+ }}
+ locationParams={getLocationParams(searchParams)}
+ registerMethods={registerMethods}
+ >
+ <PdfBlockContent />
+ </PdfDocument>
+ </DocumentBlockContainer>
);
+}
- createMethodRegistration(blockHandle, {
- goToLocationFromParams: async (params: LocationBlockParams) =>
- goToLocationFromParams(params),
- });
+function PdfBlockContent() {
+ const pdf = usePdfDocument();
+ const [showTabBar] = pdf.state.signals.showTabBar;
return (
- <DocumentBlockContainer>
- <div
- class="size-full select-none overscroll-none overflow-hidden flex flex-col"
- onContextMenu={(e) => e.preventDefault()}
- data-tut="App"
- >
- <ModalsProvider>
- <Show
- when={!isNestedBlock}
- fallback={
- <div
- class="flex size-full relative justify-end overflow-visible z-main-view-layout"
- id="main-view"
- >
- <Document />
- </div>
- }
- >
- <SidePanel.Layout>
- <PdfSidePanelSections />
- <div class="flex size-full min-w-0 flex-col overflow-hidden">
- <TopBar />
- <Show when={showTabBar()}>
- <div class="flex px-2 justify-between min-h-11 items-center gap-2">
- <div class="overflow-x-auto overflow-y-hidden grow customScrollbar w-0">
- <Tabs />
- </div>
- </div>
- </Show>
- <div
- class="flex size-full relative justify-end overflow-visible z-main-view-layout"
- id="main-view"
- >
- {/* {ENABLE_VIEWER_SIDE_PANEL && <ViewerNavStack />} */}
- <Document />
- {/* <CustomCursor /> */}
+ <ModalsProvider>
+ <Show when={!pdf.isNested()} fallback={<PdfDocumentContent />}>
+ <SidePanel.Layout>
+ <PdfSidePanelSections />
+ <div class="flex size-full min-w-0 flex-col overflow-hidden">
+ <TopBar />
+ <Show when={showTabBar()}>
+ <div class="flex px-2 justify-between min-h-11 items-center gap-2">
+ <div class="overflow-x-auto overflow-y-hidden grow customScrollbar w-0">
+ <Tabs />
</div>
</div>
- </SidePanel.Layout>
- </Show>
- </ModalsProvider>
- </div>
- </DocumentBlockContainer>
+ </Show>
+ <PdfDocumentContent />
+ </div>
+ </SidePanel.Layout>
+ </Show>
+ </ModalsProvider>
);
}
+
+function getLocationParams(
+ params: Partial<Record<string, string | string[] | undefined>>
+): LocationSearchParams {
+ const value = (key: string) => {
+ const param = params[key];
+ return Array.isArray(param) ? param[0] : param;
+ };
+ return {
+ annotationId: value(URL_PARAMS.annotationId),
+ searchPage: value(URL_PARAMS.searchPage),
+ searchSnippet: value(URL_PARAMS.searchSnippet),
+ searchRawQuery: value(URL_PARAMS.searchRawQuery),
+ highlightTerms: value(URL_PARAMS.searchHighlightTerms),
+ pageNumber: value(URL_PARAMS.pageNumber),
+ yPos: value(URL_PARAMS.yPos),
+ x: value(URL_PARAMS.x),
+ width: value(URL_PARAMS.width),
+ height: value(URL_PARAMS.height),
+ };
+}
diff --git a/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsx b/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsx
index 3383cc2904..9df5014c49 100644
--- a/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsx
+++ b/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsx
@@ -8,10 +8,11 @@ import {
import { createEffect, createMemo, type JSX, onCleanup, Show } from 'solid-js';
import { createStore, produce } from 'solid-js/store';
import { styled } from 'solid-styled-components';
+import { usePdfDocument } from '../../context/pdf-document-context';
import type Section from '../../model/Section';
import type Term from '../../model/Term';
import { keyedTermDataStore } from '../../PdfViewer/TermDataStore';
-import { popupOpen, useIsPopup } from '../../signal/pdfViewer';
+import { useIsPopup } from '../../signal/pdfViewer';
import { useGoToLocation } from '../../signal/tab';
import { usePopupStore } from '../../store/definitionPopup';
import { useGetIdToSectionMap } from '../../store/tableOfContents';
@@ -109,6 +110,7 @@ export interface IState {
}
export function DefinitionLookup(props: IProps) {
+ const popupOpen = usePdfDocument().state.derived.popupOpen;
const isPopup = useIsPopup();
const getIdToSectionMap = useGetIdToSectionMap();
// popupAtoms => popupStore
diff --git a/apps/web/src/features/block-pdf/component/Document.tsx b/apps/web/src/features/block-pdf/component/Document.tsx
index 4ab20e60d9..e5de87e915 100644
--- a/apps/web/src/features/block-pdf/component/Document.tsx
+++ b/apps/web/src/features/block-pdf/component/Document.tsx
@@ -2,11 +2,6 @@ import '../PdfViewer/pdf_viewer.css';
import type { PDFViewer } from '@block-pdf/PdfViewer';
import { ZOOM_MAX, ZOOM_MIN } from '@block-pdf/PdfViewer/zoom';
-import {
- disableOverlayClickSignal,
- isSelectingViewerTextSignal,
-} from '@block-pdf/signal/click';
-import { useCanEditModificationData } from '@block-pdf/signal/permissions';
import { useGoToLocationHash } from '@block-pdf/signal/tab';
import { usePdfCommentEffects } from '@block-pdf/store/comments/commentEffect';
import { getPdfPageRect } from '@block-pdf/util/pdfjsUtils';
@@ -15,7 +10,6 @@ import {
isMultiPageSelection,
useResetSelection,
} from '@block-pdf/util/selectionUtils';
-import { useIsNestedBlock } from '@core/block';
import { LoadingSpinner } from '@core/component/LoadingSpinner';
import {
ENABLE_PDF_LOCATION_AUTOSAVE,
@@ -23,12 +17,9 @@ import {
} from '@core/constant/featureFlags';
import { IS_MAC } from '@core/constant/isMac';
import { observedSize } from '@core/directive/observedSize';
-import { blockElementSignal } from '@core/signal/blockElement';
-import { blockMetadataSignal } from '@core/signal/load';
import { isInDOMRect } from '@core/util/rect';
import { createCallback } from '@solid-primitives/rootless';
import { debounce } from '@solid-primitives/scheduled';
-import { useSearchParams } from '@solidjs/router';
import { cn } from '@ui';
import {
createDeferred,
@@ -45,48 +36,15 @@ import {
untrack,
} from 'solid-js';
import { Portal } from 'solid-js/web';
+import { usePdfDocument } from '../context/pdf-document-context';
import { PageModel } from '../model/Page';
+import { useGoToLinkLocation } from '../signal/location';
import {
- pdfDocumentProxy,
- pdfModificationDataStore,
- pdfOverlays,
-} from '../signal/document';
-import {
- generalPopupLocationSignal,
- type LocationSearchParams,
- locationChangedSignal,
- URL_PARAMS,
- useGoToLinkLocation,
- useSetLocationStore,
-} from '../signal/location';
-import {
- canZoomIn,
- canZoomOut,
- currentPageNumber,
initializePdfViewer,
- popupOpen,
- useAttachViewerSignals,
- useDetachViewerSignals,
- useGetPopupContextViewer,
- useGetPopupViewer,
- useGetRootViewer,
useIsPopup,
- useOverlayViewsChanged,
- useSetPopupViewer,
- useSetRootViewer,
ViewerPopupProvider,
- viewerHasVisiblePagesSignal,
- viewerReadySignal,
- visiblePagesChangedSignal,
} from '../signal/pdfViewer';
-import {
- isSaving as isSavingSignal,
- modificationDataSaveRequired,
- numOperations,
- serverModificationDataSignal,
- usePdfSaveLocation,
- useSaveModificationData,
-} from '../signal/save';
+import { usePdfSaveLocation, useSaveModificationData } from '../signal/save';
import { useLoadAnnotations } from '../store/annotations';
import { useSetSelectionHighlights } from '../store/highlight';
import { type IPageOverlayProps, PageOverlay } from './PageOverlay';
@@ -99,7 +57,10 @@ const PDF = 72.0;
const PDF_TO_CSS_UNITS = CSS / PDF;
function InnerDocument() {
- const getViewer = useGetPopupContextViewer();
+ const { state } = usePdfDocument();
+ const isPopup = useIsPopup();
+ const getViewer = () =>
+ isPopup ? state.signals.popupViewer[0]() : state.signals.rootViewer[0]();
// attach new tab listeners
const goToLocationHash = useGoToLocationHash();
@@ -124,19 +85,22 @@ function InnerDocument() {
// watch the overlays and send the contents to be rendered by PDFViewer
createEffect(() => {
- const overlays = pdfOverlays();
+ const overlays = state.signals.overlays[0]();
if (!overlays || overlays.length === 0) return;
getViewer()?.setOverlays(overlays);
});
- const isPopup = useIsPopup();
if (!isPopup) {
usePdfCommentEffects();
}
const showOverlays = createMemo(
- () => (isPopup ? popupOpen() : true) && viewerReadySignal()
+ () =>
+ (isPopup ? state.derived.popupOpen() : true) &&
+ state.derived.viewerReady()
);
- const overlayViewsChanged = useOverlayViewsChanged();
+ const overlayViewsChanged = isPopup
+ ? state.signals.overlayViewsChangedPopup[0]
+ : state.signals.overlayViewsChanged[0];
const pageOverlays = () => {
const pageViews = createMemo<IPageOverlayProps[]>(
@@ -201,8 +165,10 @@ function InnerDocument() {
/** Shows the document loading spinner without unloading the PDF Viewer */
function LoadingDocumentSpinnerEffect() {
+ const viewerHasVisiblePages =
+ usePdfDocument().state.signals.viewerHasVisiblePages[0];
return (
- <Show when={!viewerHasVisiblePagesSignal.get()}>
+ <Show when={!viewerHasVisiblePages()}>
<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 />
@@ -212,22 +178,92 @@ function LoadingDocumentSpinnerEffect() {
);
}
-const [destroying, setDestroying] = createSignal(false);
-
export function Document() {
- const isNestedBlock = useIsNestedBlock();
+ const pdf = usePdfDocument();
+ const { signals, stores, derived } = pdf.state;
const [documentSize, setDocumentSize] = createSignal<DOMRect>();
const [documentContainerRef, setDocumentContainerRef] =
createSignal<HTMLDivElement>();
- const setRootViewer = useSetRootViewer();
- const setPopupViewer = useSetPopupViewer();
- const getRootViewer = useGetRootViewer();
- const getPopupViewer = useGetPopupViewer();
- const attachViewerSignals = useAttachViewerSignals();
- const detachViewerSignals = useDetachViewerSignals();
- const disableClick = disableOverlayClickSignal.get;
- const setIsSelecting = isSelectingViewerTextSignal.set;
- const blockElement = blockElementSignal.get;
+ const [destroying, setDestroying] = signals.destroying;
+ const [getRootViewer, setRootViewer] = signals.rootViewer;
+ const [getPopupViewer, setPopupViewer] = signals.popupViewer;
+ const disableClick = signals.disableOverlayClick[0];
+ const setIsSelecting = signals.isSelectingViewerText[1];
+ const blockElement = pdf.rootElement;
+
+ const attachViewerSignals = (viewer: PDFViewer, isPopup: boolean) => {
+ if (isPopup) {
+ viewer.event.on('scalechanging', signals.scaleChangingPopup[1]);
+ viewer.event.on('pagechanging', signals.pageChangingPopup[1]);
+ viewer.event.on(
+ 'overlayViewsChanged',
+ signals.overlayViewsChangedPopup[1]
+ );
+ viewer.event.on('updateviewarea', signals.visiblePagesChangedPopup[1]);
+ return;
+ }
+
+ viewer.event.on('pagesloaded', signals.pagesLoaded[1]);
+ viewer.event.on('scalechanging', signals.scaleChanging[1]);
+ viewer.event.on('pagechanging', signals.pageChanging[1]);
+ viewer.event.on('overlayViewsChanged', signals.overlayViewsChanged[1]);
+ viewer.event.on(
+ 'popupvisibilitychanged',
+ signals.popupVisibilityChanged[1]
+ );
+ viewer.event.on('updateviewarea', signals.visiblePagesChanged[1]);
+ viewer.event.on(
+ 'updatefindcontrolstate',
+ signals.updateFindControlState[1]
+ );
+ viewer.event.on(
+ 'updatefindmatchescount',
+ signals.updateFindMatchesCount[1]
+ );
+ };
+
+ const detachViewerSignals = (viewer: PDFViewer, isPopup: boolean) => {
+ if (isPopup) {
+ viewer.event.off('scalechanging', signals.scaleChangingPopup[1]);
+ viewer.event.off('pagechanging', signals.pageChangingPopup[1]);
+ viewer.event.off(
+ 'overlayViewsChanged',
+ signals.overlayViewsChangedPopup[1]
+ );
+ viewer.event.off('updateviewarea', signals.visiblePagesChangedPopup[1]);
+ signals.scaleChangingPopup[1](undefined);
+ signals.pageChangingPopup[1](undefined);
+ signals.overlayViewsChangedPopup[1](undefined);
+ signals.visiblePagesChangedPopup[1](undefined);
+ return;
+ }
+
+ viewer.event.off('pagesloaded', signals.pagesLoaded[1]);
+ viewer.event.off('scalechanging', signals.scaleChanging[1]);
+ viewer.event.off('pagechanging', signals.pageChanging[1]);
+ viewer.event.off('overlayViewsChanged', signals.overlayViewsChanged[1]);
+ viewer.event.off(
+ 'popupvisibilitychanged',
+ signals.popupVisibilityChanged[1]
+ );
+ viewer.event.off('updateviewarea', signals.visiblePagesChanged[1]);
+ viewer.event.off(
+ 'updatefindcontrolstate',
+ signals.updateFindControlState[1]
+ );
+ viewer.event.off(
+ 'updatefindmatchescount',
+ signals.updateFindMatchesCount[1]
+ );
+ signals.pagesLoaded[1](undefined);
+ signals.scaleChanging[1](undefined);
+ signals.pageChanging[1](undefined);
+ signals.overlayViewsChanged[1](undefined);
+ signals.popupVisibilityChanged[1](undefined);
+ signals.visiblePagesChanged[1](undefined);
+ signals.updateFindControlState[1](undefined);
+ signals.updateFindMatchesCount[1](undefined);
+ };
let rootViewer: PDFViewer | undefined;
let popupViewer: PDFViewer | undefined;
@@ -286,10 +322,10 @@ export function Document() {
});
const saveModificationData = useSaveModificationData();
- const canSaveModificationData = useCanEditModificationData();
+ const canSaveModificationData = pdf.permissions.canEdit;
const loadAnnotations = useLoadAnnotations();
- const serverModificationData = serverModificationDataSignal.get;
+ const serverModificationData = signals.serverModificationData[0];
const hasServerModificationData = () => !!serverModificationData();
const updateModificationDataOnLoad = () =>
canSaveModificationData() && !hasServerModificationData();
@@ -299,11 +335,10 @@ export function Document() {
const popupPdfViewer = getPopupViewer();
if (!rootPdfViewer || !popupPdfViewer) return;
- const documentProxy = pdfDocumentProxy();
- const documentMetadata = blockMetadataSignal();
- const modificationData = pdfModificationDataStore.get;
+ const documentProxy = signals.documentProxy[0]();
+ const modificationData = stores.modificationData[0];
- if (documentProxy && documentMetadata) {
+ if (documentProxy) {
const annotationsPromise = loadAnnotations(
documentProxy,
modificationData
@@ -313,7 +348,7 @@ export function Document() {
annotationsPromise.then(saveModificationData);
}
- const { documentId } = documentMetadata;
+ const documentId = pdf.documentId();
if (documentId === prevDocumentId) return documentId;
rootPdfViewer.load(documentProxy);
@@ -335,9 +370,9 @@ export function Document() {
!selection.getRangeAt(0) ||
selection.getRangeAt(0).collapsed;
- const isPopupOpen = createMemo(() => popupOpen());
- const setGeneralPopupLocation = generalPopupLocationSignal.set;
- const setLocationStore = useSetLocationStore();
+ const isPopupOpen = createMemo(derived.popupOpen);
+ const setGeneralPopupLocation = signals.generalPopupLocation[1];
+ const setLocationStore = stores.location[1];
const handleSelection = async (selection: Selection, pageIndex: number) => {
const viewer = getRootViewer();
@@ -373,12 +408,15 @@ export function Document() {
const selectionString = selection.toString();
if (selectionString.trim().length === 0) {
+ setLocationStore('annotation', undefined);
setLocationStore('precise', undefined);
return;
}
// let shouldHandleDefinition = isValidTerm(selectionString);
+ setLocationStore('annotation', undefined);
setLocationStore('precise', {
+ type: 'precise',
pageIndex: pageIndex + 1,
...location,
});
@@ -437,12 +475,12 @@ export function Document() {
case '+':
case '=':
e.preventDefault();
- if (canZoomIn()) viewer.zoomIn();
+ if (derived.canZoomIn()) viewer.zoomIn();
break;
case '_':
case '-':
e.preventDefault();
- if (canZoomOut()) viewer.zoomOut();
+ if (derived.canZoomOut()) viewer.zoomOut();
break;
case 'PageUp':
case 'ArrowLeft':
@@ -458,7 +496,7 @@ export function Document() {
});
onMount(() => {
- if (isNestedBlock) return;
+ if (pdf.isNested()) return;
blockElement()?.addEventListener('selectionchange', selectionChangeHandler);
onCleanup(() => {
@@ -470,7 +508,7 @@ export function Document() {
});
createEffect(() => {
- if (isNestedBlock) return;
+ if (pdf.isNested()) return;
const element = blockElement();
if (!element) return;
@@ -486,7 +524,7 @@ export function Document() {
const [mouseDown, setMouseDown] = createSignal(false);
createEffect(() => {
- if (isNestedBlock) return;
+ if (pdf.isNested()) return;
const element = documentContainerRef();
if (!element) return;
@@ -516,27 +554,10 @@ export function Document() {
});
});
- const [searchParams] = useSearchParams();
- const locationSearchParams = () => {
- return {
- annotationId: searchParams[URL_PARAMS.annotationId],
- searchPage: searchParams[URL_PARAMS.searchPage],
- searchSnippet: searchParams[URL_PARAMS.searchSnippet],
- searchRawQuery: searchParams[URL_PARAMS.searchRawQuery],
- highlightTerms: searchParams[URL_PARAMS.searchHighlightTerms],
- pageNumber: searchParams[URL_PARAMS.pageNumber],
- yPos: searchParams[URL_PARAMS.yPos],
- x: searchParams[URL_PARAMS.x],
- width: searchParams[URL_PARAMS.width],
- height: searchParams[URL_PARAMS.height],
- } as LocationSearchParams;
- };
-
const goToLinkLocation = useGoToLinkLocation();
createEffect(() => {
- if (locationChangedSignal() || !viewerReadySignal()) return;
- let params = locationSearchParams();
- goToLinkLocation(params);
+ if (signals.locationChanged[0]() || !derived.viewerReady()) return;
+ goToLinkLocation(pdf.locationParams());
});
const [initialized, setInitialized] = createSignal(false);
@@ -555,7 +576,7 @@ export function Document() {
)
return;
- const currentPage = currentPageNumber() ?? 1;
+ const currentPage = derived.currentPageNumber();
const pdfDimensions = viewer.pageViewport(currentPage);
if (!pdfDimensions) return;
@@ -589,16 +610,17 @@ export function Document() {
createEffect(() => {
setLocationStore('general', {
- pageIndex: currentPageNumber() ?? 1,
+ type: 'general',
+ pageIndex: derived.currentPageNumber(),
y: 0,
});
});
- if (ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE && !isNestedBlock) {
- const isSaving = createDeferred(isSavingSignal);
- const currentOperations = createDeferred(numOperations);
+ if (ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE && !pdf.isNested()) {
+ const isSaving = createDeferred(signals.isSaving[0]);
+ const currentOperations = createDeferred(signals.numOperations[0]);
const [savedOperations, setSavedOperations] = createSignal(0);
- const setSaveRequired = modificationDataSaveRequired.set;
+ const setSaveRequired = signals.modificationDataSaveRequired[1];
createEffect(() => {
if (isSaving()) return;
@@ -617,9 +639,9 @@ export function Document() {
// TODO: hacky location autosave that works on page refresh
// without requiring a confirm dialog
- if (ENABLE_PDF_LOCATION_AUTOSAVE && !isNestedBlock) {
- const isSaving = createDeferred(isSavingSignal);
- const viewChanged = createDeferred(visiblePagesChangedSignal);
+ if (ENABLE_PDF_LOCATION_AUTOSAVE && !pdf.isNested()) {
+ const isSaving = createDeferred(signals.isSaving[0]);
+ const viewChanged = createDeferred(signals.visiblePagesChanged[0]);
const saveLocation = usePdfSaveLocation();
const debouncedSaveLocation = debounce(saveLocation, 1000);
@@ -636,7 +658,7 @@ export function Document() {
return (
<>
- <Show when={!isNestedBlock}>
+ <Show when={!pdf.isNested()}>
<div class="absolute top-4 right-4 z-simple-search">
<SimpleSearch />
</div>
@@ -662,7 +684,7 @@ export function Document() {
This is where the document should go!
</div>
<InnerDocument />
- <Show when={!isNestedBlock}>
+ <Show when={!pdf.isNested()}>
<ViewerPopupProvider isPopup>
<InnerDocument />
</ViewerPopupProvider>
diff --git a/apps/web/src/features/block-pdf/component/MarkupToolbar.tsx b/apps/web/src/features/block-pdf/component/MarkupToolbar.tsx
index f174df589b..6ce86464bb 100644
--- a/apps/web/src/features/block-pdf/component/MarkupToolbar.tsx
+++ b/apps/web/src/features/block-pdf/component/MarkupToolbar.tsx
@@ -1,14 +1,5 @@
import { useOwnedCommentPlaceableSelector } from '@block-pdf/signal/permissions';
-import {
- activePlaceableIdSignal,
- placeableModeSignal,
-} from '@block-pdf/signal/placeables';
import { isThreadPlaceable } from '@block-pdf/store/comments/freeComments';
-import {
- useCanComment,
- useCanEdit,
- useIsDocumentOwner,
-} from '@core/signal/permissions';
import ChatTeardrop from '@phosphor/chat-teardrop.svg';
import Signature from '@phosphor/signature.svg';
import Textbox from '@phosphor/textbox.svg';
@@ -16,17 +7,18 @@ import Trash from '@phosphor/trash-simple.svg';
import Cancel from '@phosphor/x.svg';
import { Button } from '@ui';
import { createMemo, Show } from 'solid-js';
-import { placeableIdMap, useDeletePlaceable } from '../store/placeables';
+import { usePdfDocument } from '../context/pdf-document-context';
+import { useDeletePlaceable, usePlaceableIdMap } from '../store/placeables';
import { PayloadMode } from '../type/placeables';
export function MarkupToolbar() {
- const canEdit = useCanEdit();
- const canComment = useCanComment();
- const isDocumentOwner = useIsDocumentOwner();
-
- const [mode, setMode] = placeableModeSignal;
-
- const activePlaceableId = activePlaceableIdSignal.get;
+ const pdf = usePdfDocument();
+ const canEdit = pdf.permissions.canEdit;
+ const canComment = pdf.permissions.canComment;
+ const isDocumentOwner = pdf.permissions.isOwner;
+ const [mode, setMode] = pdf.state.signals.placeableMode;
+ const [activePlaceableId] = pdf.state.signals.activePlaceableId;
+ const placeableIdMap = usePlaceableIdMap();
const deletePlaceable = useDeletePlaceable();
const showCancel = () => mode() !== PayloadMode.NoMode;
const ownedCommentSelector = useOwnedCommentPlaceableSelector();
diff --git a/apps/web/src/features/block-pdf/component/PDFPopup.tsx b/apps/web/src/features/block-pdf/component/PDFPopup.tsx
index 79f40dc8c6..51bde34330 100644
--- a/apps/web/src/features/block-pdf/component/PDFPopup.tsx
+++ b/apps/web/src/features/block-pdf/component/PDFPopup.tsx
@@ -1,12 +1,9 @@
import type { IHighlight } from '@block-pdf/model/Highlight';
import { useSplitLayout } from '@components/app/split-layout/layout';
import { useIsAuthenticated } from '@core/auth';
-import { useBlockId } from '@core/block';
import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';
import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';
-import { blockElementSignal } from '@core/signal/blockElement';
import { createMarkdownFile } from '@core/util/create';
-import { useBlockDocumentName } from '@core/util/currentBlockDocumentName';
import CheckIcon from '@phosphor-icons/core/bold/check-bold.svg?component-solid';
import ClipboardIcon from '@phosphor-icons/core/bold/clipboard-bold.svg?component-solid';
import NotesIcon from '@phosphor-icons/core/bold/file-md-bold.svg?component-solid';
@@ -29,10 +26,7 @@ import {
Show,
Switch,
} from 'solid-js';
-import {
- PDFPopupCompletionSignal,
- PDFPopupSelectedTextSignal,
-} from './PageOverlay';
+import { usePdfDocument } from '../context/pdf-document-context';
type PDFPopupProps = {
highlightProps: {
@@ -88,8 +82,10 @@ function LoadingContent(props: { lines: number }) {
export function PDFPopup(props: PDFPopupProps) {
const _isAuthenticated = useIsAuthenticated();
- const blockId = useBlockId();
- const [completion, _setCompletion] = PDFPopupCompletionSignal;
+ const pdf = usePdfDocument();
+ const blockId = pdf.documentId();
+ const [completion] = pdf.state.signals.popupCompletion;
+ const [selectedText, setSelectedText] = pdf.state.signals.popupSelectedText;
const isGenerating = () => completion()?.status !== 'completed';
const [copied, setCopied] = createSignal(false);
@@ -103,12 +99,12 @@ export function PDFPopup(props: PDFPopupProps) {
createEffect(() => {
const currentSelection = window.getSelection()?.toString();
if (currentSelection && currentSelection.length > 0) {
- PDFPopupSelectedTextSignal.set(currentSelection);
+ setSelectedText(currentSelection);
}
});
const _selectedText = createMemo(() => {
- const currentSelection = PDFPopupSelectedTextSignal();
+ const currentSelection = selectedText();
if (currentSelection && currentSelection.length > 0) {
return currentSelection;
}
@@ -153,7 +149,6 @@ export function PDFPopup(props: PDFPopupProps) {
}
};
- const name = useBlockDocumentName();
const handleEditInMarkdown = createCallback(async () => {
setIsLoading(true);
const content = completion()?.content;
@@ -164,7 +159,7 @@ export function PDFPopup(props: PDFPopupProps) {
const title = await generateTitle(content);
const documentId = await createMarkdownFile({
content,
- title: title ?? `${name()} - AI Explanation`,
+ title: title ?? `${pdf.documentName()} - AI Explanation`,
});
if (!documentId) {
@@ -185,7 +180,7 @@ export function PDFPopup(props: PDFPopupProps) {
e.stopPropagation();
};
- const blockElement = blockElementSignal();
+ const blockElement = pdf.rootElement();
if (blockElement) {
blockElement.addEventListener('selectionchange', handler, {
capture: true,
diff --git a/apps/web/src/features/block-pdf/component/PageNumberInput.tsx b/apps/web/src/features/block-pdf/component/PageNumberInput.tsx
index ccd0c78256..0489a3fda9 100644
--- a/apps/web/src/features/block-pdf/component/PageNumberInput.tsx
+++ b/apps/web/src/features/block-pdf/component/PageNumberInput.tsx
@@ -1,14 +1,11 @@
-import { blockElementSignal } from '@core/signal/blockElement';
import { createCallback } from '@solid-primitives/rootless';
import { cn } from '@ui';
import { createEffect, createSignal, onCleanup, Show } from 'solid-js';
-import {
- pageCount,
- useCurrentPageNumber,
- useGetRootViewer,
-} from '../signal/pdfViewer';
+import { usePdfDocument } from '../context/pdf-document-context';
+import { useCurrentPageNumber, useGetRootViewer } from '../signal/pdfViewer';
export function PageNumberInput() {
+ const pdf = usePdfDocument();
// const context = useContext(BarContext);
// if (!context) throw new Error('PageNumberInput must be used within a Bar');
// const truncation = context.truncation;
@@ -19,7 +16,7 @@ export function PageNumberInput() {
const [intermediateVal, setIntermediate] = createSignal<string>('');
const inputValue = () => intermediateVal() || currentPageNumber();
- const getPageCount = () => pageCount() ?? 1;
+ const getPageCount = () => pdf.state.derived.pageCount() ?? 1;
const getWidthClass = (value: number | string) => {
const strLength = value.toString().length;
@@ -46,9 +43,8 @@ export function PageNumberInput() {
}
});
- const blockElement = blockElementSignal.get;
createEffect(() => {
- const element = blockElement();
+ const element = pdf.rootElement();
if (!element) return;
element.addEventListener('keydown', handleKeyDown);
diff --git a/apps/web/src/features/block-pdf/component/PageOverlay.tsx b/apps/web/src/features/block-pdf/component/PageOverlay.tsx
index 82f0e20f0a..0cf358dd0e 100644
--- a/apps/web/src/features/block-pdf/component/PageOverlay.tsx
+++ b/apps/web/src/features/block-pdf/component/PageOverlay.tsx
@@ -1,37 +1,17 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import { PDFPopup } from '@block-pdf/component/PDFPopup';
import {
- disableOverlayClickSignal,
- disablePageViewClickSignal,
- disableViewerTextSelectionSignal,
-} from '@block-pdf/signal/click';
-import { pdfModificationDataStore } from '@block-pdf/signal/document';
-import {
- useCanEditModificationData,
useOwnedCommentPlaceableSelector,
useOwnedHighlightSelector,
} from '@block-pdf/signal/permissions';
-import {
- activePlaceableIdSignal,
- newPlaceableSignal,
- placeableModeSignal,
-} from '@block-pdf/signal/placeables';
import { useDoEdit } from '@block-pdf/signal/save';
-import {
- activeCommentThreadSignal,
- useIsActiveThreadSelector,
-} from '@block-pdf/store/comments/commentStore';
-import { commentPlaceables } from '@block-pdf/store/comments/freeComments';
+import { useCommentPlaceables } from '@block-pdf/store/comments/freeComments';
import { useCreateHighlightCommentAtSelection } from '@block-pdf/store/comments/highlightComments';
import { useCreatePlaceable } from '@block-pdf/store/placeables';
import { PayloadMode, type PayloadType } from '@block-pdf/type/placeables';
import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';
import { useIsAuthenticated } from '@core/auth';
-import { createBlockSignal, useBlockId, useIsNestedBlock } from '@core/block';
-import type { Completion } from '@core/client/completion';
import { openLoginModal } from '@core/component/TopBar/LoginButton';
-import { blockElementSignal } from '@core/signal/blockElement';
-import { useCanComment, useIsDocumentOwner } from '@core/signal/permissions';
import { cn } from '@ui';
import { detect } from 'detect-browser';
import type { PageViewport } from 'pdfjs-dist';
@@ -46,40 +26,21 @@ import {
onMount,
Show,
} from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
import type { IColor } from '../model/Color';
import { Highlight, HighlightType } from '../model/Highlight';
import { PageModel } from '../model/Page';
import type Term from '../model/Term';
-import { keyedTermDataStore } from '../PdfViewer/TermDataStore';
-import {
- generalPopupLocationSignal,
- LocationType,
- useCreateShareUrl,
-} from '../signal/location';
-import {
- popupOpen,
- useCurrentPageViewport,
- useGetPopupViewer,
- useGetRootViewer,
- useIsPopup,
-} from '../signal/pdfViewer';
+import { LocationType, useCreateShareUrl } from '../signal/location';
+import { useIsPopup } from '../signal/pdfViewer';
import { usePopupContextUpdate, usePopupStore } from '../store/definitionPopup';
-import {
- highlightStore,
- selectionStore,
- useAddNewHighlights,
- useRemoveHighlight,
-} from '../store/highlight';
+import { useAddNewHighlights, useRemoveHighlight } from '../store/highlight';
import { useGetIdToSectionMap } from '../store/tableOfContents';
import TocUtils from '../util/TocUtils';
import { AbsoluteDefinitionLookups } from './AbsoluteDefinitionLookups';
import { Placeable } from './Placeable';
import { RightMarginLayout } from './RightMarginLayout';
-import {
- activeHighlightSignal,
- UserHighlight,
- useResetUserHighlights,
-} from './UserHighlight';
+import { UserHighlight, useResetUserHighlights } from './UserHighlight';
export interface IPageOverlayProps {
pageIndex: number;
@@ -100,29 +61,22 @@ export interface IHighlightObj {
isActive: boolean;
}
-export const PDFPopupSelectedTextSignal = createBlockSignal<
- string | undefined
->();
-
-export const PDFPopupCompletionSignal = createBlockSignal<
- Completion | undefined
->();
-
// This is where all the page-specifc overlays should reside, like placeables, etc.
export function PageOverlay(props: IPageOverlayProps) {
const analytics = useAnalytics();
- const isNestedBlock = useIsNestedBlock();
+ const pdf = usePdfDocument();
+ const { signals, stores, derived } = pdf.state;
let pageOverlayRef!: HTMLDivElement;
const pageViewDivProp = () => props.pageViewDiv;
- const modificationPlaceablesAccess = useCanEditModificationData();
- const commentAccess = useCanComment();
- const isDocumentOwner = useIsDocumentOwner();
+ const modificationPlaceablesAccess = pdf.permissions.canEdit;
+ const commentAccess = pdf.permissions.canComment;
+ const isDocumentOwner = pdf.permissions.isOwner;
- const [mode, setMode] = placeableModeSignal;
- const getPopupViewer = useGetPopupViewer();
- const getRootViewer = useGetRootViewer();
+ const [mode, setMode] = signals.placeableMode;
+ const getPopupViewer = signals.popupViewer[0];
+ const getRootViewer = signals.rootViewer[0];
const getIdToSectionMap = useGetIdToSectionMap();
const isPopup = useIsPopup();
const popupDispatchCtx = usePopupContextUpdate(isPopup);
@@ -130,10 +84,11 @@ export function PageOverlay(props: IPageOverlayProps) {
const resetUserHighlights = useResetUserHighlights();
const isAuth = useIsAuthenticated();
const createPlaceable = useCreatePlaceable();
- const disableOverlayClick = disableOverlayClickSignal.get;
- const setActiveThreadId = activeCommentThreadSignal.set;
- const disablePageViewClick = disablePageViewClickSignal.get;
- const termDataStore = keyedTermDataStore();
+ const commentPlaceables = useCommentPlaceables();
+ const disableOverlayClick = signals.disableOverlayClick[0];
+ const setActiveThreadId = signals.activeCommentThread[1];
+ const disablePageViewClick = signals.disablePageViewClick[0];
+ const termDataStore = pdf.state.termDataStore;
const onClick = (e: MouseEvent) => {
if (disablePageViewClick()) return;
@@ -277,7 +232,7 @@ export function PageOverlay(props: IPageOverlayProps) {
pageViewDiv.removeEventListener('click', onClick);
});
- if (isNestedBlock) return;
+ if (pdf.isNested()) return;
pageViewDiv.addEventListener('paste', onPaste);
pageViewDiv.addEventListener('keydown', onKeyDown);
onCleanup(() => {
@@ -286,7 +241,7 @@ export function PageOverlay(props: IPageOverlayProps) {
});
});
- const disableSelect = disableViewerTextSelectionSignal.get;
+ const disableSelect = signals.disableViewerTextSelection[0];
createEffect(() => {
const pageViewDiv = pageViewDivProp();
if (!pageViewDiv) return;
@@ -297,13 +252,12 @@ export function PageOverlay(props: IPageOverlayProps) {
}
});
- const blockElement = blockElementSignal.get;
onMount(() => {
const resetMode = (_e: MouseEvent) => {
setActiveThreadId(null);
setMode(PayloadMode.NoMode);
};
- const el = blockElement();
+ const el = pdf.rootElement();
if (!el) return;
el.addEventListener('click', resetMode);
onCleanup(() => el.removeEventListener('click', resetMode));
@@ -322,12 +276,23 @@ export function PageOverlay(props: IPageOverlayProps) {
return textModes.includes(mode) ? 'pointer' : 'text';
};
- const [selectionStoreValue, setSelectionStore] = selectionStore;
+ const [selectionStoreValue, setSelectionStore] = stores.selection;
const addNewHighlights = useAddNewHighlights();
const doEdit = useDoEdit();
- const setActiveHighlightId = activeHighlightSignal.set;
- const currentPageViewport = useCurrentPageViewport();
+ const setActiveHighlightId = signals.activeHighlight[1];
+ const currentPageViewport = () => {
+ const pageNumber = isPopup
+ ? derived.popupCurrentPageNumber()
+ : derived.currentPageNumber();
+ const viewer = isPopup ? getPopupViewer() : getRootViewer();
+ return (
+ viewer?.pageViewport(pageNumber - 1) ?? {
+ pageWidth: 0,
+ pageHeight: 0,
+ }
+ );
+ };
const addHighlight = () => {
if (!selectionStoreValue.selection) return;
@@ -427,24 +392,23 @@ export function PageOverlay(props: IPageOverlayProps) {
},
});
- const documentId = useBlockId();
const aiProps = {
- attachmentId: documentId,
+ attachmentId: pdf.documentId(),
};
- const newPlaceable = newPlaceableSignal.get;
+ const newPlaceable = signals.newPlaceable[0];
const newPlaceableId = () => newPlaceable()?.internalId;
const isNewPlaceableSelector = createSelector(newPlaceableId);
- const activePlaceableId = activePlaceableIdSignal.get;
+ const activePlaceableId = signals.activePlaceableId[0];
const isActivePlaceableSelector = createSelector(activePlaceableId);
const ownedCommentSelector = useOwnedCommentPlaceableSelector();
const showPopup = createMemo(() => {
const shouldshow =
- !isPopup && !popupOpen() && !!generalPopupLocationSignal();
+ !isPopup && !derived.popupOpen() && !!signals.generalPopupLocation[0]();
if (!shouldshow) {
- PDFPopupSelectedTextSignal.set(undefined);
- PDFPopupCompletionSignal.set(undefined);
+ signals.popupSelectedText[1](undefined);
+ signals.popupCompletion[1](undefined);
}
return shouldshow;
});
@@ -468,7 +432,7 @@ export function PageOverlay(props: IPageOverlayProps) {
}}
class="bg-transparent top-0 left-0 absolute"
>
- <Show when={showPopup() && generalPopupLocationSignal()}>
+ <Show when={showPopup() && signals.generalPopupLocation[0]()}>
{(generalPopupLocation) => (
<Show when={generalPopupLocation().pageIndex === props.pageIndex}>
<PDFPopup
@@ -513,9 +477,9 @@ export function PageOverlay(props: IPageOverlayProps) {
'transform-origin': '0% 0%',
}}
class="top-0 left-0 absolute bg-transparent"
- inert={isNestedBlock}
+ inert={pdf.isNested()}
>
- <For each={pdfModificationDataStore.get.placeables}>
+ <For each={stores.modificationData[0].placeables}>
{(placeable) => {
return (
<Show
@@ -570,14 +534,17 @@ function UserHighlightNodes(props: {
pageIndex: number;
viewport: PageViewport;
}) {
+ const { signals, stores } = usePdfDocument().state;
const thisPageHighlights = createMemo(() =>
- Object.values(highlightStore.get[props.pageIndex] ?? {}).filter((h) => !!h)
+ Object.values(stores.highlights[0][props.pageIndex] ?? {}).filter(
+ (h) => !!h
+ )
);
const viewportHeight = createMemo(() => props.viewport.height);
const viewportWidth = createMemo(() => props.viewport.width);
- const isActiveHighlightSelector = createSelector(activeHighlightSignal);
- const isActiveThreadSelector = useIsActiveThreadSelector();
+ const isActiveHighlightSelector = createSelector(signals.activeHighlight[0]);
+ const isActiveThreadSelector = createSelector(signals.activeCommentThread[0]);
return (
<For each={thisPageHighlights()}>
diff --git a/apps/web/src/features/block-pdf/component/PdfDocument.tsx b/apps/web/src/features/block-pdf/component/PdfDocument.tsx
new file mode 100644
index 0000000000..34efd93436
--- /dev/null
+++ b/apps/web/src/features/block-pdf/component/PdfDocument.tsx
@@ -0,0 +1,205 @@
+import './block.css';
+
+import type { PortalScope } from '@core/component/ScopedPortal';
+import type { GetDocumentResponseDataViewLocation } from '@service-storage/generated/schemas/getDocumentResponseDataViewLocation';
+import { debounce, leading } from '@solid-primitives/scheduled';
+import { type BeforeLeaveEventArgs, useBeforeLeave } from '@solidjs/router';
+import type { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
+import {
+ createEffect,
+ createResource,
+ type JSX,
+ onCleanup,
+ onMount,
+ Show,
+} from 'solid-js';
+import { reconcile } from 'solid-js/store';
+import { fromZodError } from 'zod-validation-error';
+import {
+ type PdfDocumentPermissions,
+ PdfDocumentProvider,
+ usePdfDocument,
+} from '../context/pdf-document-context';
+import {
+ type LocationBlockParams,
+ type LocationSearchParams,
+ usePendingLocationNavigationEffect,
+} from '../signal/location';
+import { usePdfSave } from '../signal/save';
+import { useUpdateColorsEffect } from '../signal/setting';
+import { useSyncHighlightStore } from '../store/highlight';
+import { useSyncActivePlaceableWithCommentThread } from '../store/placeables';
+import { useTableOfContentsUpdate } from '../store/tableOfContents';
+import {
+ IModificationDataOnServerSchema,
+ transformModificationDataToClient,
+} from '../type/coParse';
+import { preprocess } from '../websocket/preprocess';
+import { Document } from './Document';
+
+function preventNativePdfShortcuts(event: KeyboardEvent) {
+ if (
+ (event.key.toLowerCase() === 's' || event.key === 'z') &&
+ (navigator.platform.includes('Mac') ? event.metaKey : event.ctrlKey)
+ ) {
+ event.preventDefault();
+ }
+ if (
+ event.key === 'p' &&
+ (navigator.platform.includes('Mac') ? event.metaKey : event.ctrlKey)
+ ) {
+ event.preventDefault();
+ }
+}
+
+export type PdfDocumentMethods = {
+ goToLocationFromParams: (params: LocationBlockParams) => Promise<void>;
+};
+
+export type PdfDocumentProps = {
+ documentId: string;
+ documentVersionId?: number;
+ documentName: string;
+ documentProxy?: PDFDocumentProxy;
+ viewLocation?: GetDocumentResponseDataViewLocation;
+ modificationData?: unknown;
+ isNested?: boolean;
+ hotkeyScope: string;
+ portalScope?: PortalScope;
+ permissions: PdfDocumentPermissions;
+ locationParams?: LocationSearchParams;
+ registerMethods?: (methods: Partial<PdfDocumentMethods>) => void;
+ children: JSX.Element;
+};
+
+export function PdfDocument(props: PdfDocumentProps) {
+ return (
+ <Show when={props.documentId} keyed>
+ {(documentId) => (
+ <PdfDocumentProvider
+ documentId={documentId}
+ documentVersionId={props.documentVersionId}
+ documentName={props.documentName}
+ isNested={props.isNested}
+ hotkeyScope={props.hotkeyScope}
+ portalScope={props.portalScope}
+ permissions={props.permissions}
+ locationParams={props.locationParams}
+ >
+ <PdfDocumentState {...props} />
+ </PdfDocumentProvider>
+ )}
+ </Show>
+ );
+}
+
+export function PdfDocumentContent() {
+ return (
+ <div class="flex size-full relative justify-end overflow-visible z-main-view-layout">
+ <Document />
+ </div>
+ );
+}
+
+function PdfDocumentState(props: PdfDocumentProps) {
+ const pdf = usePdfDocument();
+ usePendingLocationNavigationEffect();
+ useSyncHighlightStore();
+ useSyncActivePlaceableWithCommentThread();
+ const {
+ documentProxy,
+ viewLocation,
+ pendingLocationParams,
+ locationChanged,
+ serverModificationData,
+ isSaving,
+ } = pdf.state.signals;
+ const [, setModificationData] = pdf.state.stores.modificationData;
+ const tableOfContentsDispatch = useTableOfContentsUpdate();
+ const savePdf = usePdfSave();
+
+ props.registerMethods?.({
+ goToLocationFromParams: async (params) => {
+ locationChanged[1](true);
+ pendingLocationParams[1](JSON.parse(JSON.stringify(params)));
+ },
+ });
+
+ createEffect(() => {
+ documentProxy[1](props.documentProxy);
+ viewLocation[1](pdf.isNested() ? undefined : props.viewLocation);
+
+ const modificationData = props.modificationData;
+ if (!modificationData) return;
+ const parsed = IModificationDataOnServerSchema.safeParse(modificationData);
+ if (!parsed.success) {
+ console.error(
+ 'Failed to parse modification data',
+ fromZodError(parsed.error)
+ );
+ return;
+ }
+
+ serverModificationData[1](parsed.data);
+ setModificationData(
+ reconcile(transformModificationDataToClient(parsed.data))
+ );
+ });
+
+ const [preprocessResource] = createResource(() => {
+ const documentVersionId = pdf.documentVersionId();
+ if (!documentVersionId) return;
+ return {
+ documentId: pdf.documentId(),
+ documentVersionId,
+ };
+ }, preprocess);
+
+ createEffect(() => {
+ if (preprocessResource.error) return;
+ const coparse = preprocessResource.latest;
+ if (!coparse) return;
+
+ pdf.state.termDataStore.load(coparse.defs ?? '');
+ tableOfContentsDispatch({ type: 'LOAD_AI_TOC', coparse });
+ pdf.state.signals.overlays[1](coparse.overlays);
+ });
+
+ const debouncedSave = leading(
+ debounce,
+ (event: BeforeLeaveEventArgs) => {
+ event.preventDefault();
+ void savePdf().then(() => event.retry(true));
+ },
+ 500
+ );
+ useBeforeLeave((event) => {
+ if (!pdf.isNested()) debouncedSave(event);
+ });
+
+ useUpdateColorsEffect();
+
+ onMount(() => {
+ if (pdf.isNested()) return;
+ const handleBeforeUnload = (event: Event) => {
+ if (isSaving[0]()) event.preventDefault();
+ };
+ window.addEventListener('keydown', preventNativePdfShortcuts);
+ window.addEventListener('beforeunload', handleBeforeUnload);
+ onCleanup(() => {
+ window.removeEventListener('keydown', preventNativePdfShortcuts);
+ window.removeEventListener('beforeunload', handleBeforeUnload);
+ });
+ });
+
+ return (
+ <div
+ ref={pdf.setRootElement}
+ class="size-full select-none overscroll-none overflow-hidden flex flex-col"
+ onContextMenu={(event) => event.preventDefault()}
+ data-tut="App"
+ >
+ {props.children}
+ </div>
+ );
+}
diff --git a/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsx b/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsx
index a3b2aa6b0b..e1b256fb9f 100644
--- a/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsx
+++ b/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsx
@@ -1,20 +1,19 @@
-import { showTabBarSignal } from '@block-pdf/signal/placeables';
import {
SplitToolbarLeft,
SplitToolbarRight,
} from '@components/app/split-layout/components/SplitToolbar';
import { ENABLE_PDF_MARKUP } from '@core/constant/featureFlags';
-import { useCanEdit } from '@core/signal/permissions';
import Tabs from '@phosphor/tabs.svg';
import { Button } from '@ui';
import { Show } from 'solid-js';
-import { pdfDocumentProxy } from '../signal/document';
+import { usePdfDocument } from '../context/pdf-document-context';
import { MarkupToolbar } from './MarkupToolbar';
import { PageNumberInput } from './PageNumberInput';
function TabsToggle() {
- const canEdit = useCanEdit();
- const [showTabBar, setShowTabBar] = showTabBarSignal;
+ const pdf = usePdfDocument();
+ const canEdit = pdf.permissions.canEdit;
+ const [showTabBar, setShowTabBar] = pdf.state.signals.showTabBar;
return (
<Show when={canEdit()}>
@@ -33,8 +32,9 @@ function TabsToggle() {
}
export function PdfSplitToolbar() {
+ const [documentProxy] = usePdfDocument().state.signals.documentProxy;
return (
- <Show when={pdfDocumentProxy()}>
+ <Show when={documentProxy()}>
<SplitToolbarLeft>
<div class="flex items-center gap-2">
<PageNumberInput />
diff --git a/apps/web/src/features/block-pdf/component/Placeable.tsx b/apps/web/src/features/block-pdf/component/Placeable.tsx
index 6bc0ccf211..2b00f6a306 100644
--- a/apps/web/src/features/block-pdf/component/Placeable.tsx
+++ b/apps/web/src/features/block-pdf/component/Placeable.tsx
@@ -1,17 +1,9 @@
-import {
- useCurrentScale,
- useGetPopupContextViewer,
- useIsPopup,
- useVisiblePages,
-} from '@block-pdf/signal/pdfViewer';
-import { activePlaceableIdSignal } from '@block-pdf/signal/placeables';
-import { activeCommentThreadSignal } from '@block-pdf/store/comments/commentStore';
+import { useIsPopup } from '@block-pdf/signal/pdfViewer';
import { isThreadPlaceable } from '@block-pdf/store/comments/freeComments';
import { useUpdatePlaceablePosition } from '@block-pdf/store/placeables';
import { type IPlaceable, PayloadMode } from '@block-pdf/type/placeables';
import { getPdfPageRect } from '@block-pdf/util/pdfjsUtils';
import { PDF_TO_CSS_UNITS } from '@block-pdf/util/pixelsPerInch';
-import { createBlockSignal } from '@core/block';
import { setEquals } from '@core/util/compareUtils';
import { isInDOMRect } from '@core/util/rect';
import { debounce } from '@solid-primitives/scheduled';
@@ -27,6 +19,7 @@ import {
Switch,
untrack,
} from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
import {
FreeCommentPlaceable,
NewFreeCommentPlaceable,
@@ -34,8 +27,6 @@ import {
import { Signature } from './placeables/Signature';
import { TextBox } from './placeables/TextBox';
-const isPopupDragSignal = createBlockSignal<boolean>(false);
-
export const Placeable: Component<{
pageNum: number;
isNew: boolean;
@@ -44,7 +35,11 @@ export const Placeable: Component<{
id: string;
canEdit: boolean;
}> = (props) => {
- const getViewer = useGetPopupContextViewer();
+ const pdf = usePdfDocument();
+ const isPopup = useIsPopup();
+ const { signals, derived } = pdf.state;
+ const getViewer = () =>
+ isPopup ? signals.popupViewer[0]() : signals.rootViewer[0]();
const [textAreaRef, setTextAreaRef] = createSignal<HTMLTextAreaElement>();
let placeableRef!: HTMLDivElement;
@@ -53,7 +48,11 @@ export const Placeable: Component<{
const parentId = () => props.pageNum + 1;
- const visiblePages = useVisiblePages();
+ const visiblePages = () =>
+ (isPopup
+ ? signals.visiblePagesChangedPopup[0]()
+ : signals.visiblePagesChanged[0]()
+ )?.visiblePages;
const visiblePageNumbers = createMemo((prev: Set<number>) => {
const visiblePageIds = visiblePages()?.ids ?? new Set();
const equals = setEquals(prev, visiblePageIds);
@@ -62,11 +61,10 @@ export const Placeable: Component<{
}, new Set());
const updatePlaceablePosition = useUpdatePlaceablePosition();
- const setActivePlaceableId = activePlaceableIdSignal.set;
- const setActiveCommentThreadId = activeCommentThreadSignal.set;
+ const setActivePlaceableId = signals.activePlaceableId[1];
+ const setActiveCommentThreadId = signals.activeCommentThread[1];
- const isPopup = useIsPopup();
- const [isPopupDrag, setIsPopupDrag] = isPopupDragSignal;
+ const [isPopupDrag, setIsPopupDrag] = signals.isPopupDrag;
const [mousePosition, setMousePosition] = createSignal({ x: 0, y: 0 });
const [dragOffset, setDragOffset] = createSignal({ x: 0, y: 0 });
@@ -328,7 +326,8 @@ export const Placeable: Component<{
});
});
- const currentScale = useCurrentScale();
+ const currentScale = () =>
+ (isPopup ? derived.popupCurrentScale() : derived.currentScale()) ?? 1;
const scale = createMemo(
() =>
getViewer()?.getScale({ pageNumber: 1 })?.scale ??
diff --git a/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx b/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx
index 5c4e5c313a..9e68db95b3 100644
--- a/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx
+++ b/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx
@@ -1,35 +1,25 @@
-import { selectingCommentThreadSignal } from '@block-pdf/signal/click';
-import { useOwnedCommentSelector } from '@block-pdf/signal/permissions';
import {
GUTTER_MARGIN,
MIN_RIGHT_COLUMN_WIDTH,
- viewerThreeColumnLayout,
} from '@block-pdf/signal/viewerThreeColumnLayout';
-import {
- threadHeightStore,
- threadsOnPagePositionStore,
-} from '@block-pdf/store/comments/commentLayout';
import {
useCreateComment,
useDeleteComment,
useUpdateComment,
} from '@block-pdf/store/comments/commentOperations';
-import {
- activeCommentThreadSignal,
- useGetCommentById,
- useIsActiveThreadSelector,
-} from '@block-pdf/store/comments/commentStore';
-import { useBlockId, useIsNestedBlock } from '@core/block';
import {
baseCommentTheme,
CommentsContext,
type CommentsContextType,
Thread,
} from '@core/comments/Thread';
-import { useCanComment, useIsDocumentOwner } from '@core/signal/permissions';
+import { useUserId } from '@core/context/user';
import { createMemo, createSelector, For } from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
export function RightMarginLayout(props: { pageNumber: number }) {
+ const [viewerThreeColumnLayout] =
+ usePdfDocument().state.signals.viewerThreeColumnLayout;
const styles = createMemo(() => {
const { centerWidth, marginWidth, rightWidth } = viewerThreeColumnLayout();
if (!centerWidth) return {};
@@ -57,35 +47,33 @@ export function RightMarginLayout(props: { pageNumber: number }) {
}
const useCommentsContext = (): CommentsContextType => {
- const isNestedBlock = useIsNestedBlock();
-
- const setActiveThread = activeCommentThreadSignal.set;
- const setThreadHeight = threadHeightStore.set;
+ const pdf = usePdfDocument();
+ const { signals, stores, derived } = pdf.state;
+ const setActiveThread = signals.activeCommentThread[1];
+ const setThreadHeight = stores.threadHeight[1];
const createComment = useCreateComment();
const updateComment = useUpdateComment();
const deleteComment = useDeleteComment();
- const ownedCommentSelector = useOwnedCommentSelector();
-
- const documentId = useBlockId();
- const isDocumentOwner = useIsDocumentOwner();
- const hasPermissions = useCanComment();
- const canComment = () => {
- if (isNestedBlock) return false;
- return hasPermissions();
+ const userId = useUserId();
+ const ownedComment = (id: number) => {
+ const currentUserId = userId();
+ return (
+ currentUserId != null &&
+ derived.commentMap()?.get(id)?.owner === currentUserId
+ );
};
-
- const getCommentById = useGetCommentById();
+ const getCommentById = (id: number) => derived.commentMap()?.get(id);
const commentsContext: CommentsContextType = {
setActiveThread,
setThreadHeight,
- canComment,
- isDocumentOwner,
+ canComment: () => !pdf.isNested() && pdf.permissions.canComment(),
+ isDocumentOwner: pdf.permissions.isOwner,
getCommentById,
- documentId,
- ownedComment: ownedCommentSelector,
+ documentId: pdf.documentId(),
+ ownedComment,
commentOperations: {
createComment,
deleteComment,
@@ -99,14 +87,16 @@ const useCommentsContext = (): CommentsContextType => {
};
function CommentsAndSuggestions(props: { pageNumber: number }) {
+ const { signals, stores } = usePdfDocument().state;
const threadsOnPage = createMemo(
- () => threadsOnPagePositionStore.get[props.pageNumber] ?? []
+ () => stores.threadsOnPagePosition[0][props.pageNumber] ?? []
);
- const isActiveThreadSelector = useIsActiveThreadSelector();
- const setActiveThreadId = activeCommentThreadSignal.set;
+ const [activeCommentThread, setActiveThreadId] = signals.activeCommentThread;
+ const isActiveThreadSelector = createSelector(activeCommentThread);
- const [selectedThreadId, setSelectedThreadId] = selectingCommentThreadSignal;
+ const [selectedThreadId, setSelectedThreadId] =
+ signals.selectingCommentThread;
const isSelectingThreadSelector = createSelector(selectedThreadId);
const commentTheme = (threadId: number | null) => {
diff --git a/apps/web/src/features/block-pdf/component/SimpleSearch.tsx b/apps/web/src/features/block-pdf/component/SimpleSearch.tsx
index 1ef7160e7a..a43c7ca9bf 100644
--- a/apps/web/src/features/block-pdf/component/SimpleSearch.tsx
+++ b/apps/web/src/features/block-pdf/component/SimpleSearch.tsx
@@ -1,12 +1,9 @@
-import { searchLocationPendingSignal } from '@block-pdf/signal/location';
import type { FindBarController } from '@core/component/createFindBarController';
import { FindBar } from '@core/component/FindBar';
import { IS_MAC } from '@core/constant/isMac';
-import { blockElementSignal } from '@core/signal/blockElement';
import { createEffect, createSignal, onCleanup, Show, untrack } from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
import {
- isSearchOpenSignal,
- searchSignal,
useJumpToResult,
useSearchClose,
useSearchResults,
@@ -14,15 +11,16 @@ import {
} from '../signal/search';
export function SimpleSearch() {
+ const pdf = usePdfDocument();
const searchStart = useSearchStart();
const searchResults = useSearchResults();
const jumpToResult = useJumpToResult();
const closeSearchBar = useSearchClose();
- const locationPending = searchLocationPendingSignal.get;
+ const [locationPending] = pdf.state.signals.searchLocationPending;
const [inputEl, setInputEl] = createSignal<HTMLInputElement>();
- const [isOpen, setIsOpen] = isSearchOpenSignal;
- const [searchText, setSearchText] = searchSignal;
+ const [isOpen, setIsOpen] = pdf.state.signals.isSearchOpen;
+ const [searchText, setSearchText] = pdf.state.signals.search;
const [isPending, setIsPending] = createSignal(false);
// Re-run the active search when the bar opens (or re-opens with prior text).
@@ -115,15 +113,12 @@ export function SimpleSearch() {
}
};
- const blockElement = blockElementSignal.get;
createEffect(() => {
- const element = blockElement();
+ const element = pdf.rootElement();
if (!element) return;
element.addEventListener('keydown', handleHotkey);
- document.addEventListener('keydown', handleHotkey);
onCleanup(() => {
element.removeEventListener('keydown', handleHotkey);
- document.removeEventListener('keydown', handleHotkey);
});
});
diff --git a/apps/web/src/features/block-pdf/component/Tabs.tsx b/apps/web/src/features/block-pdf/component/Tabs.tsx
index 3399635780..99796c6753 100644
--- a/apps/web/src/features/block-pdf/component/Tabs.tsx
+++ b/apps/web/src/features/block-pdf/component/Tabs.tsx
@@ -1,11 +1,6 @@
+import { useCurrentPageNumber } from '@block-pdf/signal/pdfViewer';
import {
- useCurrentPageNumber,
- viewerHasVisiblePagesSignal,
-} from '@block-pdf/signal/pdfViewer';
-import {
- activeTabIdSignal,
MAX_TAB_COUNT,
- tabDataStore,
useCreateTab,
useDeleteTab,
useNavigateToTab,
@@ -13,6 +8,7 @@ import {
import PlusIcon from '@phosphor/plus.svg';
import XIcon from '@phosphor/x.svg';
import { For, Show } from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
interface IInternalTabProps {
label: string;
@@ -25,7 +21,7 @@ interface IInternalTabProps {
}
function Tab(props: IInternalTabProps) {
- const [activeTabId] = activeTabIdSignal;
+ const [activeTabId] = usePdfDocument().state.signals.activeTabId;
const currentPageNumber = useCurrentPageNumber();
const active = () => props.id === activeTabId();
@@ -57,12 +53,14 @@ function Tab(props: IInternalTabProps) {
}
export function Tabs() {
- const [tabs] = tabDataStore;
+ const pdf = usePdfDocument();
+ const [tabs] = pdf.state.stores.tabData;
+ const [viewerHasVisiblePages] = pdf.state.signals.viewerHasVisiblePages;
const createTab = useCreateTab();
const deleteTab = useDeleteTab();
const navigate = useNavigateToTab();
return (
- <Show when={viewerHasVisiblePagesSignal.get()}>
+ <Show when={viewerHasVisiblePages()}>
<div class="w-full h-7 rounded-full flex px-1.5 shrink items-center">
<For each={tabs}>
{(tab, index) => (
diff --git a/apps/web/src/features/block-pdf/component/TopBar.tsx b/apps/web/src/features/block-pdf/component/TopBar.tsx
index e46b87e60f..24de60a93e 100644
--- a/apps/web/src/features/block-pdf/component/TopBar.tsx
+++ b/apps/web/src/features/block-pdf/component/TopBar.tsx
@@ -47,11 +47,13 @@ import {
storageServiceClient,
} from '@service-storage/client';
import { createCallback } from '@solid-primitives/rootless';
-import { pdfDocumentProxy } from '../signal/document';
+import { usePdfDocument } from '../context/pdf-document-context';
import { LocationType, useCreateShareUrl } from '../signal/location';
import { PdfSplitToolbar } from './PdfSplitToolbar';
export function TopBar() {
+ const pdf = usePdfDocument();
+ const [documentProxy] = pdf.state.signals.documentProxy;
const isAuth = useIsAuthenticated();
const documentId = useBlockId();
const blockName = useBlockName();
@@ -77,10 +79,10 @@ export function TopBar() {
const printFile = createCallback(async () => {
if (!isAuth()) return openLoginModal();
- const documentProxy = pdfDocumentProxy();
- if (!documentProxy) return;
+ const proxy = documentProxy();
+ if (!proxy) return;
- const data = (await documentProxy.getData()) as Uint8Array<ArrayBuffer>;
+ const data = (await proxy.getData()) as Uint8Array<ArrayBuffer>;
const blob = new Blob([data], { type: 'application/pdf' });
return doPrint(blob);
@@ -89,10 +91,10 @@ export function TopBar() {
const download = createCallback(async () => {
if (!isAuth()) return openLoginModal();
- const documentProxy = pdfDocumentProxy();
- if (!documentProxy) return toast.failure('Unable to download file');
+ const proxy = documentProxy();
+ if (!proxy) return toast.failure('Unable to download file');
- const data = (await documentProxy.getData()) as Uint8Array<ArrayBuffer>;
+ const data = (await proxy.getData()) as Uint8Array<ArrayBuffer>;
const blob = new Blob([data], { type: 'application/pdf' });
const fileNameWithExtension = `${fileName()}.pdf`;
diff --git a/apps/web/src/features/block-pdf/component/UserHighlight.tsx b/apps/web/src/features/block-pdf/component/UserHighlight.tsx
index ad122ca19e..648d7f50a0 100644
--- a/apps/web/src/features/block-pdf/component/UserHighlight.tsx
+++ b/apps/web/src/features/block-pdf/component/UserHighlight.tsx
@@ -1,8 +1,3 @@
-import {
- activeCommentThreadSignal,
- noScrollToActiveCommentThreadSignal,
-} from '@block-pdf/store/comments/commentStore';
-import { createBlockSignal } from '@core/block';
import { createCallback } from '@solid-primitives/rootless';
import { cn } from '@ui';
import {
@@ -12,29 +7,23 @@ import {
onMount,
type VoidProps,
} from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
import { Color, type IColor } from '../model/Color';
import type { IHighlight } from '../model/Highlight';
-import {
- generalPopupLocationSignal,
- useSetLocationStore,
-} from '../signal/location';
import { useIsPopup } from '../signal/pdfViewer';
import { usePopupContextUpdate } from '../store/definitionPopup';
-import { selectionStore, useGetHighlightByUuid } from '../store/highlight';
import type { IHighlightObj } from './PageOverlay';
-const hoverHighlightSignal = createBlockSignal<string | null>(null);
-// uuid of the highlight that is currently active
-export const activeHighlightSignal = createBlockSignal<string | null>(null);
-
// TODO: only check for highlight IDs within the block DOM subtree
export const highlightIdSelector = (highlightId: string) =>
`[data-highlight-id="${highlightId}"]`;
export const useResetUserHighlights = () => {
- const setActiveThread = activeCommentThreadSignal.set;
- const setHoverHighlight = hoverHighlightSignal.set;
- const setActiveHighlight = activeHighlightSignal.set;
+ const { activeCommentThread, activeHighlight, hoverHighlight } =
+ usePdfDocument().state.signals;
+ const setActiveThread = activeCommentThread[1];
+ const setHoverHighlight = hoverHighlight[1];
+ const setActiveHighlight = activeHighlight[1];
return createCallback(() => {
setActiveThread(null);
@@ -103,15 +92,16 @@ const isHighlightComment = (highlight: IHighlight) =>
// TODO: handle highlight selection in a different document
export const useHighlightSelection = () => {
- const setSelectionStore = selectionStore.set;
- const getHighlightByUuid = useGetHighlightByUuid();
- const setActiveThread = activeCommentThreadSignal.set;
- const setActiveHighlight = activeHighlightSignal.set;
- const setGeneralPopupLocation = generalPopupLocationSignal.set;
- const setLocationStore = useSetLocationStore();
+ const pdf = usePdfDocument();
+ const { signals, stores, derived } = pdf.state;
+ const setSelectionStore = stores.selection[1];
+ const setActiveThread = signals.activeCommentThread[1];
+ const setActiveHighlight = signals.activeHighlight[1];
+ const setGeneralPopupLocation = signals.generalPopupLocation[1];
+ const setLocationStore = stores.location[1];
return (highlightId: string, element?: HTMLElement) => {
- const highlight = getHighlightByUuid(highlightId);
+ const highlight = derived.highlightsUuidMap()?.[highlightId];
if (!highlight) return;
// handle comments and regular highlights differently
@@ -125,7 +115,9 @@ export const useHighlightSelection = () => {
// Find the highlight element in the DOM
const highlightElement =
element ??
- document.querySelector<HTMLElement>(highlightIdSelector(highlightId));
+ pdf
+ .rootElement()
+ ?.querySelector<HTMLElement>(highlightIdSelector(highlightId));
if (!highlightElement) return;
// Check if the highlight is in the viewport
@@ -145,6 +137,7 @@ export const useHighlightSelection = () => {
element: highlightElement,
});
setLocationStore('annotation', {
+ type: 'annotation',
pageIndex: highlight.pageNum,
id: highlight.uuid,
});
@@ -170,12 +163,13 @@ export function UserHighlight(props: VoidProps<IHighlightObj>) {
let highlightRef!: HTMLDivElement;
let textRef!: HTMLDivElement;
+ const { signals } = usePdfDocument().state;
const isPopup = useIsPopup();
const popupDispatchCtx = usePopupContextUpdate(isPopup);
const highlightSelection = useHighlightSelection();
- const setActiveThread = activeCommentThreadSignal.set;
- const [hoverHighlight, setHoverHighlight] = hoverHighlightSignal;
- const setActiveHighlight = activeHighlightSignal.set;
+ const setActiveThread = signals.activeCommentThread[1];
+ const [hoverHighlight, setHoverHighlight] = signals.hoverHighlight;
+ const setActiveHighlight = signals.activeHighlight[1];
onMount(() => {
const handleSelectStart = (e: MouseEvent) => {
@@ -231,8 +225,8 @@ export function UserHighlight(props: VoidProps<IHighlightObj>) {
};
});
- const setGeneralPopupLocation = generalPopupLocationSignal.set;
- const setNoScroll = noScrollToActiveCommentThreadSignal.set;
+ const setGeneralPopupLocation = signals.generalPopupLocation[1];
+ const setNoScroll = signals.noScrollToActiveCommentThread[1];
const clickHandler: JSX.EventHandler<HTMLDivElement, MouseEvent> =
createCallback((e) => {
// prevents the page overlay from receiving the click event and resetting
diff --git a/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx b/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx
index 18e26ca7a9..405d7771e4 100644
--- a/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx
+++ b/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx
@@ -1,17 +1,15 @@
-import {
- activeCommentThreadSignal,
- noScrollToActiveCommentThreadSignal,
- useIsActiveThreadSelector,
-} from '@block-pdf/store/comments/commentStore';
+import { useIsActiveThreadSelector } from '@block-pdf/store/comments/commentStore';
import type { IThreadPlaceable } from '@block-pdf/type/placeables';
import { cn } from '@ui';
import type { Component } from 'solid-js';
+import { usePdfDocument } from '../../context/pdf-document-context';
export const FreeCommentPlaceable: Component<{
payload: NonNullable<IThreadPlaceable['payload']>;
}> = (props) => {
const isActiveThreadSelector = useIsActiveThreadSelector();
- const setActiveThreadId = activeCommentThreadSignal.set;
+ const [, setActiveThreadId] =
+ usePdfDocument().state.signals.activeCommentThread;
return (
<CommentIndicator
@@ -33,8 +31,8 @@ function CommentIndicator(props: {
isActive: boolean;
setActive?: () => void;
}) {
- const setNoScrollToActiveCommentThread =
- noScrollToActiveCommentThreadSignal.set;
+ const [, setNoScrollToActiveCommentThread] =
+ usePdfDocument().state.signals.noScrollToActiveCommentThread;
// SCUFFED, decide how to define this color
return (
diff --git a/apps/web/src/features/block-pdf/component/placeables/Signature.tsx b/apps/web/src/features/block-pdf/component/placeables/Signature.tsx
index 2934699578..a4ba1cadf4 100644
--- a/apps/web/src/features/block-pdf/component/placeables/Signature.tsx
+++ b/apps/web/src/features/block-pdf/component/placeables/Signature.tsx
@@ -1,8 +1,4 @@
-import {
- activePlaceableIdSignal,
- newPlaceableSignal,
-} from '@block-pdf/signal/placeables';
-import { blockElementSignal } from '@core/signal/blockElement';
+import { ScopedPortal } from '@core/component/ScopedPortal';
import Dialog from '@corvu/dialog';
import Check from '@phosphor/check.svg';
import Trash from '@phosphor/trash-simple.svg';
@@ -17,8 +13,8 @@ import {
onMount,
Show,
} from 'solid-js';
-import { Portal } from 'solid-js/web';
import { themeReactive } from '../../../theme/signals/themeReactive';
+import { usePdfDocument } from '../../context/pdf-document-context';
import { useDeletePlaceable, useModifyPayload } from '../../store/placeables';
import { type AllowableEdits, PayloadMode } from '../../type/placeables';
@@ -35,6 +31,7 @@ interface SignatureEditorProps {
}
function SignatureEditor(props: SignatureEditorProps) {
+ const pdf = usePdfDocument();
let canvasRef!: HTMLCanvasElement;
let signaturePad: SignaturePad | undefined;
@@ -42,11 +39,11 @@ function SignatureEditor(props: SignatureEditorProps) {
signaturePad = new SignaturePad(canvasRef);
});
- const setActivePlaceable = activePlaceableIdSignal.set;
+ const [, setActivePlaceable] = pdf.state.signals.activePlaceableId;
const modifyPayload = useModifyPayload();
const deletePlaceable = useDeletePlaceable();
- const setNewPlaceable = newPlaceableSignal.set;
+ const [, setNewPlaceable] = pdf.state.signals.newPlaceable;
const updatePlaceable = createCallback((e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
@@ -77,7 +74,7 @@ function SignatureEditor(props: SignatureEditorProps) {
);
onMount(() => {
- const el = blockElementSignal.get();
+ const el = pdf.rootElement();
if (!el) {
setBlockRect(undefined);
return;
@@ -122,7 +119,7 @@ function SignatureEditor(props: SignatureEditorProps) {
// this is because we often prevent default onMouseDown
noOutsidePointerEvents={false}
>
- <Portal mount={document.getElementById('modal') ?? undefined}>
+ <ScopedPortal scope={pdf.portalScope()}>
<Dialog.Overlay
class="dialog-overlay-open-animation flex sm:max-h-full items-center justify-center z-modal-overlay fixed inset-0 bg-modal-overlay"
style={{
@@ -170,7 +167,7 @@ function SignatureEditor(props: SignatureEditorProps) {
</Button>
</div>
</Dialog.Content>
- </Portal>
+ </ScopedPortal>
</Dialog>
);
}
diff --git a/apps/web/src/features/block-pdf/component/placeables/TextBox.tsx b/apps/web/src/features/block-pdf/component/placeables/TextBox.tsx
index 8a41d8bbdb..93fe6aaf94 100644
--- a/apps/web/src/features/block-pdf/component/placeables/TextBox.tsx
+++ b/apps/web/src/features/block-pdf/component/placeables/TextBox.tsx
@@ -1,5 +1,4 @@
import { Color } from '@block-pdf/model/Color';
-import { activePlaceableIdSignal } from '@block-pdf/signal/placeables';
import {
useDeletePlaceable,
useModifyPayload,
@@ -12,6 +11,7 @@ import {
import { createCallback } from '@solid-primitives/rootless';
import { cn } from '@ui';
import { createEffect, createSignal, type JSX, type Ref } from 'solid-js';
+import { usePdfDocument } from '../../context/pdf-document-context';
interface TextBoxProps {
id: string;
@@ -26,7 +26,8 @@ interface TextBoxProps {
export function TextBox(props: TextBoxProps) {
let textAreaRef!: HTMLTextAreaElement;
const [text, setText] = createSignal(props.payload.text);
- const setActivePlaceable = activePlaceableIdSignal.set;
+ const [, setActivePlaceable] =
+ usePdfDocument().state.signals.activePlaceableId;
const modifyPayload = useModifyPayload();
const deletePlaceable = useDeletePlaceable();
diff --git a/apps/web/src/features/block-pdf/context/pdf-document-context.tsx b/apps/web/src/features/block-pdf/context/pdf-document-context.tsx
new file mode 100644
index 0000000000..ed8900f722
--- /dev/null
+++ b/apps/web/src/features/block-pdf/context/pdf-document-context.tsx
@@ -0,0 +1,88 @@
+import type { PortalScope } from '@core/component/ScopedPortal';
+import {
+ type Accessor,
+ createContext,
+ createSignal,
+ type FlowComponent,
+ useContext,
+} from 'solid-js';
+import type { LocationSearchParams } from '../signal/location';
+import {
+ createPdfDocumentState,
+ type PdfDocumentState,
+} from './pdf-document-state';
+
+export type PdfDocumentPermissions = {
+ canComment: boolean;
+ canEdit: boolean;
+ isOwner: boolean;
+};
+
+export type PdfDocumentContextValue = {
+ documentId: Accessor<string>;
+ documentVersionId: Accessor<number | undefined>;
+ documentName: Accessor<string>;
+ isNested: Accessor<boolean>;
+ hotkeyScope: Accessor<string>;
+ portalScope: Accessor<PortalScope>;
+ permissions: {
+ canComment: Accessor<boolean>;
+ canEdit: Accessor<boolean>;
+ isOwner: Accessor<boolean>;
+ };
+ locationParams: Accessor<LocationSearchParams>;
+ rootElement: Accessor<HTMLElement | undefined>;
+ setRootElement: (element: HTMLElement | undefined) => void;
+ state: PdfDocumentState;
+};
+
+export type PdfDocumentProviderProps = {
+ documentId: string;
+ documentVersionId?: number;
+ documentName: string;
+ isNested?: boolean;
+ hotkeyScope: string;
+ portalScope?: PortalScope;
+ permissions: PdfDocumentPermissions;
+ locationParams?: LocationSearchParams;
+};
+
+const PdfDocumentContext = createContext<PdfDocumentContextValue>();
+
+export const PdfDocumentProvider: FlowComponent<PdfDocumentProviderProps> = (
+ props
+) => {
+ const documentId = () => props.documentId;
+ const [rootElement, setRootElement] = createSignal<HTMLElement>();
+ const context: PdfDocumentContextValue = {
+ documentId,
+ documentVersionId: () => props.documentVersionId,
+ documentName: () => props.documentName,
+ isNested: () => props.isNested ?? false,
+ hotkeyScope: () => props.hotkeyScope,
+ portalScope: () => props.portalScope ?? 'split',
+ permissions: {
+ canComment: () => props.permissions.canComment,
+ canEdit: () => props.permissions.canEdit,
+ isOwner: () => props.permissions.isOwner,
+ },
+ locationParams: () => props.locationParams ?? {},
+ rootElement,
+ setRootElement,
+ state: createPdfDocumentState(documentId),
+ };
+
+ return (
+ <PdfDocumentContext.Provider value={context}>
+ {props.children}
+ </PdfDocumentContext.Provider>
+ );
+};
+
+export function usePdfDocument(): PdfDocumentContextValue {
+ const context = useContext(PdfDocumentContext);
+ if (!context) {
+ throw new Error('usePdfDocument must be used within a PdfDocumentProvider');
+ }
+ return context;
+}
diff --git a/apps/web/src/features/block-pdf/context/pdf-document-state.ts b/apps/web/src/features/block-pdf/context/pdf-document-state.ts
new file mode 100644
index 0000000000..6e4c334879
--- /dev/null
+++ b/apps/web/src/features/block-pdf/context/pdf-document-state.ts
@@ -0,0 +1,378 @@
+import type { Completion } from '@core/client/completion';
+import type { ThreadId } from '@core/comments/commentType';
+import type { ThreeColumnLayout } from '@core/util/threeColumnLayout';
+import type { GetDocumentResponseDataViewLocation } from '@service-storage/generated/schemas/getDocumentResponseDataViewLocation';
+import type { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
+import type { Accessor } from 'solid-js';
+import {
+ createEffect,
+ createMemo,
+ createResource,
+ createSignal,
+} from 'solid-js';
+import { createStore, reconcile } from 'solid-js/store';
+import type { IHighlight } from '../model/Highlight';
+import type { PDFViewer } from '../PdfViewer';
+import type { TEvents } from '../PdfViewer/EventBus';
+import { TermDataStore } from '../PdfViewer/TermDataStore';
+import { ZOOM_MAX, ZOOM_MIN } from '../PdfViewer/zoom';
+import { getPdfAnchors, getPdfComments } from '../queries/annotations';
+import type {
+ AnnotationLocation,
+ GeneralLocation,
+ LocationBlockParams,
+ PreciseLocation,
+ SearchLocation,
+} from '../signal/location';
+import type { TabInfo } from '../signal/tab';
+import type {
+ ThreadHeights,
+ ThreadPositionsOnPage,
+} from '../store/comments/commentLayout';
+import type { ISectionPopupContext } from '../store/definitionPopup';
+import type { HighlightPageMap, HighlightUuidMap } from '../store/highlight';
+import type { ITableOfContentsContext } from '../store/tableOfContents';
+import type { CommentStore } from '../type/comments';
+import type {
+ IModificationData,
+ IModificationDataOnServer,
+} from '../type/coParse';
+import {
+ type IPlaceable,
+ PayloadMode,
+ type PayloadType,
+} from '../type/placeables';
+
+const defaultTabData = (id: number): TabInfo => ({
+ label: 'Page 1',
+ locationHash: '#page=1',
+ id,
+});
+
+const createDefinitionPopupState = (): ISectionPopupContext => ({
+ terms: [],
+ termIDs: [],
+ termIDToSizingMap: {},
+ pageWidth: null,
+ element: null,
+});
+
+const createTableOfContentsState = (): ITableOfContentsContext => ({
+ original: {
+ aiToc: null,
+ pdfBookmarks: null,
+ },
+ currentMode: 'bookmarks',
+ width:
+ typeof window === 'undefined'
+ ? 150
+ : Math.max(150, Math.round(window.innerWidth * 0.15)),
+ sectionToRenameID: null,
+ renameFormValue: '',
+ sectionToDeleteID: null,
+ unsavedBookmarks: false,
+ coparse: null,
+ items: [],
+ openItems: {},
+ isLoaded: false,
+ pageToSectionMap: [],
+ idToSectionMap: {},
+ idToPathMap: {},
+ idToNearestTitleMap: {},
+ aiTocIdToSectionMap: {},
+});
+
+export function createPdfDocumentState(documentId: Accessor<string>) {
+ const documentProxy = createSignal<PDFDocumentProxy>();
+ const viewLocation = createSignal<GetDocumentResponseDataViewLocation>();
+ const modificationData = createStore<IModificationData>({
+ bookmarks: [],
+ placeables: [],
+ pinnedTermsNames: [],
+ });
+ const overlays = createSignal<string[]>();
+
+ const locationChanged = createSignal(false);
+ const pendingLocationParams = createSignal<LocationBlockParams>();
+ const searchLocationPending = createSignal(false);
+ const location = createStore<{
+ general: GeneralLocation | undefined;
+ precise: PreciseLocation | undefined;
+ annotation: AnnotationLocation | undefined;
+ search: SearchLocation | undefined;
+ }>({
+ general: undefined,
+ precise: undefined,
+ annotation: undefined,
+ search: undefined,
+ });
+ const generalPopupLocation = createSignal<{
+ pageIndex: number;
+ element: HTMLElement;
+ hasHighlight?: boolean;
+ hasComment?: boolean;
+ } | null>(null);
+
+ const disableOverlayClick = createSignal(false);
+ const disableViewerTextSelection = createSignal(false);
+ const disablePageViewClick = createSignal(false);
+ const isSelectingViewerText = createSignal(false);
+ const selectingCommentThread = createSignal<number | null>(null);
+
+ const search = createSignal('');
+ const isSearchOpen = createSignal(false);
+
+ const placeableMode = createSignal<PayloadType>(PayloadMode.NoMode);
+ const showTabBar = createSignal(false);
+ const activePlaceableId = createSignal<string>();
+ const newPlaceable = createSignal<IPlaceable>();
+ const fontPreference = createSignal<
+ 'Times New Roman' | 'Courier' | 'Helvetica'
+ >('Times New Roman');
+
+ const numOperations = createSignal(0);
+ const savingCount = createSignal(0);
+ const isSaving = createSignal(false);
+ const modificationDataSaveRequired = createSignal(false);
+ const serverModificationData = createSignal<IModificationDataOnServer>();
+
+ const tabId = createSignal(0);
+ const tabData = createStore<TabInfo[]>([defaultTabData(0)]);
+ const activeTabId = createSignal(0);
+ const tabHistory = createSignal<number[]>([0]);
+
+ const rootViewer = createSignal<PDFViewer>();
+ const popupViewer = createSignal<PDFViewer>();
+ const pagesLoaded = createSignal<TEvents['pagesloaded']>();
+ const scaleChanging = createSignal<TEvents['scalechanging']>();
+ const pageChanging = createSignal<TEvents['pagechanging']>();
+ const overlayViewsChanged = createSignal<TEvents['overlayViewsChanged']>();
+ const popupVisibilityChanged =
+ createSignal<TEvents['popupvisibilitychanged']>();
+ const visiblePagesChanged = createSignal<TEvents['updateviewarea']>();
+ const updateFindControlState =
+ createSignal<TEvents['updatefindcontrolstate']>();
+ const updateFindMatchesCount =
+ createSignal<TEvents['updatefindmatchescount']>();
+ const scaleChangingPopup = createSignal<TEvents['scalechanging']>();
+ const pageChangingPopup = createSignal<TEvents['pagechanging']>();
+ const overlayViewsChangedPopup =
+ createSignal<TEvents['overlayViewsChanged']>();
+ const visiblePagesChangedPopup = createSignal<TEvents['updateviewarea']>();
+ const viewerHasVisiblePages = createSignal(false);
+ const pageHeight = createStore<Partial<Record<number, number>>>({});
+ const destroying = createSignal(false);
+
+ const viewerThreeColumnLayout = createSignal<ThreeColumnLayout>({
+ isInitialized: false,
+ leftWidth: 352,
+ rightWidth: 293,
+ rightMargin: 6,
+ centerWidth: -1,
+ windowWidth: -1,
+ marginWidth: -1,
+ });
+
+ const highlights = createStore<HighlightPageMap>({});
+ const selection = createStore<{
+ highlightsUnderSelection: IHighlight[];
+ selection: Selection | null;
+ selectionString: string;
+ }>({
+ highlightsUnderSelection: [],
+ selection: null,
+ selectionString: '',
+ });
+ const activeHighlight = createSignal<string | null>(null);
+ const hoverHighlight = createSignal<string | null>(null);
+ const popupSelectedText = createSignal<string>();
+ const popupCompletion = createSignal<Completion>();
+ const isPopupDrag = createSignal(false);
+
+ const convertedHighlightThreadId = createSignal<string | null>(null);
+ const activeCommentThread = createSignal<ThreadId | null>(null);
+ const noScrollToActiveCommentThread = createSignal(false);
+ const comments = createStore<CommentStore>([]);
+ const threadHeight = createStore<Partial<ThreadHeights>>({});
+ const threadsOnPagePosition = createStore<ThreadPositionsOnPage>({});
+
+ const rootDefinition = createStore<ISectionPopupContext>(
+ createDefinitionPopupState()
+ );
+ const popupDefinition = createStore<ISectionPopupContext>(
+ createDefinitionPopupState()
+ );
+ const tableOfContents = createStore<ITableOfContentsContext>(
+ createTableOfContentsState()
+ );
+
+ const commentThreads = createResource(documentId, getPdfComments);
+ const anchors = createResource(documentId, getPdfAnchors);
+
+ const popupOpen = createMemo(
+ () => popupVisibilityChanged[0]()?.isOpen ?? false
+ );
+ const currentPageNumber = createMemo(
+ () => pageChanging[0]()?.pageNumber ?? 1
+ );
+ const currentScale = createMemo(() => scaleChanging[0]()?.scale);
+ const canZoomIn = createMemo(() => {
+ const scale = currentScale();
+ return !!(scale && scale < ZOOM_MAX);
+ });
+ const canZoomOut = createMemo(() => {
+ const scale = currentScale();
+ return !!(scale && scale > ZOOM_MIN);
+ });
+ const pageCount = createMemo(() => pagesLoaded[0]()?.pagesCount);
+ const popupCurrentPageNumber = createMemo(
+ () => pageChangingPopup[0]()?.pageNumber ?? 1
+ );
+ const popupCurrentScale = createMemo(() => scaleChangingPopup[0]()?.scale);
+ const viewerReady = createMemo(() => {
+ const loaded = pagesLoaded[0]();
+ return !!loaded && loaded.pagesCount > 0;
+ });
+ const highlightList = createMemo(() => {
+ const result: IHighlight[] = [];
+ for (const pageHighlights of Object.values(highlights[0] ?? {})) {
+ if (!pageHighlights) continue;
+ for (const highlight of Object.values(pageHighlights)) {
+ if (highlight) result.push(highlight);
+ }
+ }
+ return result;
+ });
+ const highlightsUuidMap = createMemo(() => {
+ const result: HighlightUuidMap = {};
+ for (const pageHighlights of Object.values(highlights[0] ?? {})) {
+ if (!pageHighlights) continue;
+ for (const [uuid, highlight] of Object.entries(pageHighlights)) {
+ result[uuid] = highlight;
+ }
+ }
+ return result;
+ });
+ const commentMap = createMemo(() => {
+ const result = new Map<number, CommentStore[number]>();
+ for (const comment of comments[0]) result.set(comment.id, comment);
+ return result;
+ });
+
+ createEffect(() => {
+ const disabled =
+ placeableMode[0]() !== PayloadMode.NoMode || isSelectingViewerText[0]();
+ disableOverlayClick[1](disabled);
+ });
+ createEffect(() => {
+ if (isSelectingViewerText[0]()) selectingCommentThread[1](null);
+ });
+ createEffect(() => {
+ disableViewerTextSelection[1](selectingCommentThread[0]() != null);
+ });
+ createEffect(() => {
+ const ids = visiblePagesChanged[0]()?.visiblePages.ids;
+ viewerHasVisiblePages[1](!!ids && ids.size > 0);
+ });
+ createEffect(() => {
+ const event = overlayViewsChanged[0]();
+ if (!event) return;
+ const updated: Partial<Record<number, number>> = {};
+ for (const pageView of Object.values(event.views)) {
+ updated[pageView.id - 1] = pageView.viewport.height;
+ }
+ pageHeight[1](reconcile(updated));
+ });
+
+ return {
+ signals: {
+ documentProxy,
+ viewLocation,
+ overlays,
+ locationChanged,
+ pendingLocationParams,
+ searchLocationPending,
+ generalPopupLocation,
+ disableOverlayClick,
+ disableViewerTextSelection,
+ disablePageViewClick,
+ isSelectingViewerText,
+ selectingCommentThread,
+ search,
+ isSearchOpen,
+ placeableMode,
+ showTabBar,
+ activePlaceableId,
+ newPlaceable,
+ fontPreference,
+ numOperations,
+ savingCount,
+ isSaving,
+ modificationDataSaveRequired,
+ serverModificationData,
+ tabId,
+ activeTabId,
+ tabHistory,
+ rootViewer,
+ popupViewer,
+ pagesLoaded,
+ scaleChanging,
+ pageChanging,
+ overlayViewsChanged,
+ popupVisibilityChanged,
+ visiblePagesChanged,
+ updateFindControlState,
+ updateFindMatchesCount,
+ scaleChangingPopup,
+ pageChangingPopup,
+ overlayViewsChangedPopup,
+ visiblePagesChangedPopup,
+ viewerHasVisiblePages,
+ destroying,
+ viewerThreeColumnLayout,
+ activeHighlight,
+ hoverHighlight,
+ popupSelectedText,
+ popupCompletion,
+ isPopupDrag,
+ convertedHighlightThreadId,
+ activeCommentThread,
+ noScrollToActiveCommentThread,
+ },
+ stores: {
+ modificationData,
+ location,
+ tabData,
+ pageHeight,
+ highlights,
+ selection,
+ comments,
+ threadHeight,
+ threadsOnPagePosition,
+ rootDefinition,
+ popupDefinition,
+ tableOfContents,
+ },
+ resources: {
+ commentThreads,
+ anchors,
+ },
+ derived: {
+ popupOpen,
+ currentPageNumber,
+ currentScale,
+ canZoomIn,
+ canZoomOut,
+ pageCount,
+ popupCurrentPageNumber,
+ popupCurrentScale,
+ viewerReady,
+ highlightList,
+ highlightsUuidMap,
+ commentMap,
+ },
+ termDataStore: new TermDataStore(),
+ };
+}
+
+export type PdfDocumentState = ReturnType<typeof createPdfDocumentState>;
diff --git a/apps/web/src/features/block-pdf/queries/annotations.ts b/apps/web/src/features/block-pdf/queries/annotations.ts
new file mode 100644
index 0000000000..969b090938
--- /dev/null
+++ b/apps/web/src/features/block-pdf/queries/annotations.ts
@@ -0,0 +1,15 @@
+import { storageServiceClient } from '@service-storage/client';
+
+export async function getPdfComments(documentId: string) {
+ const result = await storageServiceClient.annotations.getComments({
+ documentId,
+ });
+ return result.isOk() ? result.value.data : [];
+}
+
+export async function getPdfAnchors(documentId: string) {
+ const result = await storageServiceClient.annotations.getAnchors({
+ documentId,
+ });
+ return result.isOk() ? result.value.data : [];
+}
diff --git a/apps/web/src/features/block-pdf/signal/click.ts b/apps/web/src/features/block-pdf/signal/click.ts
deleted file mode 100644
index 99dfc1db9b..0000000000
--- a/apps/web/src/features/block-pdf/signal/click.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { PayloadMode } from '@block-pdf/type/placeables';
-import { createBlockEffect, createBlockSignal } from '@core/block';
-import { placeableModeSignal } from './placeables';
-
-export const disableOverlayClickSignal = createBlockSignal<boolean>(false);
-
-export const disableViewerTextSelectionSignal =
- createBlockSignal<boolean>(false);
-
-export const disablePageViewClickSignal = createBlockSignal<boolean>(false);
-
-export const isSelectingViewerTextSignal = createBlockSignal<boolean>(false);
-
-export const selectingCommentThreadSignal = createBlockSignal<number | null>(
- null
-);
-
-createBlockEffect(() => {
- const mode = placeableModeSignal.get;
- const selectionStarted = isSelectingViewerTextSignal.get;
- const disabled = mode() !== PayloadMode.NoMode || selectionStarted();
-
- disableOverlayClickSignal.set(disabled);
-});
-
-createBlockEffect(() => {
- const selectingViewer = isSelectingViewerTextSignal.get();
- if (selectingViewer) {
- selectingCommentThreadSignal.set(null);
- }
-});
-
-createBlockEffect(() => {
- const selectingCommentId = selectingCommentThreadSignal.get();
- disableViewerTextSelectionSignal.set(selectingCommentId != null);
-});
diff --git a/apps/web/src/features/block-pdf/signal/document.ts b/apps/web/src/features/block-pdf/signal/document.ts
deleted file mode 100644
index e87a9c3ef5..0000000000
--- a/apps/web/src/features/block-pdf/signal/document.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { createBlockSignal, createBlockStore } from '@core/block';
-import type { GetDocumentResponseDataViewLocation } from '@service-storage/generated/schemas/getDocumentResponseDataViewLocation';
-import type { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';
-import type { IModificationData } from '../type/coParse';
-
-export const pdfDocumentProxy = createBlockSignal<PDFDocumentProxy>();
-export const pdfViewLocation =
- createBlockSignal<GetDocumentResponseDataViewLocation>();
-
-export const pdfModificationDataStore = createBlockStore<IModificationData>({
- bookmarks: [],
- placeables: [],
- pinnedTermsNames: [],
-});
-export const pdfOverlays = createBlockSignal<string[]>();
diff --git a/apps/web/src/features/block-pdf/signal/location.ts b/apps/web/src/features/block-pdf/signal/location.ts
index 0c89f055e1..ad1c102c8e 100644
--- a/apps/web/src/features/block-pdf/signal/location.ts
+++ b/apps/web/src/features/block-pdf/signal/location.ts
@@ -5,25 +5,13 @@ import {
type IUpdateFindControlStateEvent,
} from '@block-pdf/PdfViewer/EventBus';
import type { FindController } from '@block-pdf/PdfViewer/FindController';
-import {
- createBlockEffect,
- createBlockSignal,
- createBlockStore,
- useBlockId,
-} from '@core/block';
import { useReferralCode } from '@core/context/user';
import { buildSimpleEntityUrl } from '@core/util/url';
import { waitForSignal } from '@core/util/waitForSignal';
import { createCallback } from '@solid-primitives/rootless';
-import { type Accessor, createMemo } from 'solid-js';
+import { type Accessor, createEffect, createMemo } from 'solid-js';
import { z } from 'zod';
-import { pdfViewLocation } from './document';
-import {
- updateFindControlStateSignal,
- useGetRootViewer,
- viewerHasVisiblePagesSignal,
- viewerReadySignal,
-} from './pdfViewer';
+import { usePdfDocument } from '../context/pdf-document-context';
export { URL_PARAMS };
@@ -121,54 +109,41 @@ export const PdfOrderInfoSchema = z.object({
export type PdfOrderInfo = z.infer<typeof PdfOrderInfoSchema>;
-export const locationChangedSignal = createBlockSignal<boolean>(false);
-
-export const pendingLocationParamsSignal =
- createBlockSignal<LocationBlockParams>();
-
-export const searchLocationPendingSignal = createBlockSignal<boolean>(false);
-
const useIsViewerReadyForScroll = () => {
- const viewerHasVisiblePages = viewerHasVisiblePagesSignal.get;
- return createMemo(() => viewerReadySignal() && viewerHasVisiblePages());
+ const pdf = usePdfDocument();
+ const [viewerHasVisiblePages] = pdf.state.signals.viewerHasVisiblePages;
+ return createMemo(
+ () => pdf.state.derived.viewerReady() && viewerHasVisiblePages()
+ );
};
-createBlockEffect(() => {
- const getViewer = useGetRootViewer();
+export function usePendingLocationNavigationEffect() {
+ const pdf = usePdfDocument();
+ const [rootViewer] = pdf.state.signals.rootViewer;
+ const [pendingLocationParams] = pdf.state.signals.pendingLocationParams;
const goToLinkLocationFromParams = useGoToLinkLocationFromParams();
const isViewerReady = useIsViewerReadyForScroll();
- const params = pendingLocationParamsSignal();
-
- if (isViewerReady() && params) {
- // TODO: do we need to clear all overlays here
- getViewer()?.clearAllOverlays();
-
- goToLinkLocationFromParams(params);
- }
-});
+ createEffect(() => {
+ const params = pendingLocationParams();
+ if (isViewerReady() && params) {
+ // TODO: do we need to clear all overlays here
+ rootViewer()?.clearAllOverlays();
-export const locationStore = createBlockStore<{
- general: GeneralLocation | undefined;
- precise: PreciseLocation | undefined;
- annotation: AnnotationLocation | undefined;
- search: SearchLocation | undefined;
-}>({
- general: undefined,
- precise: undefined,
- annotation: undefined,
- search: undefined,
-});
+ void goToLinkLocationFromParams(params);
+ }
+ });
+}
export function useSetLocationStore() {
- const setLocationStore_ = locationStore.set;
+ const [, setLocation] = usePdfDocument().state.stores.location;
const setLocationStore = <T extends PdfLocationType>(
type: T,
location: Omit<LocationTypeMap[T], 'type'> | undefined
): void => {
if (type === 'precise') {
- setLocationStore_('annotation', undefined);
+ setLocation('annotation', undefined);
}
const l: LocationTypeMap[T] | undefined = location
@@ -177,19 +152,12 @@ export function useSetLocationStore() {
type,
} as LocationTypeMap[T])
: undefined;
- setLocationStore_(type, l);
+ setLocation(type, l);
};
return createCallback(setLocationStore);
}
-export const generalPopupLocationSignal = createBlockSignal<{
- pageIndex: number;
- element: HTMLElement;
- hasHighlight?: boolean;
- hasComment?: boolean;
-} | null>(null);
-
/**
* Converts a location into URL parameters for sharing.
*
@@ -263,8 +231,8 @@ export function selectLocationForFidelity(
}
export function useCreateShareUrl() {
- const locationStore_ = locationStore.get;
- const blockId = useBlockId();
+ const pdf = usePdfDocument();
+ const [locationStore] = pdf.state.stores.location;
const referralCode = useReferralCode();
/**
@@ -279,13 +247,13 @@ export function useCreateShareUrl() {
copy: boolean = true
): string => {
const locations = {
- general: locationStore_.general,
- precise: locationStore_.precise,
- annotation: locationStore_.annotation,
- search: locationStore_.search,
+ general: locationStore.general,
+ precise: locationStore.precise,
+ annotation: locationStore.annotation,
+ search: locationStore.search,
};
- const location = selectLocationForFidelity(fidelity, locations);
- const url = locationToUrl(location);
+ const selectedLocation = selectLocationForFidelity(fidelity, locations);
+ const url = locationToUrl(selectedLocation);
const params = Object.fromEntries(new URL(url).searchParams);
const code = referralCode();
if (code) {
@@ -294,7 +262,7 @@ export function useCreateShareUrl() {
const updatedUrl = buildSimpleEntityUrl(
{
type: 'pdf',
- id: blockId,
+ id: pdf.documentId(),
},
params
);
@@ -542,12 +510,14 @@ async function applyCustomHighlights(
* @param location - The location to go to
*/
function useGoToPdfLocation() {
- const getRootViewer = useGetRootViewer();
- const findControllerStateEventSignal = updateFindControlStateSignal.get;
- const setSearchLocationPending = searchLocationPendingSignal.set;
+ const pdf = usePdfDocument();
+ const [rootViewer] = pdf.state.signals.rootViewer;
+ const [findControllerStateEventSignal] =
+ pdf.state.signals.updateFindControlState;
+ const [, setSearchLocationPending] = pdf.state.signals.searchLocationPending;
const go = async (location: PdfLocation): Promise<void> => {
- const viewer = getRootViewer();
+ const viewer = rootViewer();
if (!viewer) return;
switch (location.type) {
@@ -692,18 +662,19 @@ function useGoToPdfLocation() {
}
const useGoToPreviousLocation = () => {
- const getViewer = useGetRootViewer();
- const getViewLocation = pdfViewLocation.get;
+ const pdf = usePdfDocument();
+ const [viewer] = pdf.state.signals.rootViewer;
+ const [viewLocation] = pdf.state.signals.viewLocation;
const isViewerReady = useIsViewerReadyForScroll();
return async () => {
- const viewer = getViewer();
+ const rootViewer = viewer();
- await waitForSignal(getViewLocation, (location) => !!location, 300).then(
+ await waitForSignal(viewLocation, (location) => !!location, 300).then(
(prevLocationHash) => {
waitForSignal(isViewerReady).then(() => {
- if (viewer && prevLocationHash) {
- viewer.goToLocationHash(prevLocationHash);
+ if (rootViewer && prevLocationHash) {
+ rootViewer.goToLocationHash(prevLocationHash);
}
});
}
diff --git a/apps/web/src/features/block-pdf/signal/pdfBlockData.ts b/apps/web/src/features/block-pdf/signal/pdfBlockData.ts
deleted file mode 100644
index 35622f8737..0000000000
--- a/apps/web/src/features/block-pdf/signal/pdfBlockData.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { blockDataSignalAs } from '@core/block';
-import type { PdfBlockData } from '../definition';
-
-// You really shouldn't use this unless you REALLY need to
-// Instead, use the signals in document.ts
-export const pdfBlockDataSignal = blockDataSignalAs<PdfBlockData>('pdf');
diff --git a/apps/web/src/features/block-pdf/signal/pdfViewer.tsx b/apps/web/src/features/block-pdf/signal/pdfViewer.tsx
index 5bbbaea115..8c97336c8f 100644
--- a/apps/web/src/features/block-pdf/signal/pdfViewer.tsx
+++ b/apps/web/src/features/block-pdf/signal/pdfViewer.tsx
@@ -1,20 +1,6 @@
-import {
- createBlockEffect,
- createBlockMemo,
- createBlockSignal,
- createBlockStore,
-} from '@core/block';
-import { setEquals } from '@core/util/compareUtils';
-import {
- createContext,
- createMemo,
- type ParentComponent,
- useContext,
-} from 'solid-js';
-import { reconcile } from 'solid-js/store';
+import { createContext, type ParentComponent, useContext } from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
import { PDFViewer } from '../PdfViewer';
-import type { IUpdateViewArea, TEvents } from '../PdfViewer/EventBus';
-import { ZOOM_MAX, ZOOM_MIN } from '../PdfViewer/zoom';
type PageViewportWithScale = {
width: number;
@@ -43,26 +29,13 @@ export const initializePdfViewer = (popupViewer?: PDFViewer) => {
return new PDFViewer(popupViewer);
};
-const popupPdfViewerSignal = createBlockSignal<PDFViewer | undefined>();
-const rootPdfViewerSignal = createBlockSignal<PDFViewer | undefined>();
-
-export const useSetRootViewer = () => {
- const set = rootPdfViewerSignal.set;
- return (viewer: PDFViewer | undefined) => set(viewer);
-};
-
-export const useSetPopupViewer = () => {
- const set = popupPdfViewerSignal.set;
- return (viewer: PDFViewer | undefined) => set(viewer);
-};
-
export const useGetRootViewer = () => {
- const viewer = rootPdfViewerSignal.get;
+ const [viewer] = usePdfDocument().state.signals.rootViewer;
return () => viewer();
};
export const useGetPopupViewer = () => {
- const viewer = popupPdfViewerSignal.get;
+ const [viewer] = usePdfDocument().state.signals.popupViewer;
return () => viewer();
};
@@ -73,164 +46,15 @@ export const useGetPopupContextViewer = () => {
return () => (isPopup ? getPopupViewer() : getRootViewer());
};
-// @ts-ignore
-const _visiblePagesEqual = (prev?: IUpdateViewArea, next?: IUpdateViewArea) => {
- const isEqual =
- prev != null &&
- next != null &&
- !next.forceUpdate &&
- // checking for scale change allows change on zoom/resize
- (prev.location.viewportScale === next.location.viewportScale ||
- Math.abs(prev.location.viewportScale - next.location.viewportScale) <
- 0.01) &&
- setEquals(prev.visiblePages.ids, next.visiblePages.ids);
- return isEqual;
-};
-
-const pagesLoadedSignal = createBlockSignal<TEvents['pagesloaded']>();
-const scaleChangingSignal = createBlockSignal<TEvents['scalechanging']>();
-const pageChangingSignal = createBlockSignal<TEvents['pagechanging']>();
-const overlayViewsChangedSignal =
- createBlockSignal<TEvents['overlayViewsChanged']>();
-const popupVisibilityChangedSignal =
- createBlockSignal<TEvents['popupvisibilitychanged']>();
-export const visiblePagesChangedSignal = createBlockSignal<
- TEvents['updateviewarea'] | undefined
->();
-export const updateFindControlStateSignal = createBlockSignal<
- TEvents['updatefindcontrolstate'] | undefined
->();
-export const updateFindMatchesCountSignal = createBlockSignal<
- TEvents['updatefindmatchescount'] | undefined
->();
-
-const scaleChangingPopupSignal = createBlockSignal<TEvents['scalechanging']>();
-const pageChangingPopupSignal = createBlockSignal<TEvents['pagechanging']>();
-const overlayViewsChangedPopupSignal =
- createBlockSignal<TEvents['overlayViewsChanged']>();
-const visiblePagesChangedPopupSignal = createBlockSignal<
- TEvents['updateviewarea'] | undefined
->();
-
-export const popupOpen = createBlockMemo(
- () => popupVisibilityChangedSignal()?.isOpen ?? false
-);
-
-export const currentPageNumber = createBlockMemo(
- () => pageChangingSignal()?.pageNumber ?? 1
-);
-
// NOTE: this fires off on every change because the isEqual function is not working
export const useVisiblePages = () => {
+ const { visiblePagesChanged, visiblePagesChangedPopup } =
+ usePdfDocument().state.signals;
const isPopup = useIsPopup();
- const signal = isPopup
- ? visiblePagesChangedPopupSignal
- : visiblePagesChangedSignal;
- return () => signal()?.visiblePages;
-};
-
-const currentScale = createBlockMemo(() => scaleChangingSignal()?.scale);
-
-export const canZoomIn = createBlockMemo(() => {
- const cs = currentScale();
- return !!(cs && cs < ZOOM_MAX);
-});
-
-export const canZoomOut = createBlockMemo(() => {
- const cs = currentScale();
- return !!(cs && cs > ZOOM_MIN);
-});
-export const pageCount = createBlockMemo(() => pagesLoadedSignal()?.pagesCount);
-
-export const popupCurrentPageNumber = createBlockMemo(
- () => pageChangingPopupSignal()?.pageNumber ?? 1
-);
-export const popupCurrentScale = createBlockMemo(
- () => scaleChangingPopupSignal()?.scale
-);
-
-export const useAttachViewerSignals = () => {
- const setPagesLoaded = pagesLoadedSignal.set;
- const setScaleChanging = scaleChangingSignal.set;
- const setPageChanging = pageChangingSignal.set;
- const setOverlayViewsChanged = overlayViewsChangedSignal.set;
- const setPopupVisibilityChanged = popupVisibilityChangedSignal.set;
- const setVisiblePagesChanged = visiblePagesChangedSignal.set;
- const setUpdateFindControlState = updateFindControlStateSignal.set;
- const setUpdateFindMatchesCount = updateFindMatchesCountSignal.set;
-
- const setScaleChangingPopup = scaleChangingPopupSignal.set;
- const setPageChangingPopup = pageChangingPopupSignal.set;
- const setOverlayViewsChangedPopup = overlayViewsChangedPopupSignal.set;
- const setVisiblePagesChangedPopup = visiblePagesChangedPopupSignal.set;
-
- // For reasons unknown to me, using viewer.isPopup causes the signal to not update
- return (viewer: PDFViewer, isPopup: boolean) => {
- if (isPopup) {
- viewer.event.on('scalechanging', setScaleChangingPopup);
- viewer.event.on('pagechanging', setPageChangingPopup);
- viewer.event.on('overlayViewsChanged', setOverlayViewsChangedPopup);
- viewer.event.on('updateviewarea', setVisiblePagesChangedPopup);
- return;
- }
-
- viewer.event.on('pagesloaded', setPagesLoaded);
- viewer.event.on('scalechanging', setScaleChanging);
- viewer.event.on('pagechanging', setPageChanging);
- viewer.event.on('overlayViewsChanged', setOverlayViewsChanged);
- viewer.event.on('popupvisibilitychanged', setPopupVisibilityChanged);
- viewer.event.on('updateviewarea', setVisiblePagesChanged);
- viewer.event.on('updatefindcontrolstate', setUpdateFindControlState);
- viewer.event.on('updatefindmatchescount', setUpdateFindMatchesCount);
- };
-};
-
-export const useDetachViewerSignals = () => {
- const setPagesLoaded = pagesLoadedSignal.set;
- const setScaleChanging = scaleChangingSignal.set;
- const setPageChanging = pageChangingSignal.set;
- const setOverlayViewsChanged = overlayViewsChangedSignal.set;
- const setPopupVisibilityChanged = popupVisibilityChangedSignal.set;
- const setVisiblePagesChanged = visiblePagesChangedSignal.set;
- const setUpdateFindControlState = updateFindControlStateSignal.set;
- const setUpdateFindMatchesCount = updateFindMatchesCountSignal.set;
-
- const setScaleChangingPopup = scaleChangingPopupSignal.set;
- const setPageChangingPopup = pageChangingPopupSignal.set;
- const setOverlayViewsChangedPopup = overlayViewsChangedPopupSignal.set;
- const setVisiblePagesChangedPopup = visiblePagesChangedPopupSignal.set;
-
- return (viewer: PDFViewer, isPopup: boolean) => {
- if (isPopup) {
- viewer.event.off('scalechanging', setScaleChangingPopup);
- viewer.event.off('pagechanging', setPageChangingPopup);
- viewer.event.off('overlayViewsChanged', setOverlayViewsChangedPopup);
- viewer.event.off('updateviewarea', setVisiblePagesChangedPopup);
- setScaleChangingPopup(undefined);
- setPageChangingPopup(undefined);
- setOverlayViewsChangedPopup(undefined);
- setVisiblePagesChangedPopup(undefined);
- return;
- }
-
- viewer.event.off('pagesloaded', setPagesLoaded);
- viewer.event.off('scalechanging', setScaleChanging);
- viewer.event.off('pagechanging', setPageChanging);
- viewer.event.off('overlayViewsChanged', setOverlayViewsChanged);
- viewer.event.off('popupvisibilitychanged', setPopupVisibilityChanged);
- viewer.event.off('updateviewarea', setVisiblePagesChanged);
- viewer.event.off('updatefindcontrolstate', setUpdateFindControlState);
- viewer.event.off('updatefindmatchescount', setUpdateFindMatchesCount);
-
- setPagesLoaded(undefined);
- setScaleChanging(undefined);
- setPageChanging(undefined);
- setOverlayViewsChanged(undefined);
- setPopupVisibilityChanged(undefined);
- setVisiblePagesChanged(undefined);
- setUpdateFindControlState(undefined);
- setUpdateFindMatchesCount(undefined);
- };
+ const [visiblePages] = isPopup
+ ? visiblePagesChangedPopup
+ : visiblePagesChanged;
+ return () => visiblePages()?.visiblePages;
};
const PopupContext = createContext<boolean>();
@@ -251,108 +75,39 @@ export function useIsPopup() {
}
export const useOverlayViewsChanged = () => {
+ const { overlayViewsChanged, overlayViewsChangedPopup } =
+ usePdfDocument().state.signals;
const isPopup = useIsPopup();
- const overlayViewsChangedPopupSignal_ = overlayViewsChangedPopupSignal.get;
- const overlayViewsChangedSignal_ = overlayViewsChangedSignal.get;
return () =>
- isPopup ? overlayViewsChangedPopupSignal_() : overlayViewsChangedSignal_();
+ isPopup ? overlayViewsChangedPopup[0]() : overlayViewsChanged[0]();
};
-export const viewerHasVisiblePagesSignal = createBlockSignal<boolean>(false);
-
-createBlockEffect(() => {
- const visiblePages = visiblePagesChangedSignal()?.visiblePages;
- const loadedIds = visiblePages?.ids;
- const hasVisiblePages = loadedIds ? loadedIds.size > 0 : false;
- viewerHasVisiblePagesSignal.set(hasVisiblePages);
-});
-
-// /** Indicates that all pages have been loaded */
-export const viewerReadySignal = createBlockMemo(() => {
- const pagesLoaded = pagesLoadedSignal();
- if (!pagesLoaded) return false;
- return pagesLoaded.pagesCount > 0;
-});
-
export const useCurrentPageNumber = () => {
- const getCurrentPageNumber = createMemo(currentPageNumber);
- return () => getCurrentPageNumber() ?? 1;
+ const currentPageNumber = usePdfDocument().state.derived.currentPageNumber;
+ return () => currentPageNumber() ?? 1;
};
// /** reactive values based on current page dimensions */
export const useCurrentPageViewport = () => {
+ const pdf = usePdfDocument();
const isPopup = useIsPopup();
const getViewer = useGetPopupContextViewer();
- const getViewerReady = createMemo(viewerReadySignal);
- const getCurrentPageNumber = createMemo(currentPageNumber);
- const getPopupCurrentPageNumber = createMemo(popupCurrentPageNumber);
+ const { currentPageNumber, popupCurrentPageNumber, viewerReady } =
+ pdf.state.derived;
return () => {
- const viewerReady = getViewerReady();
- const curPage = isPopup
- ? getPopupCurrentPageNumber()
- : getCurrentPageNumber();
+ const curPage = isPopup ? popupCurrentPageNumber() : currentPageNumber();
const viewer = getViewer();
- if (!viewerReady || !viewer || curPage == null || curPage < 1)
+ if (!viewerReady() || !viewer || curPage == null || curPage < 1)
return PAGE_VIEWPORT_DEFAULT;
return viewer.pageViewport(curPage - 1) ?? PAGE_VIEWPORT_DEFAULT;
};
};
export const useCurrentScale = () => {
+ const { currentScale, popupCurrentScale } = usePdfDocument().state.derived;
const isPopup = useIsPopup();
- const getCurrentScale = createMemo(currentScale);
- const getPopupCurrentScale = createMemo(popupCurrentScale);
return () => {
- return (isPopup ? getPopupCurrentScale() : getCurrentScale()) ?? 1;
+ return (isPopup ? popupCurrentScale() : currentScale()) ?? 1;
};
};
-
-type PageHeightStore = Partial<Record<number, number>>;
-/** Maps page index to page height */
-// TODO: in the future we can make this the entire viewport object but for now we only need the height
-export const pageHeightStore = createBlockStore<PageHeightStore>({});
-
-createBlockEffect(() => {
- const changeEvent = overlayViewsChangedSignal();
- if (!changeEvent) return;
-
- const updatedViewports: PageHeightStore = {};
- for (const pageView of Object.values(changeEvent.views)) {
- const pageIndex = pageView.id - 1;
- const viewport = pageView.viewport;
- updatedViewports[pageIndex] = viewport.height;
- }
-
- const setStore = pageHeightStore.set;
- setStore(reconcile(updatedViewports));
-});
-
-// export const useCurrentMaxPageWidth = () => {
-// const isPopup = useIsPopup();
-// const getViewer = useGetPopupContextViewer();
-// return () => {
-// const curPage = isPopup ? popupCurrentPageNumber() : currentPageNumber();
-// const viewer = getViewer();
-// if (!viewer || curPage == null) return 0;
-//
-// const defaultViewport = {
-// width: 0,
-// height: 0,
-// offsetX: 0,
-// offsetY: 0,
-// viewScale: 0,
-// relativeScale: 0,
-// pageHeight: 0,
-// pageWidth: 0,
-// };
-//
-// return [
-// viewer.pageViewport(curPage) ?? defaultViewport,
-// viewer.pageViewport(curPage - 1) ?? defaultViewport,
-// viewer.pageViewport(curPage + 1) ?? defaultViewport,
-// ]
-// .map((viewport) => viewport.width)
-// .sort((a, b) => b - a)[0];
-// };
-// };
diff --git a/apps/web/src/features/block-pdf/signal/permissions.ts b/apps/web/src/features/block-pdf/signal/permissions.ts
index d9aff5722d..b24369ee0c 100644
--- a/apps/web/src/features/block-pdf/signal/permissions.ts
+++ b/apps/web/src/features/block-pdf/signal/permissions.ts
@@ -1,41 +1,38 @@
-import { commentsStore } from '@block-pdf/store/comments/commentStore';
-import { commentPlaceables } from '@block-pdf/store/comments/freeComments';
-import { highlightsUuidMap } from '@block-pdf/store/highlight';
-import { createBlockMemo } from '@core/block';
import { useUserId } from '@core/context/user';
-import { useCanEdit } from '@core/signal/permissions';
-import { createSelector } from 'solid-js';
-
-export const useCanEditModificationData = useCanEdit;
-
-const ownedCommentAnchorUuids = createBlockMemo(() => {
- const userId = useUserId()();
- if (!userId) {
- console.error('User ID not found, cannot get owned comment placeables');
- return [];
- }
- const owned =
- commentPlaceables()
- ?.filter((p) => p.owner === userId)
- .map((p) => p.internalId) ?? [];
- return owned;
-});
-
-const ownedCommentIds = createBlockMemo(() => {
- const userId = useUserId()();
- if (!userId) {
- console.error('User ID not found, cannot get owned comment placeables');
- return [];
- }
- const owned =
- Object.values(commentsStore.get ?? [])
- ?.filter((c) => c.owner === userId)
- .map((c) => c.id) ?? [];
- return owned;
-});
+import { createMemo, createSelector } from 'solid-js';
+import { usePdfDocument } from '../context/pdf-document-context';
+import { isThreadPlaceable } from '../type/placeables';
// true if user owns the comment placeable (by uuid)
export const useOwnedCommentPlaceableSelector = () => {
+ const pdf = usePdfDocument();
+ const userId = useUserId();
+ const [anchors] = pdf.state.resources.anchors;
+ const [newPlaceable] = pdf.state.signals.newPlaceable;
+ const ownedCommentAnchorUuids = createMemo(() => {
+ const currentUserId = userId();
+ if (!currentUserId) {
+ console.error('User ID not found, cannot get owned comment placeables');
+ return [];
+ }
+
+ const owned =
+ anchors()
+ ?.filter(
+ (anchor) =>
+ anchor.anchorType === 'placeable' && anchor.owner === currentUserId
+ )
+ .map((anchor) => anchor.uuid) ?? [];
+ const newComment = newPlaceable();
+ if (
+ newComment &&
+ isThreadPlaceable(newComment) &&
+ newComment.owner === currentUserId
+ ) {
+ owned.push(newComment.internalId);
+ }
+ return owned;
+ });
const ownedCommentSelector = createSelector(
ownedCommentAnchorUuids,
(uuid: string, owned) => (owned ?? []).includes(uuid)
@@ -44,6 +41,19 @@ export const useOwnedCommentPlaceableSelector = () => {
};
export const useOwnedCommentSelector = () => {
+ const pdf = usePdfDocument();
+ const userId = useUserId();
+ const [comments] = pdf.state.stores.comments;
+ const ownedCommentIds = createMemo(() => {
+ const currentUserId = userId();
+ if (!currentUserId) {
+ console.error('User ID not found, cannot get owned comments');
+ return [];
+ }
+ return comments
+ .filter((comment) => comment.owner === currentUserId)
+ .map((comment) => comment.id);
+ });
const ownedCommentSelector = createSelector(
ownedCommentIds,
(id: number, owned) => (owned ?? []).includes(id)
@@ -52,7 +62,9 @@ export const useOwnedCommentSelector = () => {
};
export const useOwnedHighlightSelector = () => {
+ const pdf = usePdfDocument();
const userId = useUserId();
+ const highlightsUuidMap = pdf.state.derived.highlightsUuidMap;
const ownedHighlightSelector = createSelector(
highlightsUuidMap,
(uuid: string, owned) => {
diff --git a/apps/web/src/features/block-pdf/signal/placeables.ts b/apps/web/src/features/block-pdf/signal/placeables.ts
deleted file mode 100644
index aa4da5efe2..0000000000
--- a/apps/web/src/features/block-pdf/signal/placeables.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import {
- type IPlaceable,
- PayloadMode,
- type PayloadType,
-} from '@block-pdf/type/placeables';
-import { createBlockSignal } from '@core/block';
-
-export const placeableModeSignal = createBlockSignal<PayloadType>(
- PayloadMode.NoMode
-);
-export const showTabBarSignal = createBlockSignal<boolean>(false);
-export const activePlaceableIdSignal = createBlockSignal<string>();
-export const newPlaceableSignal = createBlockSignal<IPlaceable>();
diff --git a/apps/web/src/features/block-pdf/signal/save.ts b/apps/web/src/features/block-pdf/signal/save.ts
index 8270b176ed..95d5a9229b 100644
--- a/apps/web/src/features/block-pdf/signal/save.ts
+++ b/apps/web/src/features/block-pdf/signal/save.ts
@@ -1,35 +1,24 @@
-import type { IModificationDataOnServer } from '@block-pdf/type/coParse';
-import { createBlockSignal, useBlockId } from '@core/block';
import { ENABLE_PDF_MODIFICATION_DATA_AUTOSAVE } from '@core/constant/featureFlags';
import { useUserId } from '@core/context/user';
import { refetchHistory } from '@queries/history/history';
import { storageServiceClient } from '@service-storage/client';
import { createMemo } from 'solid-js';
-import { highlightStore } from '../store/highlight';
-import { useTableOfContentsValue } from '../store/tableOfContents';
+import { usePdfDocument } from '../context/pdf-document-context';
import {
getSaveModificationData,
hashModificationData,
hashModificationDataSync,
} from '../util/buildModificationData';
-import { pdfModificationDataStore, pdfViewLocation } from './document';
-import { useGetRootViewer } from './pdfViewer';
-import { useCanEditModificationData } from './permissions';
-
-export const numOperations = createBlockSignal(0);
-const savingCountSignal = createBlockSignal(0);
-export const isSaving = createBlockSignal(false);
-export const modificationDataSaveRequired = createBlockSignal(false);
-export const serverModificationDataSignal =
- createBlockSignal<IModificationDataOnServer>();
+
export function useDoEdit() {
- const setNumOperations = numOperations.set;
+ const [, setNumOperations] = usePdfDocument().state.signals.numOperations;
return () => setNumOperations((prev) => prev + 1);
}
const useSaveWrapper = () => {
- const setIsSaving = isSaving.set;
- const [savingCount, setSaveCount] = savingCountSignal;
+ const { isSaving, savingCount } = usePdfDocument().state.signals;
+ const [, setIsSaving] = isSaving;
+ const [getSavingCount, setSavingCount] = savingCount;
return (save: () => Promise<void>, shouldSave: () => boolean) => {
return async () => {
@@ -38,14 +27,14 @@ const useSaveWrapper = () => {
if (!shouldSave()) return;
saving = true;
setIsSaving(true);
- setSaveCount((prev) => prev + 1);
+ setSavingCount((prev) => prev + 1);
await save();
} catch (e) {
console.error('Error saving PDF', e);
} finally {
if (saving) {
- const count = savingCount() - 1;
- setSaveCount(count);
+ const count = getSavingCount() - 1;
+ setSavingCount(count);
if (count === 0) {
setIsSaving(false);
}
@@ -56,8 +45,9 @@ const useSaveWrapper = () => {
};
export function useHasModificationData() {
- const highlightStoreValue = highlightStore.get;
- const pdfModificationValue = pdfModificationDataStore.get;
+ const { highlights, modificationData } = usePdfDocument().state.stores;
+ const [highlightStoreValue] = highlights;
+ const [pdfModificationValue] = modificationData;
return () =>
Object.keys(highlightStoreValue).length > 0 ||
@@ -65,12 +55,11 @@ export function useHasModificationData() {
}
export function useSaveModificationData() {
+ const pdf = usePdfDocument();
const saveWrapper = useSaveWrapper();
- const pdfModificationValue = pdfModificationDataStore.get;
- const tableOfContentsValue = useTableOfContentsValue();
- const documentId = useBlockId();
- const serverModificationData = serverModificationDataSignal.get;
- const canSave = useCanEditModificationData();
+ const [pdfModificationValue] = pdf.state.stores.modificationData;
+ const [tableOfContents] = pdf.state.stores.tableOfContents;
+ const [serverModificationData] = pdf.state.signals.serverModificationData;
const serverModificationDataHash = createMemo(() => {
const modificationData_ = serverModificationData();
@@ -84,18 +73,18 @@ export function useSaveModificationData() {
const placeables = pdfModificationValue.placeables ?? [];
const { modificationData } = getSaveModificationData({
placeables,
- TOCItems: tableOfContentsValue().items,
+ TOCItems: tableOfContents.items,
pinnedTerms: [],
});
const sha = hashModificationDataSync(modificationData);
- return canSave() && serverModificationDataHash() !== sha;
+ return pdf.permissions.canEdit() && serverModificationDataHash() !== sha;
};
const save = async () => {
const placeables = pdfModificationValue.placeables ?? [];
const { modificationData } = getSaveModificationData({
placeables,
- TOCItems: tableOfContentsValue().items,
+ TOCItems: tableOfContents.items,
pinnedTerms: [],
});
@@ -104,7 +93,7 @@ export function useSaveModificationData() {
const sha = await hashModificationData(modificationData);
serverSaves.push(
storageServiceClient.pdfSave({
- documentId,
+ documentId: pdf.documentId(),
modificationData,
sha,
})
@@ -120,10 +109,11 @@ export function useSaveModificationData() {
}
export function usePdfSaveLocation() {
+ const pdf = usePdfDocument();
const saveWrapper = useSaveWrapper();
- const viewer = useGetRootViewer();
- const [prevLocationHash, setPrevLocationHash] = pdfViewLocation;
- const documentId = useBlockId();
+ const [viewer] = pdf.state.signals.rootViewer;
+ const [prevLocationHash, setPrevLocationHash] =
+ pdf.state.signals.viewLocation;
const userId = useUserId();
const shouldSave = () => {
@@ -139,11 +129,11 @@ export function usePdfSaveLocation() {
setPrevLocationHash(location);
if (location == null) {
await storageServiceClient.deleteDocumentViewLocation({
- documentId,
+ documentId: pdf.documentId(),
});
} else {
await storageServiceClient.upsertDocumentViewLocation({
- documentId,
+ documentId: pdf.documentId(),
location,
});
}
diff --git a/apps/web/src/features/block-pdf/signal/search.ts b/apps/web/src/features/block-pdf/signal/search.ts
index 9b3128765b..99d213365a 100644
--- a/apps/web/src/features/block-pdf/signal/search.ts
+++ b/apps/web/src/features/block-pdf/signal/search.ts
@@ -1,5 +1,5 @@
import type { PDFViewer } from '@block-pdf/PdfViewer';
-import { createBlockSignal } from '@core/block';
+import { usePdfDocument } from '../context/pdf-document-context';
import {
FindState,
type IMatchesCount,
@@ -12,14 +12,6 @@ import {
} from '../store/tableOfContents';
import TocUtils from '../util/TocUtils';
import { generatePhrases } from '../util/wordSearchUtils';
-import {
- updateFindControlStateSignal,
- updateFindMatchesCountSignal,
- useGetRootViewer,
-} from './pdfViewer';
-
-export const searchSignal = createBlockSignal<string>('');
-export const isSearchOpenSignal = createBlockSignal<boolean>(false);
enum SearchMatchType {
Word = 'word',
@@ -49,12 +41,12 @@ type WordMatch = BaseMatch & {
type Match = EntityMatch | WordMatch;
function useMergedEventSignal() {
- const updateFindControlState = updateFindControlStateSignal.get;
- const updateFindMatchesCount = updateFindMatchesCountSignal.get;
+ const { updateFindControlState, updateFindMatchesCount } =
+ usePdfDocument().state.signals;
return (): IUpdateFindControlStateEvent | null => {
- const controlStateEvent = updateFindControlState();
- const matchesCount = updateFindMatchesCount();
+ const controlStateEvent = updateFindControlState[0]();
+ const matchesCount = updateFindMatchesCount[0]();
if (!controlStateEvent) return null;
@@ -185,9 +177,9 @@ function getWordMatches(
}
export function useSearchStart() {
- const getRootViewer = useGetRootViewer();
+ const [rootViewer] = usePdfDocument().state.signals.rootViewer;
return (args: Parameters<PDFViewer['search']>[0]) => {
- getRootViewer()?.search(args);
+ rootViewer()?.search(args);
};
}
@@ -230,7 +222,7 @@ export function useSearchResults() {
}
export function useJumpToResult() {
- const getRootViewer = useGetRootViewer();
+ const [rootViewer] = usePdfDocument().state.signals.rootViewer;
const mergedEvent = useMergedEventSignal();
return (match: Match) => {
@@ -240,7 +232,7 @@ export function useJumpToResult() {
matchIndex: match.matchNumber,
});
} else {
- getRootViewer()?.scrollTo({
+ rootViewer()?.scrollTo({
pageNumber: match.page + 1,
yPos: match.yPos,
});
@@ -249,8 +241,8 @@ export function useJumpToResult() {
}
export function useSearchClose() {
- const getRootViewer = useGetRootViewer();
+ const [rootViewer] = usePdfDocument().state.signals.rootViewer;
return () => {
- getRootViewer()?.findBarClose();
+ rootViewer()?.findBarClose();
};
}
diff --git a/apps/web/src/features/block-pdf/signal/tab.ts b/apps/web/src/features/block-pdf/signal/tab.ts
index e992da2918..3aa2d35f6b 100644
--- a/apps/web/src/features/block-pdf/signal/tab.ts
+++ b/apps/web/src/features/block-pdf/signal/tab.ts
@@ -1,12 +1,6 @@
-import {
- createBlockSignal,
- createBlockStore,
- useIsNestedBlock,
-} from '@core/block';
import { ENABLE_PDF_TABS } from '@core/constant/featureFlags';
import { createCallback } from '@solid-primitives/rootless';
-import { useCurrentPageNumber, useGetRootViewer } from './pdfViewer';
-import { showTabBarSignal } from './placeables';
+import { usePdfDocument } from '../context/pdf-document-context';
const TOP_PADDING = 0.2;
@@ -20,12 +14,12 @@ export type TabInfo = {
};
export function useGoToLocationHash() {
- const getRootViewer = useGetRootViewer();
+ const [rootViewer] = usePdfDocument().state.signals.rootViewer;
const createTab = useCreateTab();
const tabCount = useTabCount();
return createCallback((hash: string, newTab = false) => {
- const viewer = getRootViewer();
+ const viewer = rootViewer();
if (!viewer) return;
if (ENABLE_PDF_TABS && newTab && tabCount() < MAX_TAB_COUNT) {
createTab();
@@ -36,7 +30,7 @@ export function useGoToLocationHash() {
}
export function useGoToLocation() {
- const getRootViewer = useGetRootViewer();
+ const [rootViewer] = usePdfDocument().state.signals.rootViewer;
const createTab = useCreateTab();
const tabCount = useTabCount();
return createCallback(
@@ -46,7 +40,7 @@ export function useGoToLocation() {
callout: number;
newTab: boolean;
}) => {
- const viewer = getRootViewer();
+ const viewer = rootViewer();
if (!viewer) return;
if (ENABLE_PDF_TABS && loc.newTab && tabCount() < MAX_TAB_COUNT) {
@@ -78,46 +72,8 @@ const defaultTabData = (id: number) => ({
id,
});
-// Store a simple signal that goes up when we make a new tab
-const tabIdSignal = createBlockSignal<number>(0);
-
-export const tabDataStore = createBlockStore<TabInfo[]>([defaultTabData(0)]);
-export const activeTabIdSignal = createBlockSignal<number>(0);
-export const tabHistorySignal = createBlockSignal<number[]>([0]);
-
-function tabById(id: number): TabInfo | undefined {
- return tabDataStore.get.find((t) => t.id === id);
-}
-
-function tabIndexById(id: number): number {
- return tabDataStore.get.findIndex((t) => t.id === id);
-}
-
-function updateTabById(
- id: number,
- info?: { label?: string; locationHash?: string }
-): void {
- const index = tabIndexById(id);
- if (index === -1) return;
- if (info?.label) {
- tabDataStore.set(index, 'label', info.label);
- }
- if (info?.locationHash) {
- tabDataStore.set(index, 'locationHash', info.locationHash);
- }
-}
-
-function createTab(info: { label: string; locationHash: string }): number {
- tabIdSignal.set((p) => p + 1);
- const id = tabIdSignal.get();
- tabDataStore.set([
- ...tabDataStore.get,
- {
- ...info,
- id,
- },
- ]);
- return id;
+function tabById(tabs: readonly TabInfo[], id: number): TabInfo | undefined {
+ return tabs.find((tab) => tab.id === id);
}
/**
@@ -125,22 +81,25 @@ function createTab(info: { label: string; locationHash: string }): number {
* selected tab id, and pushes it to the tab history.
*/
export function useNavigateToTab() {
+ const pdf = usePdfDocument();
const updateCurrentTab = useUpdateCurrentTab();
- const setTabHistory = tabHistorySignal.set;
- const getRootViewer = useGetRootViewer();
+ const [tabs] = pdf.state.stores.tabData;
+ const [, setActiveTabId] = pdf.state.signals.activeTabId;
+ const [, setTabHistory] = pdf.state.signals.tabHistory;
+ const [rootViewer] = pdf.state.signals.rootViewer;
return createCallback((id: number) => {
- const viewer = getRootViewer();
+ const viewer = rootViewer();
if (!viewer) return;
// Store the current location in the current tab.
updateCurrentTab();
- const tab = tabById(id);
+ const tab = tabById(tabs, id);
if (tab === undefined) {
return;
}
tab.locationHash && viewer.goToLocationHash(tab.locationHash);
- activeTabIdSignal.set(id);
+ setActiveTabId(id);
setTabHistory((p) => [...p, id]);
});
}
@@ -150,16 +109,20 @@ export function useNavigateToTab() {
* pdf viewer in the currently active tab.
*/
export function useUpdateCurrentTab() {
- const getRootViewer = useGetRootViewer();
- const currentPageNumber = useCurrentPageNumber();
+ const pdf = usePdfDocument();
+ const [rootViewer] = pdf.state.signals.rootViewer;
+ const [activeTabId] = pdf.state.signals.activeTabId;
+ const [tabs, setTabs] = pdf.state.stores.tabData;
+ const currentPageNumber = pdf.state.derived.currentPageNumber;
return createCallback(() => {
- const viewer = getRootViewer();
+ const viewer = rootViewer();
if (!viewer) return;
- updateTabById(activeTabIdSignal.get(), {
- label: `Page ${currentPageNumber()}`,
- locationHash: viewer.getLocationHash(),
- });
+ const index = tabs.findIndex((tab) => tab.id === activeTabId());
+ if (index === -1) return;
+ setTabs(index, 'label', `Page ${currentPageNumber()}`);
+ const locationHash = viewer.getLocationHash();
+ if (locationHash) setTabs(index, 'locationHash', locationHash);
});
}
@@ -167,23 +130,31 @@ export function useUpdateCurrentTab() {
* Create a block-scoped function that creates a new tab.
*/
export function useCreateTab() {
+ const pdf = usePdfDocument();
const navigateToTab = useNavigateToTab();
- const [_, setActiveTabId] = activeTabIdSignal;
- const getRootViewer = useGetRootViewer();
- const currentPageNumber = useCurrentPageNumber();
- const setShowTabBar = showTabBarSignal.set;
- const isNestedBlock = useIsNestedBlock();
+ const [tabId, setTabId] = pdf.state.signals.tabId;
+ const [, setActiveTabId] = pdf.state.signals.activeTabId;
+ const [, setShowTabBar] = pdf.state.signals.showTabBar;
+ const [tabs, setTabs] = pdf.state.stores.tabData;
+ const [rootViewer] = pdf.state.signals.rootViewer;
+ const currentPageNumber = pdf.state.derived.currentPageNumber;
return createCallback((info?: { label: string; locationHash: string }) => {
- if (isNestedBlock) return;
+ if (pdf.isNested()) return;
- const viewer = getRootViewer();
+ const viewer = rootViewer();
if (!viewer) return;
- const newId = createTab({
- locationHash: info?.locationHash ?? viewer.getLocationHash() ?? '',
- label: info?.label ?? `Page ${currentPageNumber()}`,
- });
+ setTabId((previous) => previous + 1);
+ const newId = tabId();
+ setTabs([
+ ...tabs,
+ {
+ locationHash: info?.locationHash ?? viewer.getLocationHash() ?? '',
+ label: info?.label ?? `Page ${currentPageNumber()}`,
+ id: newId,
+ },
+ ]);
setShowTabBar(true);
navigateToTab(newId);
setActiveTabId(newId);
@@ -194,10 +165,11 @@ export function useCreateTab() {
* Create a block-scoped function that resets tab state.
*/
export function useClearTabs() {
- const setActiveTabId = activeTabIdSignal.set;
- const setTabHistory = tabHistorySignal.set;
- const setTabId = tabIdSignal.set;
- const setTabData = tabDataStore.set;
+ const pdf = usePdfDocument();
+ const [, setActiveTabId] = pdf.state.signals.activeTabId;
+ const [, setTabHistory] = pdf.state.signals.tabHistory;
+ const [, setTabId] = pdf.state.signals.tabId;
+ const [, setTabData] = pdf.state.stores.tabData;
return () => {
setTabId(0);
setActiveTabId(0);
@@ -210,8 +182,9 @@ export function useClearTabs() {
* Create a block-scoped function deletes a tab by id.
*/
export function useDeleteTab() {
- const [tabs, setTabs] = tabDataStore;
- const [tabHistory, setTabHistory] = tabHistorySignal;
+ const pdf = usePdfDocument();
+ const [tabs, setTabs] = pdf.state.stores.tabData;
+ const [tabHistory, setTabHistory] = pdf.state.signals.tabHistory;
const navigateToTab = useNavigateToTab();
return createCallback((id: number) => {
@@ -230,6 +203,6 @@ export function useDeleteTab() {
}
export function useTabCount() {
- const [tabs] = tabDataStore;
+ const [tabs] = usePdfDocument().state.stores.tabData;
return createCallback(() => tabs.length);
}
diff --git a/apps/web/src/features/block-pdf/signal/viewerThreeColumnLayout.ts b/apps/web/src/features/block-pdf/signal/viewerThreeColumnLayout.ts
index 6a0c733906..a81bede3ac 100644
--- a/apps/web/src/features/block-pdf/signal/viewerThreeColumnLayout.ts
+++ b/apps/web/src/features/block-pdf/signal/viewerThreeColumnLayout.ts
@@ -1,6 +1,3 @@
-import { createBlockSignal } from '@core/block';
-import type { ThreeColumnLayout } from '@core/util/threeColumnLayout';
-
export const THREAD_WIDTH = 293;
export const MIN_THREAD_GAP = 16;
export const THREAD_VERTICAL_GAP = 24;
@@ -19,64 +16,3 @@ export const MIN_COMFY_LEFT_WIDTH_PX = 265;
export const MIN_COMFY_SEARCH_WIDTH_PX = 300;
export const MIN_COMFY_PINS_WIDTH_PX = 200;
-
-// const RESIZE_DEBOUNCE_MS = 16;
-//
-// const viewerColumnConfig: ThreeColumnConfig = {
-// gutterPx: GUTTER_PX,
-// minLeftColumnWidth: MIN_LEFT_COLUMN_WIDTH,
-// minRightColumnWidth: MIN_RIGHT_COLUMN_WIDTH,
-// maxLeftHandWidth: MAX_EDITOR_LEFT_HAND_WIDTH,
-// rightHandWidth: 293,
-// };
-
-export const viewerThreeColumnLayout = createBlockSignal<ThreeColumnLayout>({
- isInitialized: false,
- leftWidth: DEFAULT_LEFT_WIDTH,
- rightWidth: THREAD_WIDTH,
- rightMargin: GUTTER_PX,
- centerWidth: -1,
- windowWidth: -1,
- marginWidth: -1,
-});
-
-// export const useViewerThreeColumnLayoutResizer = () => {
-// const debouncedSetLayout = createMemo(() =>
-// debounce(
-// (layout: ThreeColumnLayout) => setLayout(layout),
-// RESIZE_DEBOUNCE_MS
-// )
-// );
-// const [viewerThreeColumns, setLayout] = viewerThreeColumnLayout;
-// const windowSize = windowSizeSignal.get;
-// const priorWindowWidth = createBlockSignal<number>(0);
-// const [docWidth, setDocWidth] = createSignal<number>(0);
-// const currentMaxPageWidth = useCurrentMaxPageWidth();
-//
-// createEffect(() => {
-// if (!viewerReadySignal()) {
-// return;
-// }
-// const widest = currentMaxPageWidth();
-// console.log('setting doc width', widest);
-//
-// setDocWidth(widest);
-// });
-//
-// const windowWidth = windowSize().width;
-// createEffect(() => {
-// if (!viewerReadySignal()) {
-// return;
-// }
-//
-// const layout = resizeColumns(
-// docWidth(),
-// windowWidth,
-// viewerThreeColumns(),
-// viewerColumnConfig
-// );
-//
-// priorWindowWidth[1](windowWidth);
-// debouncedSetLayout()(layout);
-// });
-// };
diff --git a/apps/web/src/features/block-pdf/store/annotations.ts b/apps/web/src/features/block-pdf/store/annotations.ts
index 3d19920395..c7a58a0f46 100644
--- a/apps/web/src/features/block-pdf/store/annotations.ts
+++ b/apps/web/src/features/block-pdf/store/annotations.ts
@@ -1,16 +1,16 @@
-import { pdfModificationDataStore } from '@block-pdf/signal/document';
-import { serverModificationDataSignal } from '@block-pdf/signal/save';
import type { IModificationData } from '@block-pdf/type/coParse';
import type { IPlaceable } from '@block-pdf/type/placeables';
import type { PDFDocumentProxy } from 'pdfjs-dist';
import { batch, untrack } from 'solid-js';
import { reconcile } from 'solid-js/store';
+import { usePdfDocument } from '../context/pdf-document-context';
import { annotationsToPlaceables } from './placeables';
export const useLoadAnnotations = () => {
- const setPdfModificationData = pdfModificationDataStore.set;
-
- const serverModificationData = serverModificationDataSignal.get;
+ const pdfDocument = usePdfDocument();
+ const [, setModificationData] = pdfDocument.state.stores.modificationData;
+ const [serverModificationData] =
+ pdfDocument.state.signals.serverModificationData;
const hasServerModificationData = () => serverModificationData() != null;
// const getPageHighlightMap = (highlights: IHighlight[]): HighlightUuidMap => {
@@ -27,13 +27,16 @@ export const useLoadAnnotations = () => {
// return hmap;
// };
- return async (pdf: PDFDocumentProxy, modificationData: IModificationData) => {
+ return async (
+ documentProxy: PDFDocumentProxy,
+ modificationData: IModificationData
+ ) => {
// clearHighlightStore();
if (hasServerModificationData()) {
batch(() => {
// setHighlightStore(reconcile(modificationData.highlights));
- setPdfModificationData(
+ setModificationData(
'placeables',
reconcile(untrack(() => modificationData.placeables))
);
@@ -41,12 +44,12 @@ export const useLoadAnnotations = () => {
return;
}
- setPdfModificationData('placeables', reconcile([]));
+ setModificationData('placeables', reconcile([]));
// const allHighlights: [number, HighlightUuidMap][] = [];
const allPlaceables: IPlaceable[] = [];
- for (let pageIndex = 0; pageIndex < pdf.numPages; pageIndex++) {
+ for (let pageIndex = 0; pageIndex < documentProxy.numPages; pageIndex++) {
try {
- const page = await pdf.getPage(pageIndex + 1);
+ const page = await documentProxy.getPage(pageIndex + 1);
const pageViewport = page.getViewport({ scale: 1 });
const [annotations, _textContent] = await Promise.all([
@@ -83,7 +86,7 @@ export const useLoadAnnotations = () => {
// for (const [pageIndex, highlightsOnPage] of allHighlights) {
// setHighlightStore(pageIndex, highlightsOnPage);
// }
- setPdfModificationData('placeables', reconcile(allPlaceables));
+ setModificationData('placeables', reconcile(allPlaceables));
});
};
};
diff --git a/apps/web/src/features/block-pdf/store/comments/commentEffect.ts b/apps/web/src/features/block-pdf/store/comments/commentEffect.ts
index 97b351b0f7..f610395331 100644
--- a/apps/web/src/features/block-pdf/store/comments/commentEffect.ts
+++ b/apps/web/src/features/block-pdf/store/comments/commentEffect.ts
@@ -1,18 +1,18 @@
+import { usePdfDocument } from '@block-pdf/context/pdf-document-context';
+import { usePdfCommentRealtimeBehavior } from '@block-pdf/store/commentsResource';
import { createEffect, createMemo } from 'solid-js';
+import { useCommentLayoutBehavior } from './commentLayout';
import {
useDeleteNewComments,
useScrollToCommentThread,
} from './commentOperations';
-import {
- activeCommentThreadSignal,
- commentsStore,
- noScrollToActiveCommentThreadSignal,
-} from './commentStore';
+import { useCommentStoreBehavior } from './commentStore';
// remove the new temporary comment when it is no longer active
const useDeleteNewCommentEffect = () => {
const deleteNewComments = useDeleteNewComments();
- const activeCommentThread = activeCommentThreadSignal.get;
+ const [activeCommentThread] =
+ usePdfDocument().state.signals.activeCommentThread;
createEffect(() => {
const activeThreadId = activeCommentThread();
@@ -25,10 +25,10 @@ const useDeleteNewCommentEffect = () => {
// scroll to the active comment thread
const useScrollToActiveThreadEffect = () => {
const scrollToCommentThread = useScrollToCommentThread();
- const comments = commentsStore.get;
- const activeCommentThread = activeCommentThreadSignal.get;
-
- const noScrollToActiveCommentThread = noScrollToActiveCommentThreadSignal.get;
+ const { signals, stores } = usePdfDocument().state;
+ const [comments] = stores.comments;
+ const [activeCommentThread] = signals.activeCommentThread;
+ const [noScrollToActiveCommentThread] = signals.noScrollToActiveCommentThread;
const noScroll = createMemo(() => {
return noScrollToActiveCommentThread();
});
@@ -49,6 +49,9 @@ const useScrollToActiveThreadEffect = () => {
};
export const usePdfCommentEffects = () => {
+ useCommentStoreBehavior();
+ useCommentLayoutBehavior();
+ usePdfCommentRealtimeBehavior();
useDeleteNewCommentEffect();
useScrollToActiveThreadEffect();
};
diff --git a/apps/web/src/features/block-pdf/store/comments/commentLayout.ts b/apps/web/src/features/block-pdf/store/comments/commentLayout.ts
index fbfd5294aa..9a7c37b74e 100644
--- a/apps/web/src/features/block-pdf/store/comments/commentLayout.ts
+++ b/apps/web/src/features/block-pdf/store/comments/commentLayout.ts
@@ -1,48 +1,31 @@
-import { pageHeightStore } from '@block-pdf/signal/pdfViewer';
import { MIN_THREAD_GAP } from '@block-pdf/signal/viewerThreeColumnLayout';
import type {
CommentLayout,
+ CommentStore,
CommentViewerInitialLayout,
Overflow,
PdfRootLayout,
} from '@block-pdf/type/comments';
-import {
- createBlockMemo,
- createBlockRenderEffect,
- createBlockStore,
-} from '@core/block';
import { isRoot, type Root } from '@core/comments/commentType';
+import { createMemo, createRenderEffect } from 'solid-js';
import { reconcile } from 'solid-js/store';
-import { activeCommentThreadSignal, commentsStore } from './commentStore';
+import { usePdfDocument } from '../../context/pdf-document-context';
// how much to pad the container for the "show more" buttons
const CONTAINER_PADDING = 80;
/** Maps thread id to height of its measure container */
-type ThreadHeights = Record<number, number>;
-export const threadHeightStore = createBlockStore<Partial<ThreadHeights>>({});
+export type ThreadHeights = Record<number, number>;
/** Maps page index to comment layout on that page */
-type ThreadPositionsOnPage = Partial<Record<number, CommentLayout<Root>[]>>;
-export const threadsOnPagePositionStore =
- createBlockStore<ThreadPositionsOnPage>({});
+export type ThreadPositionsOnPage = Partial<
+ Record<number, CommentLayout<Root>[]>
+>;
const isPdfRootLayout = (
- comment: (typeof commentsStore.get)[number]
+ comment: CommentStore[number]
): comment is PdfRootLayout => isRoot(comment) && 'layout' in comment;
-const rootCommentsGroupedByPage = createBlockMemo(() => {
- const comments = commentsStore.get;
-
- const out: Record<number, PdfRootLayout[]> = {};
- comments.filter(isPdfRootLayout).forEach((comment) => {
- const pageIndex = comment.layout.pageIndex;
- if (!out[pageIndex]) out[pageIndex] = [];
- out[pageIndex].push(comment);
- });
- return out;
-});
-
function computeLayout<T>({
initialAnchor,
input,
@@ -97,111 +80,129 @@ function computeLayout<T>({
// todo: optistic update (esp. for placeable drag)
// TODO: make this dependent on current page only
// i.e. move this logic into a page specific component so it only runs on for the selected page
-createBlockRenderEffect(() => {
- const activeThread = activeCommentThreadSignal.get;
- const setStore = threadsOnPagePositionStore.set;
- const pageHeights = pageHeightStore.get;
- const threadHeights = threadHeightStore.get;
- const rootComments = rootCommentsGroupedByPage() ?? {};
-
- const groupedThreadLayoutsByPage: ThreadPositionsOnPage = {};
- for (const [pageIndexStr, comments] of Object.entries(rootComments)) {
- const pageIndex = parseInt(pageIndexStr);
-
- // TODO compute actual position based on container bounds, height and active atom
- const pageHeight = pageHeights[pageIndex];
-
- // there are no bounds for the container, cant compute position
- if (!pageHeight) {
- groupedThreadLayoutsByPage[pageIndex] = [];
- continue;
- }
+export function useCommentLayoutBehavior() {
+ const { signals, stores } = usePdfDocument().state;
+ const [activeCommentThread] = signals.activeCommentThread;
+ const [comments] = stores.comments;
+ const [pageHeights] = stores.pageHeight;
+ const [threadHeights] = stores.threadHeight;
+ const [, setThreadPositions] = stores.threadsOnPagePosition;
+
+ const rootCommentsGroupedByPage = createMemo(() => {
+ const out: Record<number, PdfRootLayout[]> = {};
+ comments.filter(isPdfRootLayout).forEach((comment) => {
+ const pageIndex = comment.layout.pageIndex;
+ if (!out[pageIndex]) out[pageIndex] = [];
+ out[pageIndex].push(comment);
+ });
+ return out;
+ });
- const sortedThreadsByOriginalPosition = comments
- .sort((a, b) => a.layout.originalYPosition - b.layout.originalYPosition)
- .map((t) => {
- return {
- ...t,
- height: threadHeights[t.threadId] ?? 0,
- };
+ createRenderEffect(() => {
+ const activeThread = activeCommentThread();
+ const rootComments = rootCommentsGroupedByPage();
+ const groupedThreadLayoutsByPage: ThreadPositionsOnPage = {};
+ for (const [pageIndexStr, comments] of Object.entries(rootComments)) {
+ const pageIndex = parseInt(pageIndexStr);
+
+ // TODO compute actual position based on container bounds, height and active atom
+ const pageHeight = pageHeights[pageIndex];
+
+ // there are no bounds for the container, cant compute position
+ if (!pageHeight) {
+ groupedThreadLayoutsByPage[pageIndex] = [];
+ continue;
+ }
+
+ const sortedThreadsByOriginalPosition = comments
+ .sort((a, b) => a.layout.originalYPosition - b.layout.originalYPosition)
+ .map((t) => {
+ return {
+ ...t,
+ height: threadHeights[t.threadId] ?? 0,
+ };
+ });
+
+ // there are no comment threads on this page, cant position nothing
+ if (sortedThreadsByOriginalPosition.length === 0) {
+ groupedThreadLayoutsByPage[pageIndex] = [];
+ continue;
+ }
+
+ // if no threads is active by default
+ // position threads as if the first one is active
+ const anchorPositionId =
+ activeThread ?? sortedThreadsByOriginalPosition[0].threadId;
+
+ let sliceTo = sortedThreadsByOriginalPosition.findIndex(
+ (t) => t.threadId === anchorPositionId
+ );
+ if (sliceTo === -1) {
+ sliceTo = 0;
+ }
+ const sliceFrom = sliceTo + 1;
+
+ // all threads on page above the anchor with height
+ const sliceAboveAnchor = sortedThreadsByOriginalPosition.slice(
+ 0,
+ sliceTo
+ );
+ // all threads on page below the anchor with height
+ const sliceBelowAnchor = sortedThreadsByOriginalPosition.slice(sliceFrom);
+
+ // calculate closest fit for anchor within bounds of container
+ const anchorElement = sortedThreadsByOriginalPosition[sliceTo];
+ const anchorId = anchorElement.threadId;
+ const anchorHeight = threadHeights[anchorId] ?? 0;
+
+ // check if original y plus height fits inside bounds for anchor
+ const paddedHeight = pageHeight - CONTAINER_PADDING;
+ let anchorTop = anchorElement.layout.originalYPosition;
+ let anchorEnd = anchorTop + anchorHeight;
+ if (anchorEnd > paddedHeight) {
+ const anchorOverflow = anchorEnd - paddedHeight;
+ anchorTop -= anchorOverflow;
+ }
+
+ // handle edge case where anchor element is larger than container
+ if (anchorTop < 0) {
+ anchorTop = 0;
+ }
+ anchorEnd = anchorTop + anchorHeight;
+
+ const layoutAboveAnchor = computeLayout({
+ initialAnchor: anchorTop,
+ direction: 'up',
+ input: sliceAboveAnchor,
+ containerHeight: pageHeight,
+ containerPadding: CONTAINER_PADDING,
});
- // there are no comment threads on this page, cant position nothing
- if (sortedThreadsByOriginalPosition.length === 0) {
- groupedThreadLayoutsByPage[pageIndex] = [];
- continue;
- }
-
- // if no threads is active by default
- // position threads as if the first one is active
- const anchorPositionId =
- activeThread() ?? sortedThreadsByOriginalPosition[0].threadId;
-
- let sliceTo = sortedThreadsByOriginalPosition.findIndex(
- (t) => t.threadId === anchorPositionId
- );
- if (sliceTo === -1) {
- sliceTo = 0;
- }
- const sliceFrom = sliceTo + 1;
-
- // all threads on page above the anchor with height
- const sliceAboveAnchor = sortedThreadsByOriginalPosition.slice(0, sliceTo);
- // all threads on page below the anchor with height
- const sliceBelowAnchor = sortedThreadsByOriginalPosition.slice(sliceFrom);
-
- // calculate closest fit for anchor within bounds of container
- const anchorElement = sortedThreadsByOriginalPosition[sliceTo];
- const anchorId = anchorElement.threadId;
- const anchorHeight = threadHeights[anchorId] ?? 0;
-
- // check if original y plus height fits inside bounds for anchor
- const paddedHeight = pageHeight - CONTAINER_PADDING;
- let anchorTop = anchorElement.layout.originalYPosition;
- let anchorEnd = anchorTop + anchorHeight;
- if (anchorEnd > paddedHeight) {
- const anchorOverflow = anchorEnd - paddedHeight;
- anchorTop -= anchorOverflow;
- }
-
- // handle edge case where anchor element is larger than container
- if (anchorTop < 0) {
- anchorTop = 0;
- }
- anchorEnd = anchorTop + anchorHeight;
-
- const layoutAboveAnchor = computeLayout({
- initialAnchor: anchorTop,
- direction: 'up',
- input: sliceAboveAnchor,
- containerHeight: pageHeight,
- containerPadding: CONTAINER_PADDING,
- });
-
- const layoutBelowAnchor = computeLayout({
- initialAnchor: anchorEnd,
- direction: 'down',
- input: sliceBelowAnchor,
- containerHeight: pageHeight,
- containerPadding: CONTAINER_PADDING,
- });
+ const layoutBelowAnchor = computeLayout({
+ initialAnchor: anchorEnd,
+ direction: 'down',
+ input: sliceBelowAnchor,
+ containerHeight: pageHeight,
+ containerPadding: CONTAINER_PADDING,
+ });
- // the positioning of all threads on the page
- const out: CommentLayout<Root>[] = [
- ...layoutAboveAnchor,
- {
- ...anchorElement,
- layout: {
- height: anchorHeight,
- calculatedYPos: anchorTop,
- overflow: null,
+ // the positioning of all threads on the page
+ const out: CommentLayout<Root>[] = [
+ ...layoutAboveAnchor,
+ {
+ ...anchorElement,
+ layout: {
+ height: anchorHeight,
+ calculatedYPos: anchorTop,
+ overflow: null,
+ },
},
- },
- ...layoutBelowAnchor,
- ];
+ ...layoutBelowAnchor,
+ ];
- groupedThreadLayoutsByPage[pageIndex] = out;
- }
+ groupedThreadLayoutsByPage[pageIndex] = out;
+ }
- setStore(reconcile(groupedThreadLayoutsByPage));
-});
+ setThreadPositions(reconcile(groupedThreadLayoutsByPage));
+ });
+}
diff --git a/apps/web/src/features/block-pdf/store/comments/commentOperations.ts b/apps/web/src/features/block-pdf/store/comments/commentOperations.ts
index 9fb6f1d9ea..09f4b3eb8a 100644
--- a/apps/web/src/features/block-pdf/store/comments/commentOperations.ts
+++ b/apps/web/src/features/block-pdf/store/comments/commentOperations.ts
@@ -1,11 +1,8 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { useGetRootViewer } from '@block-pdf/signal/pdfViewer';
-import { commentsStore } from '@block-pdf/store/comments/commentStore';
+import { usePdfDocument } from '@block-pdf/context/pdf-document-context';
import type { PdfRootLayout } from '@block-pdf/type/comments';
-import { useBlockId } from '@core/block';
import { type DeleteCommentInfo, isRoot } from '@core/comments/commentType';
import { threadMeasureContainerId } from '@core/comments/Thread';
-import { blockElementSignal } from '@core/signal/blockElement';
import type {
CreateCommentRequest,
EditCommentRequest,
@@ -20,18 +17,20 @@ import {
useDeleteCommentResource,
useEditCommentResource,
} from '../commentsResource';
-import { highlightsUuidMap } from '../highlight';
-import { newThreadPlaceable, useDeleteNewFreeComment } from './freeComments';
+import { useDeleteNewFreeComment, useNewThreadPlaceable } from './freeComments';
import { useDeleteNewHighlightComment } from './highlightComments';
export function useCreateComment() {
const analytics = useAnalytics();
+ const { stores, derived } = usePdfDocument().state;
+ const [comments] = stores.comments;
const deleteNewComments = useDeleteNewComments();
const createFreeComment = useCreateFreeCommentResource();
const createHighlightComment = useCreateHighlightCommentResource();
const attachHighlightComment = useAttachHighlightCommentResource();
const createThreadReply = useCreateThreadReplyResource();
+ const newThreadPlaceable = useNewThreadPlaceable();
return createCallback(
async (info: CreateCommentRequest & { threadId: number }) => {
@@ -40,7 +39,7 @@ export function useCreateComment() {
// new thread + anchor
if (threadId === -1) {
- const comment = commentsStore.get.find((c) => c.threadId === threadId);
+ const comment = comments.find((c) => c.threadId === threadId);
if (!comment) {
console.error('Unable to comment');
return null;
@@ -49,7 +48,7 @@ export function useCreateComment() {
let response: CreateCommentResponse | null = null;
switch (comment.type) {
case 'highlight':
- const highlight = highlightsUuidMap()?.[comment.anchorId];
+ const highlight = derived.highlightsUuidMap()?.[comment.anchorId];
if (!highlight) {
console.error('Unable to find highlight');
return response;
@@ -70,10 +69,10 @@ export function useCreateComment() {
}
break;
case 'free':
- const newThreadPlaceable_ = newThreadPlaceable();
+ const newThreadPlaceableValue = newThreadPlaceable();
if (
- !newThreadPlaceable_ ||
- newThreadPlaceable_.internalId !== comment.anchorId
+ !newThreadPlaceableValue ||
+ newThreadPlaceableValue.internalId !== comment.anchorId
) {
console.error('Unable to find new thread placeable');
return response;
@@ -81,7 +80,7 @@ export function useCreateComment() {
response = await createFreeComment(
text,
- newThreadPlaceable_,
+ newThreadPlaceableValue,
mentions
);
break;
@@ -149,10 +148,9 @@ export function useDeleteNewComments() {
}
export function useScrollToCommentThread() {
- const viewer = useGetRootViewer();
- const comments = commentsStore.get;
- const blockElement = blockElementSignal.get;
- const documentId = useBlockId();
+ const { documentId, rootElement, state } = usePdfDocument();
+ const [viewer] = state.signals.rootViewer;
+ const [comments] = state.stores.comments;
const scrollIntoView = (el: HTMLElement) => {
el.scrollIntoView({
@@ -163,11 +161,11 @@ export function useScrollToCommentThread() {
};
return async (threadId: number) => {
- const measureContainerId = threadMeasureContainerId(documentId, threadId);
+ const measureContainerId = threadMeasureContainerId(documentId(), threadId);
let measureContainer = document.getElementById(measureContainerId);
- const blockEl = blockElement();
- if (!blockEl) {
- console.error('Unable to find block element');
+ const pdfRoot = rootElement();
+ if (!pdfRoot) {
+ console.error('Unable to find PDF document root element');
return;
}
@@ -203,7 +201,7 @@ export function useScrollToCommentThread() {
intersectionObserver.observe(measureContainer);
scrollIntoView(measureContainer);
} else {
- mutationObserver.observe(blockEl, {
+ mutationObserver.observe(pdfRoot, {
childList: true,
subtree: true,
});
@@ -234,7 +232,7 @@ export function useScrollToCommentThread() {
scrollIntoView(measureContainer);
intersectionObserver.observe(measureContainer);
} else {
- mutationObserver.observe(blockEl, {
+ mutationObserver.observe(pdfRoot, {
childList: true,
subtree: true,
});
diff --git a/apps/web/src/features/block-pdf/store/comments/commentStore.ts b/apps/web/src/features/block-pdf/store/comments/commentStore.ts
index ea81c59bef..11a125bce7 100644
--- a/apps/web/src/features/block-pdf/store/comments/commentStore.ts
+++ b/apps/web/src/features/block-pdf/store/comments/commentStore.ts
@@ -1,25 +1,15 @@
-import { freeComments } from '@block-pdf/store/comments/freeComments';
-import { highlightComments } from '@block-pdf/store/comments/highlightComments';
-import type { CommentStore, PdfComment } from '@block-pdf/type/comments';
-import {
- createBlockEffect,
- createBlockMemo,
- createBlockSignal,
- createBlockStore,
-} from '@core/block';
+import { usePdfDocument } from '@block-pdf/context/pdf-document-context';
import type { ThreadId } from '@core/comments/commentType';
-import { createMemo, createSelector } from 'solid-js';
+import { createEffect, createMemo, createSelector } from 'solid-js';
import { reconcile } from 'solid-js/store';
-
-export const activeCommentThreadSignal = createBlockSignal<ThreadId | null>(
- null
-);
-
-export const noScrollToActiveCommentThreadSignal = createBlockSignal(false);
+import { useFreeComments } from './freeComments';
+import { useHighlightComments } from './highlightComments';
export const useIsActiveThreadSelector = () => {
+ const [activeCommentThread] =
+ usePdfDocument().state.signals.activeCommentThread;
const isSelected = createSelector(
- activeCommentThreadSignal,
+ activeCommentThread,
(id: ThreadId | null, activeId) => {
if (id == null) return false;
return id === activeId;
@@ -28,39 +18,27 @@ export const useIsActiveThreadSelector = () => {
return isSelected;
};
-export const commentsStore = createBlockStore<CommentStore>([]);
-
-type CommentMap = Map<number, PdfComment>;
-export const commentMap = createBlockMemo(() => {
- const commentMap: CommentMap = new Map();
- for (const comment of commentsStore.get ?? []) {
- commentMap.set(comment.id, comment);
- }
- return commentMap;
-});
-
export const useGetCommentById = () => {
- return (id: number) => commentMap()?.get(id);
+ const { commentMap } = usePdfDocument().state.derived;
+ return (id: number) => commentMap().get(id);
};
-const combinedComments = createBlockMemo(() => {
- const highlights = highlightComments() ?? [];
- const free = freeComments() ?? [];
- const combined = [...highlights, ...free];
- return combined;
-});
-
// NOTE: this lets us block on the comments store being loaded in
// but it does not distinguish between unloaded and non-existent comments states
export const useHasComments = () => {
+ const highlightComments = useHighlightComments();
+ const freeComments = useFreeComments();
return createMemo(() => {
- const combinedComments_ = combinedComments();
- return combinedComments_ && combinedComments_.length > 0;
+ return [...highlightComments(), ...freeComments()].length > 0;
});
};
-createBlockEffect(() => {
- const setComments = commentsStore.set;
- const combinedComments_ = combinedComments();
- setComments(reconcile(combinedComments_ ?? []));
-});
+export function useCommentStoreBehavior() {
+ const highlightComments = useHighlightComments();
+ const freeComments = useFreeComments();
+ const [, setComments] = usePdfDocument().state.stores.comments;
+
+ createEffect(() => {
+ setComments(reconcile([...highlightComments(), ...freeComments()]));
+ });
+}
diff --git a/apps/web/src/features/block-pdf/store/comments/freeComments.ts b/apps/web/src/features/block-pdf/store/comments/freeComments.ts
index 5b24bdcd5d..fd4a86f6ad 100644
--- a/apps/web/src/features/block-pdf/store/comments/freeComments.ts
+++ b/apps/web/src/features/block-pdf/store/comments/freeComments.ts
@@ -1,11 +1,3 @@
-import {
- pageHeightStore,
- viewerReadySignal,
-} from '@block-pdf/signal/pdfViewer';
-import {
- activePlaceableIdSignal,
- newPlaceableSignal,
-} from '@block-pdf/signal/placeables';
import type {
PdfComment,
PdfReply,
@@ -16,13 +8,10 @@ import {
type IThreadPlaceable,
isThreadPlaceable,
} from '@block-pdf/type/placeables';
-import { createBlockMemo } from '@core/block';
import { useUserId } from '@core/context/user';
-import {
- anchorsResource,
- commentThreadsResource,
- sortComments,
-} from '../commentsResource';
+import { createMemo } from 'solid-js';
+import { usePdfDocument } from '../../context/pdf-document-context';
+import { sortComments } from '../commentsResource';
export { isThreadPlaceable };
@@ -77,137 +66,150 @@ const getFreeCommentThread = (
return { root, replies };
};
-const serverCommentPlaceables = createBlockMemo<IThreadPlaceable[]>(() => {
- const [anchorsData] = anchorsResource;
- const anchors = anchorsData();
- if (!anchors || anchors.length === 0) return [];
+const useServerCommentPlaceables = () => {
+ const { resources } = usePdfDocument().state;
+ const [anchors] = resources.anchors;
+ const [commentThreads] = resources.commentThreads;
- const [commentThreadsData] = commentThreadsResource;
- const commentThreads = commentThreadsData();
- if (!commentThreads || commentThreads.length === 0) return [];
+ return createMemo<IThreadPlaceable[]>(() => {
+ const anchorsData = anchors();
+ if (!anchorsData || anchorsData.length === 0) return [];
- const freeCommentAnchors = anchors.filter(
- (a) => a.anchorType === 'placeable'
- );
+ const commentThreadsData = commentThreads();
+ if (!commentThreadsData || commentThreadsData.length === 0) return [];
- const mappedAnchors = freeCommentAnchors.flatMap((a) => {
- const commentThread = commentThreads.find(
- (ct) => ct.thread.threadId === a.threadId
+ const freeCommentAnchors = anchorsData.filter(
+ (a) => a.anchorType === 'placeable'
);
- if (!commentThread) {
- console.error('Comment thread not found for free comment anchor', a);
- return [];
- }
- // TODO: deprecate unneeded fields
- const placeable: IThreadPlaceable = {
- owner: a.owner,
- isNew: false,
- internalId: a.uuid,
- payloadType: 'thread',
- position: {
- xPct: a.xPct,
- yPct: a.yPct,
- widthPct: a.widthPct,
- heightPct: a.heightPct,
- rotation: 0,
- },
- payload: {
- threadId: commentThread.thread.threadId,
- rootId: commentThread.comments[0].commentId,
- anchorId: a.uuid,
- page: a.page,
- comments: commentThread.comments,
- isResolved: commentThread.thread.resolved,
- },
- allowableEdits: a.allowableEdits as any,
- wasEdited: a.wasEdited,
- wasDeleted: a.wasDeleted,
- pageRange: new Set([a.page]),
- originalPage: a.originalPage,
- originalIndex: a.originalIndex,
- shouldLockOnSave: a.shouldLockOnSave,
- };
-
- return placeable;
+ return freeCommentAnchors.flatMap((a) => {
+ const commentThread = commentThreadsData.find(
+ (ct) => ct.thread.threadId === a.threadId
+ );
+ if (!commentThread) {
+ console.error('Comment thread not found for free comment anchor', a);
+ return [];
+ }
+
+ // TODO: deprecate unneeded fields
+ const placeable: IThreadPlaceable = {
+ owner: a.owner,
+ isNew: false,
+ internalId: a.uuid,
+ payloadType: 'thread',
+ position: {
+ xPct: a.xPct,
+ yPct: a.yPct,
+ widthPct: a.widthPct,
+ heightPct: a.heightPct,
+ rotation: 0,
+ },
+ payload: {
+ threadId: commentThread.thread.threadId,
+ rootId: commentThread.comments[0].commentId,
+ anchorId: a.uuid,
+ page: a.page,
+ comments: commentThread.comments,
+ isResolved: commentThread.thread.resolved,
+ },
+ allowableEdits: a.allowableEdits as any,
+ wasEdited: a.wasEdited,
+ wasDeleted: a.wasDeleted,
+ pageRange: new Set([a.page]),
+ originalPage: a.originalPage,
+ originalIndex: a.originalIndex,
+ shouldLockOnSave: a.shouldLockOnSave,
+ };
+
+ return placeable;
+ });
});
+};
- return mappedAnchors;
-});
+export const useNewThreadPlaceable = () => {
+ const [newPlaceable] = usePdfDocument().state.signals.newPlaceable;
+ return createMemo<IThreadPlaceable | undefined>(() => {
+ const value = newPlaceable();
+ if (!value || !isThreadPlaceable(value)) return undefined;
+ return value;
+ });
+};
-export const newThreadPlaceable = createBlockMemo<IThreadPlaceable | undefined>(
- () => {
- const newPlaceable = newPlaceableSignal.get();
- if (!newPlaceable || !isThreadPlaceable(newPlaceable)) return undefined;
- return newPlaceable;
- }
-);
+export const useCommentPlaceables = () => {
+ const serverCommentPlaceables = useServerCommentPlaceables();
+ const newThreadPlaceable = useNewThreadPlaceable();
+
+ return createMemo<IThreadPlaceable[]>(() => {
+ const serverArr = serverCommentPlaceables();
+ const newPlaceable = newThreadPlaceable();
+ if (!newPlaceable) return serverArr;
-export const commentPlaceables = createBlockMemo<IThreadPlaceable[]>(() => {
- const serverArr = serverCommentPlaceables() ?? [];
- const newPlaceable = newThreadPlaceable();
- if (!newPlaceable) return serverArr;
+ return [newPlaceable, ...serverArr];
+ });
+};
- return [newPlaceable, ...serverArr];
-});
+export const useFreeComments = () => {
+ const userId = useUserId();
+ const { stores, derived } = usePdfDocument().state;
+ const [pageHeights] = stores.pageHeight;
+ const commentPlaceables = useCommentPlaceables();
-export const freeComments = createBlockMemo(() => {
- const pageHeights = pageHeightStore.get;
- const userId = useUserId()();
- if (!viewerReadySignal()) return [];
+ return createMemo(() => {
+ if (!derived.viewerReady()) return [];
- const out: PdfComment[] = [];
- for (const commentPlaceable of commentPlaceables() ?? []) {
- const pageIndex = commentPlaceable.originalPage;
- const height = pageHeights[pageIndex] ?? 0;
+ const out: PdfComment[] = [];
+ for (const commentPlaceable of commentPlaceables()) {
+ const pageIndex = commentPlaceable.originalPage;
+ const height = pageHeights[pageIndex] ?? 0;
- const originalYPosition = getThreadPlaceablePos(commentPlaceable, height);
+ const originalYPosition = getThreadPlaceablePos(commentPlaceable, height);
- const layout = {
- pageIndex,
- originalYPosition,
- };
+ const layout = {
+ pageIndex,
+ originalYPosition,
+ };
- const isNew = commentPlaceable.payload == null;
- if (isNew) {
- if (!userId) {
- console.error('User ID not found');
+ const isNew = commentPlaceable.payload == null;
+ if (isNew) {
+ const currentUserId = userId();
+ if (!currentUserId) {
+ console.error('User ID not found');
+ continue;
+ }
+ const rootComment: PdfRoot = {
+ id: -1,
+ rootId: -1,
+ type: 'free',
+ text: '',
+ owner: currentUserId,
+ author: currentUserId,
+ createdAt: new Date(),
+ isNew: true,
+ children: [],
+ threadId: -1,
+ anchorId: commentPlaceable.internalId,
+ };
+ out.push({ ...rootComment, layout });
continue;
}
- const rootComment: PdfRoot = {
- id: -1,
- rootId: -1,
- type: 'free',
- text: '',
- owner: userId,
- author: userId,
- createdAt: new Date(),
- isNew: true,
- children: [],
- threadId: -1,
- anchorId: commentPlaceable.internalId,
- };
- out.push({ ...rootComment, layout });
- continue;
- }
- const freeCommentThread = getFreeCommentThread(commentPlaceable);
- if (!freeCommentThread) continue;
+ const freeCommentThread = getFreeCommentThread(commentPlaceable);
+ if (!freeCommentThread) continue;
- const { root, replies } = freeCommentThread;
- out.push({ ...root, layout });
- replies.forEach((reply) => out.push(reply));
- }
+ const { root, replies } = freeCommentThread;
+ out.push({ ...root, layout });
+ replies.forEach((reply) => out.push(reply));
+ }
- return out;
-});
+ return out;
+ });
+};
export const useDeleteNewFreeComment = () => {
- const setActivePlaceableId = activePlaceableIdSignal.set;
- const setNewPlaceable = newPlaceableSignal.set;
+ const { activePlaceableId, newPlaceable } = usePdfDocument().state.signals;
return () => {
- setNewPlaceable(undefined);
- setActivePlaceableId(undefined);
+ newPlaceable[1](undefined);
+ activePlaceableId[1](undefined);
};
};
diff --git a/apps/web/src/features/block-pdf/store/comments/highlightComments.ts b/apps/web/src/features/block-pdf/store/comments/highlightComments.ts
index 7eb8177248..acde526e30 100644
--- a/apps/web/src/features/block-pdf/store/comments/highlightComments.ts
+++ b/apps/web/src/features/block-pdf/store/comments/highlightComments.ts
@@ -1,11 +1,5 @@
import { useHighlightSelection } from '@block-pdf/component/UserHighlight';
-import { disablePageViewClickSignal } from '@block-pdf/signal/click';
-import { generalPopupLocationSignal } from '@block-pdf/signal/location';
-import {
- pageHeightStore,
- useCurrentPageViewport,
- viewerReadySignal,
-} from '@block-pdf/signal/pdfViewer';
+import { useCurrentPageViewport } from '@block-pdf/signal/pdfViewer';
import type {
PdfComment,
PdfReply,
@@ -13,30 +7,19 @@ import type {
ViewerCommentType,
} from '@block-pdf/type/comments';
import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';
-import { createBlockMemo, createBlockSignal } from '@core/block';
import { useUserId } from '@core/context/user';
import { createCallback } from '@solid-primitives/rootless';
-import { batch } from 'solid-js';
+import { batch, createMemo } from 'solid-js';
import { produce } from 'solid-js/store';
+import { usePdfDocument } from '../../context/pdf-document-context';
import {
Highlight,
HighlightType,
type IHighlight,
} from '../../model/Highlight';
-import {
- highlightStore,
- highlightsUuidMap,
- selectionStore,
- useAddNewHighlightComments,
-} from '../../store/highlight';
import { sortComments } from '../commentsResource';
import { useDeleteNewComments } from './commentOperations';
-import { activeCommentThreadSignal, useGetCommentById } from './commentStore';
-
-// highlight uuid that is converted to a comment. This allows us to revert to a regular highlight if the user cancels the comment operation
-export const convertedHighlightThreadIdSignal = createBlockSignal<
- string | null
->(null);
+import { useGetCommentById } from './commentStore';
const getHighlightPos = (highlight: IHighlight, viewportHeight: number) => {
try {
@@ -97,63 +80,67 @@ const getHighlightThread = (
return { root, replies };
};
-export const highlightComments = createBlockMemo(() => {
- const userId = useUserId()();
- const pageHeights = pageHeightStore.get;
- if (!viewerReadySignal()) return [];
-
- const out: PdfComment[] = [];
- for (const [pageIndexStr, pageHighlights] of Object.entries(
- highlightStore.get
- )) {
- if (!pageHighlights) continue;
- const pageIndex = parseInt(pageIndexStr);
- const height = pageHeights[pageIndex] ?? 0;
-
- for (const highlight of Object.values(pageHighlights)) {
- if (!highlight) continue;
-
- const originalYPosition = getHighlightPos(highlight, height);
- if (originalYPosition === null) continue;
-
- const layout = {
- pageIndex,
- originalYPosition,
- };
-
- // new highlight thread
- if (highlight.hasTempThread) {
- if (!userId) {
- console.error('User ID not found');
+export const useHighlightComments = () => {
+ const userId = useUserId();
+ const { stores, derived } = usePdfDocument().state;
+ const [pageHeights] = stores.pageHeight;
+ const [highlights] = stores.highlights;
+
+ return createMemo(() => {
+ if (!derived.viewerReady()) return [];
+
+ const out: PdfComment[] = [];
+ for (const [pageIndexStr, pageHighlights] of Object.entries(highlights)) {
+ if (!pageHighlights) continue;
+ const pageIndex = parseInt(pageIndexStr);
+ const height = pageHeights[pageIndex] ?? 0;
+
+ for (const highlight of Object.values(pageHighlights)) {
+ if (!highlight) continue;
+
+ const originalYPosition = getHighlightPos(highlight, height);
+ if (originalYPosition === null) continue;
+
+ const layout = {
+ pageIndex,
+ originalYPosition,
+ };
+
+ // new highlight thread
+ if (highlight.hasTempThread) {
+ const currentUserId = userId();
+ if (!currentUserId) {
+ console.error('User ID not found');
+ continue;
+ }
+ const rootComment: PdfRoot = {
+ id: -1,
+ rootId: -1,
+ type: 'highlight',
+ text: '',
+ owner: currentUserId,
+ author: currentUserId,
+ createdAt: new Date(),
+ isNew: true,
+ children: [],
+ threadId: -1,
+ anchorId: highlight.uuid,
+ };
+ out.push({ ...rootComment, layout });
continue;
}
- const rootComment: PdfRoot = {
- id: -1,
- rootId: -1,
- type: 'highlight',
- text: '',
- owner: userId,
- author: userId,
- createdAt: new Date(),
- isNew: true,
- children: [],
- threadId: -1,
- anchorId: highlight.uuid,
- };
- out.push({ ...rootComment, layout });
- continue;
- }
- const highlightThread = getHighlightThread(highlight);
- if (!highlightThread) continue;
+ const highlightThread = getHighlightThread(highlight);
+ if (!highlightThread) continue;
- const { root, replies } = highlightThread;
- out.push({ ...root, layout });
- replies.forEach((reply) => out.push(reply));
+ const { root, replies } = highlightThread;
+ out.push({ ...root, layout });
+ replies.forEach((reply) => out.push(reply));
+ }
}
- }
- return out;
-});
+ return out;
+ });
+};
const useGetHighlightIdFromCommentId = () => {
const getCommentById = useGetCommentById();
@@ -169,20 +156,21 @@ const useGetHighlightIdFromCommentId = () => {
export const useDeleteNewHighlightComment = () => {
const handleHighlightSelection = useHighlightSelection();
+ const { signals, stores, derived } = usePdfDocument().state;
const [convertedHighlightThreadId, setConvertedHighlightThreadId] =
- convertedHighlightThreadIdSignal;
- const setHighlightStore = highlightStore.set;
+ signals.convertedHighlightThreadId;
+ const [, setHighlights] = stores.highlights;
const getHighlightIdFromCommentId = useGetHighlightIdFromCommentId();
return () => {
const commentId = -1;
const highlightUuid = getHighlightIdFromCommentId(commentId);
if (!highlightUuid) return;
- const highlight = highlightsUuidMap()?.[highlightUuid];
+ const highlight = derived.highlightsUuidMap()?.[highlightUuid];
if (!highlight) return;
const pageIndex = highlight.pageNum;
- setHighlightStore(
+ setHighlights(
pageIndex,
produce((draft) => {
if (!draft) return;
@@ -215,34 +203,29 @@ export const useDeleteNewHighlightComment = () => {
};
export function useCreateHighlightCommentAtSelection() {
- const selectionStoreValue = selectionStore.get;
- const setHighlightStore = highlightStore.set;
- const setConvertedHighlightThreadId = convertedHighlightThreadIdSignal.set;
- const setGeneralPopupLocation = generalPopupLocationSignal.set;
- const addHighlights = useAddNewHighlightComments();
+ const { signals, stores } = usePdfDocument().state;
+ const [selection] = stores.selection;
+ const [, setHighlights] = stores.highlights;
const currentPageViewport = useCurrentPageViewport();
const deleteNewComments = useDeleteNewComments();
- const setActiveCommentThread = activeCommentThreadSignal.set;
- const setDisablePageViewClick = disablePageViewClickSignal.set;
return createCallback((_e: MouseEvent) => {
- setDisablePageViewClick(true);
+ signals.disablePageViewClick[1](true);
try {
deleteNewComments();
// TODO: make the general popup location reactive to the active highlight/term state instead of requiring a manual reset
- setGeneralPopupLocation(null);
+ signals.generalPopupLocation[1](null);
// create comment from existing highlight
- const highlightUnderSelection =
- selectionStoreValue.highlightsUnderSelection.at(0);
+ const highlightUnderSelection = selection.highlightsUnderSelection.at(0);
if (highlightUnderSelection) {
batch(() => {
- setConvertedHighlightThreadId(highlightUnderSelection.uuid);
- setActiveCommentThread(-1);
+ signals.convertedHighlightThreadId[1](highlightUnderSelection.uuid);
+ signals.activeCommentThread[1](-1);
// NOTE: the new comment is reactively determined in the highlight comments memo
- setHighlightStore(
+ setHighlights(
highlightUnderSelection.pageNum,
highlightUnderSelection.uuid,
(prev) => ({ ...prev, hasTempThread: true })
@@ -252,11 +235,11 @@ export function useCreateHighlightCommentAtSelection() {
return;
}
- const selection = selectionStoreValue.selection;
- if (!selection) return;
+ const selectedRange = selection.selection;
+ if (!selectedRange) return;
const selectionHighlights = getHighlightsFromSelection(
- selection,
+ selectedRange,
Highlight.defaultYellow,
HighlightType.HIGHLIGHT,
null,
@@ -275,10 +258,22 @@ export function useCreateHighlightCommentAtSelection() {
highlights.push({ ...highlight, hasTempThread: true });
}
- addHighlights(highlights);
- setActiveCommentThread(-1);
+ setHighlights(
+ produce((state) => {
+ for (const highlight of highlights) {
+ const pageNum = highlight.pageNum;
+ const uuid = highlight.uuid;
+ if (state[pageNum]) {
+ state[pageNum][uuid] = highlight;
+ } else {
+ state[pageNum] = { [uuid]: highlight };
+ }
+ }
+ })
+ );
+ signals.activeCommentThread[1](-1);
} finally {
- setDisablePageViewClick(false);
+ signals.disablePageViewClick[1](false);
}
});
}
diff --git a/apps/web/src/features/block-pdf/store/commentsResource.ts b/apps/web/src/features/block-pdf/store/commentsResource.ts
index 7ec47d40bd..24683ccdf5 100644
--- a/apps/web/src/features/block-pdf/store/commentsResource.ts
+++ b/apps/web/src/features/block-pdf/store/commentsResource.ts
@@ -1,15 +1,9 @@
import type { IHighlight } from '@block-pdf/model/Highlight';
import type { IThreadPlaceable } from '@block-pdf/type/placeables';
-import {
- createBlockMemo,
- createBlockResource,
- useBlockId,
- useBlockName,
-} from '@core/block';
import { useUserId } from '@core/context/user';
import { compareDateAsc } from '@core/util/date';
-import { createConnectionBlockWebsocketEffect } from '@service-connection/websocket';
+import { createConnectionWebsocketEffect } from '@service-connection/websocket';
import { storageServiceClient } from '@service-storage/client';
import type { AnnotationIncrementalUpdate } from '@service-storage/generated/schemas/annotationIncrementalUpdate';
import type { Comment } from '@service-storage/generated/schemas/comment';
@@ -29,13 +23,7 @@ import type { EditAnchorResponse } from '@service-storage/generated/schemas/edit
import type { EditCommentRequest } from '@service-storage/generated/schemas/editCommentRequest';
import type { EditCommentResponse } from '@service-storage/generated/schemas/editCommentResponse';
import { batch } from 'solid-js';
-
-const isPdfBlock = createBlockMemo(() => useBlockName() === 'pdf');
-export const commentThreadsResource = createBlockResource(
- isPdfBlock,
- fetchComments
-);
-export const anchorsResource = createBlockResource(isPdfBlock, fetchAnchors);
+import { usePdfDocument } from '../context/pdf-document-context';
export const sortComments = (a: Comment, b: Comment) => {
if (a.order != null && b.order != null) {
@@ -48,37 +36,22 @@ export const sortComments = (a: Comment, b: Comment) => {
return compareDateAsc(a.createdAt, b.createdAt);
};
-async function fetchComments() {
- const documentId = useBlockId();
- const commentThreads = await storageServiceClient.annotations.getComments({
- documentId,
- });
- return commentThreads.isOk() ? commentThreads.value.data : [];
-}
-
-async function fetchAnchors() {
- const documentId = useBlockId();
- const anchors = await storageServiceClient.annotations.getAnchors({
- documentId,
- });
- return anchors.isOk() ? anchors.value.data : [];
-}
-
function useHandleCreateUnthreadedAnchor() {
- const [, { mutate: mutateAnchors }] = anchorsResource;
+ const [, { mutate: mutateAnchors }] =
+ usePdfDocument().state.resources.anchors;
return async (response: CreateUnthreadedAnchorResponse) => {
- mutateAnchors((prev) => [...prev, response]);
+ mutateAnchors((prev) => [...(prev ?? []), response]);
};
}
function useCreateUnthreadedAnchor() {
- const documentId = useBlockId();
+ const { documentId } = usePdfDocument();
const handleCreateUnthreadedAnchor = useHandleCreateUnthreadedAnchor();
return async (body: CreateUnthreadedAnchorRequest) => {
const result = await storageServiceClient.annotations.createAnchor({
- documentId,
+ documentId: documentId(),
body,
});
@@ -96,14 +69,17 @@ function useCreateUnthreadedAnchor() {
}
function useHandleDeleteUnthreadedAnchor() {
- const [, { mutate: mutateAnchors }] = anchorsResource;
- const [, { mutate: mutateCommentThreads }] = commentThreadsResource;
+ const { anchors, commentThreads } = usePdfDocument().state.resources;
+ const [, { mutate: mutateAnchors }] = anchors;
+ const [, { mutate: mutateCommentThreads }] = commentThreads;
return async (response: DeleteUnthreadedAnchorResponse) => {
- mutateAnchors((prev) => prev.filter((a) => a.uuid !== response.uuid));
+ mutateAnchors((prev) =>
+ (prev ?? []).filter((a) => a.uuid !== response.uuid)
+ );
if (response.threadId != null) {
mutateCommentThreads((prev) =>
- prev.filter((t) => t.thread.threadId !== response.threadId)
+ (prev ?? []).filter((t) => t.thread.threadId !== response.threadId)
);
}
};
@@ -131,11 +107,12 @@ function useDeleteUnthreadedAnchor() {
}
function useHandleEditAnchor() {
- const [, { mutate: mutateAnchors }] = anchorsResource;
+ const [, { mutate: mutateAnchors }] =
+ usePdfDocument().state.resources.anchors;
return async (response: EditAnchorResponse) => {
mutateAnchors((prev) => [
- ...prev.filter((a) => a.uuid !== response.uuid),
+ ...(prev ?? []).filter((a) => a.uuid !== response.uuid),
response,
]);
};
@@ -163,8 +140,9 @@ function useEditAnchor() {
}
function useHandleCreateComment() {
- const [, { mutate: mutateCommentThreads }] = commentThreadsResource;
- const [, { mutate: mutateAnchors }] = anchorsResource;
+ const { anchors, commentThreads } = usePdfDocument().state.resources;
+ const [, { mutate: mutateCommentThreads }] = commentThreads;
+ const [, { mutate: mutateAnchors }] = anchors;
return async (response: CreateCommentResponse) => {
const commentThread: CommentThread = {
@@ -174,13 +152,13 @@ function useHandleCreateComment() {
const retAnchor = response.anchor;
batch(() => {
if (retAnchor) {
- mutateAnchors((prev) => [...prev, retAnchor]);
+ mutateAnchors((prev) => [...(prev ?? []), retAnchor]);
}
let mutatedExistingThread = false;
mutateCommentThreads((prev) => {
let out: CommentThread[] = [];
- for (const thread of prev) {
+ for (const thread of prev ?? []) {
if (thread.thread.threadId === commentThread.thread.threadId) {
mutatedExistingThread = true;
out.push(commentThread);
@@ -198,7 +176,7 @@ function useHandleCreateComment() {
}
function useCreateComment() {
- const documentId = useBlockId();
+ const { documentId } = usePdfDocument();
const handleCreateComment = useHandleCreateComment();
return async (body: CreateCommentRequest) => {
@@ -208,7 +186,7 @@ function useCreateComment() {
}
const result = await storageServiceClient.annotations.createComment({
- documentId,
+ documentId: documentId(),
body,
});
@@ -226,12 +204,13 @@ function useCreateComment() {
}
function useHandleEditComment() {
- const [, { mutate: mutateCommentThreads }] = commentThreadsResource;
+ const [, { mutate: mutateCommentThreads }] =
+ usePdfDocument().state.resources.commentThreads;
return async (response: EditCommentResponse) => {
mutateCommentThreads((prev) => {
let out: CommentThread[] = [];
- for (const thread of prev) {
+ for (const thread of prev ?? []) {
if (thread.thread.threadId === response.threadId) {
const commentThread = {
thread: thread.thread,
@@ -276,20 +255,23 @@ export function useEditCommentResource() {
}
function useHandleDeleteComment() {
- const [, { mutate: mutateCommentThreads }] = commentThreadsResource;
- const [, { mutate: mutateAnchors }] = anchorsResource;
+ const { anchors, commentThreads } = usePdfDocument().state.resources;
+ const [, { mutate: mutateCommentThreads }] = commentThreads;
+ const [, { mutate: mutateAnchors }] = anchors;
return async (response: DeleteCommentResponse) => {
batch(() => {
// either delete single comment or entire thread
if (response.thread.deleted) {
mutateCommentThreads((prev) =>
- prev.filter((t) => t.thread.threadId !== response.thread.threadId)
+ (prev ?? []).filter(
+ (t) => t.thread.threadId !== response.thread.threadId
+ )
);
} else {
mutateCommentThreads((prev) => {
let out: CommentThread[] = [];
- for (const commentThread of prev) {
+ for (const commentThread of prev ?? []) {
if (commentThread.thread.threadId === response.thread.threadId) {
const comments = commentThread.comments.filter(
(c) => c.commentId !== response.commentId
@@ -308,7 +290,7 @@ function useHandleDeleteComment() {
if (deletedAnchor.deleted) {
mutateAnchors((prev) =>
- prev.filter((a) => a.uuid !== deletedAnchor.uuid)
+ (prev ?? []).filter((a) => a.uuid !== deletedAnchor.uuid)
);
}
});
@@ -531,11 +513,9 @@ export function useEditPdfFreeCommentAnchor() {
};
}
-createConnectionBlockWebsocketEffect((msg) => {
+export function usePdfCommentRealtimeBehavior() {
const currentUserId = useUserId();
- const currentDocumentId = useBlockId();
- const blockName = useBlockName();
-
+ const { documentId } = usePdfDocument();
const handleCommentUpdate = useHandleCreateComment();
const handleCreateUnthreadedAnchor = useHandleCreateUnthreadedAnchor();
const handleEditComment = useHandleEditComment();
@@ -543,45 +523,45 @@ createConnectionBlockWebsocketEffect((msg) => {
const handleDeleteComment = useHandleDeleteComment();
const handleDeleteUnthreadedAnchor = useHandleDeleteUnthreadedAnchor();
- if (blockName !== 'pdf') return;
-
- if (msg.type === 'comment') {
- let incrementalUpdate: AnnotationIncrementalUpdate;
- try {
- incrementalUpdate = JSON.parse(msg.data) as AnnotationIncrementalUpdate;
- if (
- incrementalUpdate.payload.documentId !== currentDocumentId ||
- incrementalUpdate.payload.sender === currentUserId()
- ) {
+ createConnectionWebsocketEffect((msg) => {
+ if (msg.type === 'comment') {
+ let incrementalUpdate: AnnotationIncrementalUpdate;
+ try {
+ incrementalUpdate = JSON.parse(msg.data) as AnnotationIncrementalUpdate;
+ if (
+ incrementalUpdate.payload.documentId !== documentId() ||
+ incrementalUpdate.payload.sender === currentUserId()
+ ) {
+ return;
+ }
+ } catch (e) {
+ console.warn('unable to parse annotation incremental update', e);
return;
}
- } catch (e) {
- console.warn('unable to parse annotation incremental update', e);
- return;
- }
- switch (incrementalUpdate.updateType) {
- case 'create-comment':
- handleCommentUpdate(incrementalUpdate.payload.response);
- break;
- case 'create-anchor':
- handleCreateUnthreadedAnchor(incrementalUpdate.payload.response);
- break;
- case 'edit-comment':
- handleEditComment(incrementalUpdate.payload.response);
- break;
- case 'edit-anchor':
- handleEditAnchor(incrementalUpdate.payload.response);
- break;
- case 'delete-comment':
- handleDeleteComment(incrementalUpdate.payload.response);
- break;
- case 'delete-anchor':
- handleDeleteUnthreadedAnchor(incrementalUpdate.payload.response);
- break;
- default:
- console.error('unknown comment update type', msg);
- break;
+ switch (incrementalUpdate.updateType) {
+ case 'create-comment':
+ handleCommentUpdate(incrementalUpdate.payload.response);
+ break;
+ case 'create-anchor':
+ handleCreateUnthreadedAnchor(incrementalUpdate.payload.response);
+ break;
+ case 'edit-comment':
+ handleEditComment(incrementalUpdate.payload.response);
+ break;
+ case 'edit-anchor':
+ handleEditAnchor(incrementalUpdate.payload.response);
+ break;
+ case 'delete-comment':
+ handleDeleteComment(incrementalUpdate.payload.response);
+ break;
+ case 'delete-anchor':
+ handleDeleteUnthreadedAnchor(incrementalUpdate.payload.response);
+ break;
+ default:
+ console.error('unknown comment update type', msg);
+ break;
+ }
}
- }
-});
+ });
+}
diff --git a/apps/web/src/features/block-pdf/store/definitionPopup.ts b/apps/web/src/features/block-pdf/store/definitionPopup.ts
index ff4c7271f9..e1bf54b4fc 100644
--- a/apps/web/src/features/block-pdf/store/definitionPopup.ts
+++ b/apps/web/src/features/block-pdf/store/definitionPopup.ts
@@ -1,10 +1,10 @@
-import { createBlockStore } from '@core/block';
import { produce } from 'solid-js/store';
import {
decodeString,
// LINE_HEIGHT,
MAX_LINES,
} from '../component/DefinitionLookup/shared';
+import { usePdfDocument } from '../context/pdf-document-context';
import type Term from '../model/Term';
import { InvalidActionError } from '../util/errors';
import { estimateTextWidth } from '../util/estimateTextWidth';
@@ -88,7 +88,7 @@ function updateTermIDToSizingMap(draft: Partial<ISectionPopupContext>): void {
// TODO terms that are actually the same definition have different IDs
// As a result, you can open several of the same definition
-interface ISectionPopupContext {
+export interface ISectionPopupContext {
terms: Term[];
termIDs: Array<string>;
termIDToSizingMap: Partial<
@@ -105,15 +105,6 @@ interface ISectionPopupContext {
element: Element | null;
}
-const defaultState: ISectionPopupContext = {
- terms: [],
- termIDs: [],
- termIDToSizingMap: {},
-
- pageWidth: null,
- element: null,
-};
-
type SetRectsAction = {
type: 'SET_RECTS';
pageWidth: number;
@@ -234,19 +225,18 @@ const handler = (
}
};
-const rootDefinitionStore = createBlockStore({ ...defaultState });
-const popupDefinitionStore = createBlockStore({ ...defaultState });
-
export function usePopupContextUpdate(isPopup: boolean) {
- const setStore = isPopup ? popupDefinitionStore.set : rootDefinitionStore.set;
+ const { rootDefinition, popupDefinition } = usePdfDocument().state.stores;
+ const setStore = isPopup ? popupDefinition[1] : rootDefinition[1];
return (action: ISectionPopupAction) => {
- setStore(produce((state) => handler(state, action)));
+ setStore(produce<ISectionPopupContext>((state) => handler(state, action)));
};
}
export function usePopupStore(isPopup: boolean) {
- const store = isPopup ? popupDefinitionStore.get : rootDefinitionStore.get;
+ const { rootDefinition, popupDefinition } = usePdfDocument().state.stores;
+ const store = isPopup ? popupDefinition[0] : rootDefinition[0];
return {
terms: () => store.terms,
diff --git a/apps/web/src/features/block-pdf/store/highlight.ts b/apps/web/src/features/block-pdf/store/highlight.ts
index 4b4665f133..adb37cf4bd 100644
--- a/apps/web/src/features/block-pdf/store/highlight.ts
+++ b/apps/web/src/features/block-pdf/store/highlight.ts
@@ -1,17 +1,10 @@
-import { generalPopupLocationSignal } from '@block-pdf/signal/location';
import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';
-import {
- createBlockEffect,
- createBlockMemo,
- createBlockStore,
-} from '@core/block';
import { createCallback } from '@solid-primitives/rootless';
-import { batch } from 'solid-js';
+import { batch, createEffect } from 'solid-js';
import { produce, reconcile } from 'solid-js/store';
+import { usePdfDocument } from '../context/pdf-document-context';
import { Highlight, type IHighlight } from '../model/Highlight';
import {
- anchorsResource,
- commentThreadsResource,
useCreateUnthreadedHighlightResource,
useDeleteUnthreadedHighlightResource,
} from './commentsResource';
@@ -22,121 +15,88 @@ export type HighlightUuidMap = Partial<Record<string, IHighlight>>;
export type HighlightPageMap = Partial<Record<number, HighlightUuidMap>>;
/**
- * Map of highlight page index to highlights on that page.
- * Highlights are stored as an object mapping UUID to highlight object. See {@link Highlight}.
- * NOTE: page number is 0-indexed, and is converted to a string as a Record is a JS object under the hood
+ * Keeps the document-scoped highlight store synchronized with annotation
+ * resources. Invoke once inside the PDF document provider.
*/
-export const highlightStore = createBlockStore<HighlightPageMap>({});
-
-createBlockEffect(() => {
- const clearHighlightStore = useClearHighlightStore();
- clearHighlightStore();
+export function useSyncHighlightStore() {
+ const pdf = usePdfDocument();
+ const [, setHighlightStore] = pdf.state.stores.highlights;
+ const [anchorsData] = pdf.state.resources.anchors;
+ const [commentThreadsData] = pdf.state.resources.commentThreads;
- const [anchorsData] = anchorsResource;
- const anchors = anchorsData();
- if (!anchors || anchors.length === 0) return;
-
- const [commentThreadsData] = commentThreadsResource;
- const commentThreads = commentThreadsData() ?? [];
+ createEffect(() => {
+ setHighlightStore(reconcile({}));
- const highlightAnchors = anchors.filter((a) => a.anchorType === 'highlight');
+ const anchors = anchorsData();
+ if (!anchors || anchors.length === 0) return;
- const mappedAnchors = highlightAnchors.flatMap((a) => {
- const commentThread = commentThreads.find(
- (ct) => ct.thread.threadId === a.threadId
+ const commentThreads = commentThreadsData() ?? [];
+ const highlightAnchors = anchors.filter(
+ (anchor) => anchor.anchorType === 'highlight'
);
- // this is an error but probably resolves eventually as the data is fetched asynchronously
- if (!commentThread && a.threadId) {
- return [];
- }
-
- // TODO: deprecate unneeded fields
- const highlight: IHighlight = {
- owner: a.owner,
- existsOnServer: true,
- pageNum: a.page,
- rects: a.highlightRects,
- color: {
- red: a.red,
- green: a.green,
- blue: a.blue,
- alpha: a.alpha,
- },
- hasTempThread: false,
- uuid: a.uuid,
- text: a.text,
- type: a.highlightType,
- pageViewport: {
- width: a.pageViewportWidth,
- height: a.pageViewportHeight,
- },
- thread: commentThread
- ? {
- threadId: commentThread.thread.threadId,
- rootId: commentThread.comments[0].commentId,
- anchorId: a.uuid,
- page: a.page,
- comments: commentThread.comments,
- isResolved: commentThread.thread.resolved,
- }
- : null,
- };
- return highlight;
- });
+ const mappedAnchors = highlightAnchors.flatMap((anchor) => {
+ const commentThread = commentThreads.find(
+ (thread) => thread.thread.threadId === anchor.threadId
+ );
+ // This is an error but may resolve once both resources have loaded.
+ if (!commentThread && anchor.threadId) return [];
+
+ // TODO: deprecate unneeded fields
+ const highlight: IHighlight = {
+ owner: anchor.owner,
+ existsOnServer: true,
+ pageNum: anchor.page,
+ rects: anchor.highlightRects,
+ color: {
+ red: anchor.red,
+ green: anchor.green,
+ blue: anchor.blue,
+ alpha: anchor.alpha,
+ },
+ hasTempThread: false,
+ uuid: anchor.uuid,
+ text: anchor.text,
+ type: anchor.highlightType,
+ pageViewport: {
+ width: anchor.pageViewportWidth,
+ height: anchor.pageViewportHeight,
+ },
+ thread: commentThread
+ ? {
+ threadId: commentThread.thread.threadId,
+ rootId: commentThread.comments[0].commentId,
+ anchorId: anchor.uuid,
+ page: anchor.page,
+ comments: commentThread.comments,
+ isResolved: commentThread.thread.resolved,
+ }
+ : null,
+ };
+
+ return highlight;
+ });
- batch(() => {
- for (const highlight of mappedAnchors) {
- highlightStore.set(highlight.pageNum, (prev) => ({
- ...prev,
- [highlight.uuid]: highlight,
- }));
- }
+ batch(() => {
+ for (const highlight of mappedAnchors) {
+ setHighlightStore(highlight.pageNum, (previous) => ({
+ ...previous,
+ [highlight.uuid]: highlight,
+ }));
+ }
+ });
});
-});
-
-export const highlights = createBlockMemo(() => {
- const out: IHighlight[] = [];
- for (const pageHighlights of Object.values(highlightStore.get ?? {})) {
- if (!pageHighlights) continue;
- for (const highlight of Object.values(pageHighlights)) {
- if (!highlight) continue;
- out.push(highlight);
- }
- }
- return out;
-});
-
-export const highlightsUuidMap = createBlockMemo(() => {
- const out: HighlightUuidMap = {};
- for (const pageHighlights of Object.values(highlightStore.get ?? {})) {
- if (!pageHighlights) continue;
- for (const [highlightUuid, highlight] of Object.entries(pageHighlights)) {
- out[highlightUuid] = highlight;
- }
- }
- return out;
-});
-
-export const selectionStore = createBlockStore<{
- highlightsUnderSelection: IHighlight[];
- selection: Selection | null;
- selectionString: string;
-}>({
- highlightsUnderSelection: [],
- selection: null,
- selectionString: '',
-});
+}
export const useClearHighlightStore = () => {
- const setHighlightStore = highlightStore.set;
+ const [, setHighlightStore] = usePdfDocument().state.stores.highlights;
return () => {
setHighlightStore(reconcile({}));
};
};
export const useClearSelectionHighlights = () => {
- const setSelectionStore = selectionStore.set;
+ const [, setSelectionStore] = usePdfDocument().state.stores.selection;
return () => {
setSelectionStore(
reconcile({
@@ -149,8 +109,9 @@ export const useClearSelectionHighlights = () => {
};
export const useSetSelectionHighlights = () => {
- const setSelectionStore = selectionStore.set;
- const highlightStoreValue = highlightStore.get;
+ const { highlights, selection } = usePdfDocument().state.stores;
+ const [highlightStore] = highlights;
+ const [, setSelectionStore] = selection;
return (selection: Selection) => {
if (selection.isCollapsed) return;
@@ -167,7 +128,7 @@ export const useSetSelectionHighlights = () => {
pageIndex,
selectionHighlight,
] of selectionHighlights.entries()) {
- const existingHighlights = highlightStoreValue[pageIndex];
+ const existingHighlights = highlightStore[pageIndex];
if (!existingHighlights) continue;
const overlappingHighlights = Object.values(existingHighlights).filter(
@@ -190,7 +151,7 @@ export const useSetSelectionHighlights = () => {
};
export const useAddNewHighlightComments = () => {
- const setHighlightStore = highlightStore.set;
+ const [, setHighlightStore] = usePdfDocument().state.stores.highlights;
return (highlights: IHighlight[]) =>
setHighlightStore(
produce((state) => {
@@ -222,7 +183,8 @@ export const useAddNewHighlights = () => {
export function useRemoveHighlight() {
const deleteHighlight = useDeleteUnthreadedHighlightResource();
- const setGeneralPopupLocation = generalPopupLocationSignal.set;
+ const [, setGeneralPopupLocation] =
+ usePdfDocument().state.signals.generalPopupLocation;
return (uuid: string) => {
setGeneralPopupLocation(null);
@@ -231,13 +193,16 @@ export function useRemoveHighlight() {
}
export const useGetHighlightByUuid = () => {
+ const highlightsUuidMap = usePdfDocument().state.derived.highlightsUuidMap;
return createCallback((uuid: string) => {
return highlightsUuidMap()?.[uuid];
});
};
-export const hasHighlights = createBlockMemo(() => {
- return Object.values(highlightStore.get ?? {}).some(
- (page) => Object.values(page ?? {}).length > 0
- );
-});
+export const useHasHighlights = () => {
+ const [highlightStore] = usePdfDocument().state.stores.highlights;
+ return () =>
+ Object.values(highlightStore).some(
+ (page) => Object.values(page ?? {}).length > 0
+ );
+};
diff --git a/apps/web/src/features/block-pdf/store/placeables.ts b/apps/web/src/features/block-pdf/store/placeables.ts
index 10447ac4d3..2d9470e607 100644
--- a/apps/web/src/features/block-pdf/store/placeables.ts
+++ b/apps/web/src/features/block-pdf/store/placeables.ts
@@ -1,16 +1,6 @@
import { DEFAULT_COLOR, type IColor } from '@block-pdf/model/Color';
import { PageModel } from '@block-pdf/model/Page';
-import { pdfModificationDataStore } from '@block-pdf/signal/document';
-import {
- useCurrentScale,
- useGetPopupContextViewer,
-} from '@block-pdf/signal/pdfViewer';
-import {
- activePlaceableIdSignal,
- newPlaceableSignal,
- placeableModeSignal,
-} from '@block-pdf/signal/placeables';
-import { useDoEdit } from '@block-pdf/signal/save';
+import { useIsPopup } from '@block-pdf/signal/pdfViewer';
import {
useDeleteComment,
useDeleteNewComments,
@@ -33,18 +23,16 @@ import {
// import { reformatPdfjsDate } from '@block-pdf/util/DateUtils';
import { normalizeRect } from '@block-pdf/util/pdfjsUtils';
import { PDF_TO_CSS_UNITS } from '@block-pdf/util/pixelsPerInch';
-import {
- createBlockEffect,
- createBlockMemo,
- createBlockSignal,
-} from '@core/block';
import { useUserId } from '@core/context/user';
import { createCallback } from '@solid-primitives/rootless';
import type { PageViewport } from 'pdfjs-dist';
-import { batch } from 'solid-js';
+import { batch, createEffect, createMemo } from 'solid-js';
import { v7 as uuid7 } from 'uuid';
-import { activeCommentThreadSignal } from './comments/commentStore';
-import { commentPlaceables, isThreadPlaceable } from './comments/freeComments';
+import { usePdfDocument } from '../context/pdf-document-context';
+import {
+ isThreadPlaceable,
+ useCommentPlaceables,
+} from './comments/freeComments';
import { useEditPdfFreeCommentAnchor } from './commentsResource';
interface AppearancePayload {
@@ -63,15 +51,37 @@ const DEFAULT_APPEARANCE_PAYLOAD: AppearancePayload = {
size: 12,
};
-export const placeableIdMap = createBlockMemo(() => {
- const placeables = pdfModificationDataStore.get.placeables.concat(
- commentPlaceables() ?? []
- );
- return Object.fromEntries(placeables.map((p) => [p.internalId, p])) as Record<
- string,
- IPlaceable
- >;
-});
+export function usePlaceableIdMap() {
+ const [modificationData] = usePdfDocument().state.stores.modificationData;
+ const commentPlaceables = useCommentPlaceables();
+
+ return createMemo(() => {
+ const placeables = modificationData.placeables.concat(commentPlaceables());
+ return Object.fromEntries(
+ placeables.map((placeable) => [placeable.internalId, placeable])
+ ) as Record<string, IPlaceable>;
+ });
+}
+
+function useCurrentScale() {
+ const isPopup = useIsPopup();
+ const { currentScale, popupCurrentScale } = usePdfDocument().state.derived;
+
+ return () => (isPopup ? popupCurrentScale() : currentScale()) ?? 1;
+}
+
+function useGetPopupContextViewer() {
+ const isPopup = useIsPopup();
+ const { rootViewer, popupViewer } = usePdfDocument().state.signals;
+
+ return () => (isPopup ? popupViewer[0]() : rootViewer[0]());
+}
+
+function useDoEdit() {
+ const [, setNumOperations] = usePdfDocument().state.signals.numOperations;
+
+ return () => setNumOperations((previous) => previous + 1);
+}
// function convertTextAnnotationToThread(
// annotation: Annotation,
@@ -173,9 +183,8 @@ function parseDefaultAppearance(appearance: string): AppearancePayload {
};
}
-// helper function to convert internal id (uuid) to array index
-function internalIdToIndex(id: string) {
- const placeables = pdfModificationDataStore.get.placeables;
+// Helper function to convert internal id (uuid) to array index.
+function internalIdToIndex(placeables: IPlaceable[], id: string) {
return placeables.findIndex((p) => p.internalId === id);
}
@@ -556,11 +565,6 @@ function useMakeSignature() {
};
}
-const fontOptions = ['Times New Roman', 'Courier', 'Helvetica'] as const;
-export const fontPreferenceSignal = createBlockSignal<
- (typeof fontOptions)[number]
->(fontOptions[0]);
-
const textAnnotationProperties = {
widthInPixels: 175,
heightInPixels: 17,
@@ -569,7 +573,7 @@ const textAnnotationProperties = {
function useMakeTextAnnotation() {
const getViewer = useGetPopupContextViewer();
- const fontPreference = fontPreferenceSignal.get;
+ const [fontPreference] = usePdfDocument().state.signals.fontPreference;
const currentScale = useCurrentScale();
return (
@@ -656,45 +660,54 @@ function useMakeTextAnnotation() {
/**
* Sets active placeable when a *click outside* event occurs that sets an active comment
* Specifically in the comment MeasureContainer area
+ *
+ * Invoke once inside the PDF document provider.
*/
-createBlockEffect(() => {
- const setActivePlaceableId = activePlaceableIdSignal.set;
- const activeThreadId = activeCommentThreadSignal.get();
-
- const activePlaceableId = activePlaceableIdSignal();
+export function useSyncActivePlaceableWithCommentThread() {
+ const placeableIdMap = usePlaceableIdMap();
+ const {
+ activePlaceableId: [activePlaceableId, setActivePlaceableId],
+ activeCommentThread: [activeCommentThread],
+ } = usePdfDocument().state.signals;
+
+ createEffect(() => {
+ const activeThreadId = activeCommentThread();
+ const activePlaceableIdValue = activePlaceableId();
+ const activePlaceable = activePlaceableIdValue
+ ? placeableIdMap()[activePlaceableIdValue]
+ : null;
- const activePlaceable = activePlaceableId
- ? placeableIdMap()?.[activePlaceableId]
- : null;
-
- if (
- activeThreadId == null &&
- activePlaceable &&
- isThreadPlaceable(activePlaceable)
- ) {
- setActivePlaceableId(undefined);
- }
- if (activeThreadId == null) return;
+ if (
+ activeThreadId == null &&
+ activePlaceable &&
+ isThreadPlaceable(activePlaceable)
+ ) {
+ setActivePlaceableId(undefined);
+ }
+ if (activeThreadId == null) return;
- const matchingFreeCommentPlaceable = commentPlaceables()?.find(
- (p) => p.payload?.threadId === activeThreadId
- );
+ const matchingFreeCommentPlaceable = Object.values(placeableIdMap()).find(
+ (placeable) =>
+ isThreadPlaceable(placeable) &&
+ placeable.payload?.threadId === activeThreadId
+ );
- if (matchingFreeCommentPlaceable) {
- setActivePlaceableId(matchingFreeCommentPlaceable.internalId);
- }
-});
+ if (matchingFreeCommentPlaceable) {
+ setActivePlaceableId(matchingFreeCommentPlaceable.internalId);
+ }
+ });
+}
export function useCreatePlaceable() {
const makeThread = useMakeThread();
const makeTextAnnotation = useMakeTextAnnotation();
const makeSignature = useMakeSignature();
- const [mode, setMode] = placeableModeSignal;
- const [_pdfModificationDataValue, setPdfModificationData] =
- pdfModificationDataStore;
- const setActivePlaceableId = activePlaceableIdSignal.set;
- const setNewPlaceable = newPlaceableSignal.set;
- const setActiveCommentThread = activeCommentThreadSignal.set;
+ const pdf = usePdfDocument();
+ const [mode, setMode] = pdf.state.signals.placeableMode;
+ const [, setPdfModificationData] = pdf.state.stores.modificationData;
+ const [, setActivePlaceableId] = pdf.state.signals.activePlaceableId;
+ const [, setNewPlaceable] = pdf.state.signals.newPlaceable;
+ const [, setActiveCommentThread] = pdf.state.signals.activeCommentThread;
return async (e: MouseEvent) => {
let placeable: IPlaceable | null;
@@ -737,21 +750,21 @@ export function useCreatePlaceable() {
}
export function useModifyPlaceable() {
- const [pdfModificationDataValue, setPdfModificationData] =
- pdfModificationDataStore;
+ const [modificationData, setModificationData] =
+ usePdfDocument().state.stores.modificationData;
const doEdit = useDoEdit();
return (index: number, newPlaceable: IPlaceable) => {
if (index < 0) return false;
- const placeables = pdfModificationDataValue.placeables;
+ const placeables = modificationData.placeables;
const currPlaceable = placeables.at(index);
if (!currPlaceable) return false;
if (newPlaceable.payloadType !== currPlaceable.payloadType) return false;
- setPdfModificationData('placeables', index, {
+ setModificationData('placeables', index, {
...newPlaceable,
wasEdited: true,
});
@@ -764,6 +777,7 @@ export function useModifyPlaceable() {
export function useModifyPayload() {
const modifyPlaceable = useModifyPlaceable();
+ const [modificationData] = usePdfDocument().state.stores.modificationData;
return <T extends PayloadType>(
id: string,
@@ -772,10 +786,10 @@ export function useModifyPayload() {
Extract<IPlaceablePayload, { payloadType: T }>['payload']
>
) => {
- const index = internalIdToIndex(id);
+ const index = internalIdToIndex(modificationData.placeables, id);
if (index < 0) return false;
- const existingPlaceable = pdfModificationDataStore.get.placeables.at(index);
+ const existingPlaceable = modificationData.placeables.at(index);
if (!existingPlaceable) return false;
if (payloadType !== existingPlaceable.payloadType) return false;
@@ -792,17 +806,18 @@ export function useModifyPayload() {
}
export function useDeletePlaceable() {
- const [pdfModificationDataValue, setPdfModificationData] =
- pdfModificationDataStore;
- const setActivePlaceable = activePlaceableIdSignal.set;
+ const pdf = usePdfDocument();
+ const [modificationData, setModificationData] =
+ pdf.state.stores.modificationData;
+ const [, setActivePlaceable] = pdf.state.signals.activePlaceableId;
+ const placeableIdMap = usePlaceableIdMap();
const doEdit = useDoEdit();
const deleteComment = useDeleteComment();
const arrayDelete = (index: number) => {
- if (index < 0 || index >= pdfModificationDataValue.placeables.length)
- return false;
+ if (index < 0 || index >= modificationData.placeables.length) return false;
- setPdfModificationData('placeables', (prev) => [
+ setModificationData('placeables', (prev) => [
...prev.slice(0, index),
...prev.slice(index + 1),
]);
@@ -813,7 +828,7 @@ export function useDeletePlaceable() {
};
return createCallback((uuid: string) => {
- const placeable = placeableIdMap()?.[uuid];
+ const placeable = placeableIdMap()[uuid];
if (!placeable) {
console.error('Placeable not found', uuid);
return;
@@ -829,7 +844,7 @@ export function useDeletePlaceable() {
return;
}
- const index = internalIdToIndex(uuid);
+ const index = internalIdToIndex(modificationData.placeables, uuid);
let deleted = arrayDelete(index);
if (deleted) {
@@ -842,7 +857,10 @@ export function useDeletePlaceable() {
export function useUpdatePlaceablePosition() {
const modifyPlaceable = useModifyPlaceable();
const editPdfFreeCommentAnchor = useEditPdfFreeCommentAnchor();
- const setNewPlaceable = newPlaceableSignal.set;
+ const pdf = usePdfDocument();
+ const [, setNewPlaceable] = pdf.state.signals.newPlaceable;
+ const [modificationData] = pdf.state.stores.modificationData;
+ const placeableIdMap = usePlaceableIdMap();
return createCallback(
(
@@ -861,7 +879,7 @@ export function useUpdatePlaceablePosition() {
pageNum?: number;
}
) => {
- const placeable = placeableIdMap()?.[uuid];
+ const placeable = placeableIdMap()[uuid];
if (!placeable) {
console.error('Placeable not found', uuid);
return;
@@ -942,7 +960,7 @@ export function useUpdatePlaceablePosition() {
}
}
- const index = internalIdToIndex(uuid);
+ const index = internalIdToIndex(modificationData.placeables, uuid);
return modifyPlaceable(index, newPlaceable);
}
);
diff --git a/apps/web/src/features/block-pdf/store/tableOfContents.ts b/apps/web/src/features/block-pdf/store/tableOfContents.ts
index f55bc54967..8eecb3698f 100644
--- a/apps/web/src/features/block-pdf/store/tableOfContents.ts
+++ b/apps/web/src/features/block-pdf/store/tableOfContents.ts
@@ -1,5 +1,5 @@
-import { createBlockStore } from '@core/block';
import { produce } from 'solid-js/store';
+import { usePdfDocument } from '../context/pdf-document-context';
import Section from '../model/Section';
import TocItem from '../model/TocItem';
import type { IBookmark } from '../type/Bookmark';
@@ -9,14 +9,20 @@ import { InvalidActionError } from '../util/errors';
import TocUtils from '../util/TocUtils';
import { XMLUtils } from '../util/XMLUtils';
+const DEFAULT_WIDTH_PX = 150;
+
+function getDefaultWidth(): number {
+ if (typeof window === 'undefined') return DEFAULT_WIDTH_PX;
+ return Math.max(DEFAULT_WIDTH_PX, Math.round(window.innerWidth * 0.15));
+}
+
// import {
// ITableOfContentsContext,
// TPageToSectionMap,
// getDefaultWidth,
// } from './DefaultTableOfContentsState';
-const DEFAULT_WIDTH_PX = 150;
export type TPageToSectionMap = Partial<{ [yPos: number]: Section }>[];
-interface ITableOfContentsContext {
+export interface ITableOfContentsContext {
// original copies of each TOC mode; allows for quickly swapping between the two
original: {
aiToc: TocItem[] | null;
@@ -45,34 +51,6 @@ interface ITableOfContentsContext {
// used for clicking on section references within the document
aiTocIdToSectionMap: Partial<{ [sectionId: number]: Section }>;
}
-function getDefaultWidth(): number {
- if (typeof window === 'undefined') return DEFAULT_WIDTH_PX;
- return Math.max(DEFAULT_WIDTH_PX, Math.round(window.innerWidth * 0.15));
-}
-const defaultState: ITableOfContentsContext = {
- original: {
- aiToc: null,
- pdfBookmarks: null,
- },
- currentMode: 'bookmarks',
- width: getDefaultWidth(),
-
- isLoaded: false,
- sectionToDeleteID: null,
- renameFormValue: '',
- sectionToRenameID: null,
- items: [],
- pageToSectionMap: [],
- unsavedBookmarks: false,
- coparse: null,
-
- idToSectionMap: {},
- idToPathMap: {},
- idToNearestTitleMap: {},
- openItems: {},
- aiTocIdToSectionMap: {},
-};
-
/* -------------------------------------------------------------------------- *
* Types
* -------------------------------------------------------------------------- */
@@ -1330,24 +1308,22 @@ export function findSectionByUuid(
return foundSection;
}
-const tableOfContentStore =
- createBlockStore<ITableOfContentsContext>(defaultState);
-
export function useTableOfContentsValue() {
- const tocStore = tableOfContentStore.get;
+ const [tocStore] = usePdfDocument().state.stores.tableOfContents;
return () => tocStore;
}
export function useTableOfContentsUpdate() {
- const setTocStore = tableOfContentStore.set;
+ const [, setTocStore] = usePdfDocument().state.stores.tableOfContents;
return (action: ITableOfContentsAction) => {
- // @ts-ignore
- setTocStore(produce((state) => producer(state, action)));
+ setTocStore(
+ produce<ITableOfContentsContext>((state) => producer(state, action))
+ );
};
}
export function useGetIdToSectionMap() {
- const tocStore = tableOfContentStore.get;
+ const [tocStore] = usePdfDocument().state.stores.tableOfContents;
return () =>
tocStore.currentMode === 'bookmarks'
? tocStore.aiTocIdToSectionMap
@@ -1355,6 +1331,6 @@ export function useGetIdToSectionMap() {
}
export function useGetPageToSectionMap() {
- const tocStore = tableOfContentStore.get;
+ const [tocStore] = usePdfDocument().state.stores.tableOfContents;
return () => tocStore.pageToSectionMap;
}
diff --git a/apps/web/src/features/block-pdf/util/selectionUtils.ts b/apps/web/src/features/block-pdf/util/selectionUtils.ts
index 16bfcc158b..69772d4a6c 100644
--- a/apps/web/src/features/block-pdf/util/selectionUtils.ts
+++ b/apps/web/src/features/block-pdf/util/selectionUtils.ts
@@ -1,6 +1,4 @@
-import { activeHighlightSignal } from '../component/UserHighlight';
-import { generalPopupLocationSignal } from '../signal/location';
-import { useClearSelectionHighlights } from '../store/highlight';
+import { usePdfDocument } from '../context/pdf-document-context';
/**
* Check if a user selection spans multiple pages of the pdf document.
@@ -65,13 +63,19 @@ function nodeToString(node: Node): string {
}
export function useResetSelection() {
- const clearSelectionHighlights = useClearSelectionHighlights();
- const setActiveHighlight = activeHighlightSignal.set;
- const setGeneralPopupLocation = generalPopupLocationSignal.set;
+ const { signals, stores } = usePdfDocument().state;
+ const setActiveHighlight = signals.activeHighlight[1];
+ const setGeneralPopupLocation = signals.generalPopupLocation[1];
+ const setSelection = stores.selection[1];
+
return (selection?: Selection) => {
selection?.removeAllRanges();
setGeneralPopupLocation(null);
- clearSelectionHighlights();
+ setSelection({
+ highlightsUnderSelection: [],
+ selection: null,
+ selectionString: '',
+ });
setActiveHighlight(null);
};
}