Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
refactor(pdf): replace monolithic context state (#6568)
dev-rb1d0fd8ae476f
diff --git a/apps/web/src/features/block-pdf/PdfViewer/TermDataStore.ts b/apps/web/src/features/block-pdf/PdfViewer/TermDataStore.tsdeleted file mode 100644index 75bd411133..0000000000--- a/apps/web/src/features/block-pdf/PdfViewer/TermDataStore.ts+++ /dev/null@@ -1,147 +0,0 @@-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 PDF document context- */-export const keyedTermDataStore = () => usePdfDocument().state.termDataStore;--export class TermDataStore {- terms: Term[] = [];- idToTerm: Map<string, Term> = new Map();- allTerms: Term[] = [];- #isLoaded: boolean = false;-- constructor() {- this.terms = [];- this.idToTerm = new Map();- this.allTerms = [];- this.#isLoaded = false;- }-- getTerms(): Term[] {- return Array.from(this.idToTerm.values()).map((term) => term.clone());- }-- get(id: string): Term | null {- const term = this.idToTerm.get(id);- if (term) {- return term.clone();- }-- return null;- }-- searchTerms(query: string, terms: Term[]): Term[] {- /**- * 1. Filter sections that do not contain the query in the full descriptor- * NOTE: Query must be found at the start of a token in the descriptor- * The only prefixes that are allowed are 'in', 'un', and 're'- *- * 2. Filter out sections with the exact same full title. Keep the first one- * that appears in the document.- * - the effect is the removal of subsections with the same full title- * - the first one that appears in the document will be the parent section- *- * 3. Sort by the following criteria:- * 1) The search query is an exact match on the first token- * 2) The search query is a prefix match on the first token- * 3) The search query is an exact match somewhere- * 4) The number of times the section is referenced in the document- */- const escapedQuery = cleanQuery(query);- const includeRE = new RegExp(`(^| | in| un| re| co|-)${escapedQuery}`);- let sort1RE = new RegExp(`^${escapedQuery}( |$)`); // Starting exact match- let sort2RE = new RegExp(`^${escapedQuery}`); // Starting prefix match- let sort3RE = new RegExp(`(^| )${escapedQuery}( |$)`); // Non-starting exact match-- const isStartingExactMatch: Record<string, any> = {};- const isStartingPrefixMatch: Record<string, any> = {};- const isExactMatchSomewhere: Record<string, any> = {};- const arr = terms.filter((term) => {- isStartingExactMatch[term.id] = sort1RE.test(term.lowercaseName);- isStartingPrefixMatch[term.id] = sort2RE.test(term.lowercaseName);- isExactMatchSomewhere[term.id] = sort3RE.test(term.lowercaseName);- return includeRE.test(term.lowercaseName);- });-- return arr.sort((t1, t2) => {- const t1IsStartingExactMatch = isStartingExactMatch[t1.id];- const t2IsStartingExactMatch = isStartingExactMatch[t2.id];-- if (t1IsStartingExactMatch === t2IsStartingExactMatch) {- const t1IsStartingPrefixMatch = isStartingPrefixMatch[t1.id];- const t2IsStartingPrefixMatch = isStartingPrefixMatch[t2.id];-- if (t1IsStartingPrefixMatch === t2IsStartingPrefixMatch) {- const t1IsExactMatchSomewhere = isExactMatchSomewhere[t1.id];- const t2IsExactMatchSomewhere = isExactMatchSomewhere[t2.id];- if (t1IsExactMatchSomewhere === t2IsExactMatchSomewhere) {- return t2.numRefs - t1.numRefs;- } else {- return t2IsExactMatchSomewhere - t1IsExactMatchSomewhere;- }- } else {- return t2IsStartingPrefixMatch - t1IsStartingPrefixMatch;- }- } else {- return t2IsStartingExactMatch - t1IsStartingExactMatch;- }- });- }-- isLoaded(): boolean {- return this.#isLoaded;- }-- load(xml: string) {- // we only load the terms once per instance- if (this.#isLoaded) return;-- const terms = XMLUtils.parse(xml).getElementsByTagName('term');- const sortedTerms = Array.from(terms)- .sort((a, b) => {- const aId = a.getAttribute('id') || '';- const bId = b.getAttribute('id') || '';- return parseInt(aId) - parseInt(bId);- })- .map((termNode) => {- const id = termNode.getAttribute('id') || '';- const definition = termNode.getElementsByTagName('definition')[0];- const name = termNode.getAttribute('name') || '';- const defPageNum = parseInt(termNode.getAttribute('page') || '');- const defYPos = parseInt(termNode.getAttribute('y') || '');- const numRefs =- termNode- .getElementsByTagName('references')[0]- ?.getElementsByTagName('reference')?.length ?? 0;- const references = termNode- .getElementsByTagName('references')[0]- ?.getElementsByTagName('reference');- const sims = termNode.getAttribute('sims')- ? (termNode.getAttribute('sims') || '').trim().split(' ')- : [];- return new Term({- name,- definition,- id,- pageNum: defPageNum,- yPos: defYPos,- numRefs,- references,- sims,- });- });-- const ref = this;- sortedTerms.forEach(function (term) {- ref.terms.push(term);- ref.idToTerm.set(term.id, term);- });-- this.#isLoaded = true;- }-}diff --git a/apps/web/src/features/block-pdf/component/AbsoluteDefinitionLookups.tsx b/apps/web/src/features/block-pdf/component/AbsoluteDefinitionLookups.tsxindex 55d30890b1..f4e386a6a6 100644--- a/apps/web/src/features/block-pdf/component/AbsoluteDefinitionLookups.tsx+++ b/apps/web/src/features/block-pdf/component/AbsoluteDefinitionLookups.tsx@@ -1,6 +1,9 @@import type Term from '../model/Term';+import {+ usePopupContextUpdate,+ usePopupStore,+} from '../signal/definitionPopup';import { useIsPopup } from '../signal/pdfViewer';-import { usePopupContextUpdate, usePopupStore } from '../store/definitionPopup';import { DefinitionLookup } from './DefinitionLookup/index';interface IProps {diff --git a/apps/web/src/features/block-pdf/component/Block.tsx b/apps/web/src/features/block-pdf/component/Block.tsxindex 12c8a36bc5..b99d1c7884 100644--- a/apps/web/src/features/block-pdf/component/Block.tsx+++ b/apps/web/src/features/block-pdf/component/Block.tsx@@ -3,7 +3,6 @@ import { SidePanel } from '@components/app/side-panel';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 {useCanComment,@@ -52,7 +51,6 @@ export default function BlockPdf() {viewLocation={data()?.viewLocation}modificationData={data()?.documentMetadata.modificationData}isNested={isNested}- hotkeyScope={blockHotkeyScopeSignal.get()}portalScope="block"permissions={{canComment: canComment(),@@ -70,7 +68,6 @@ export default function BlockPdf() {function PdfBlockContent() {const pdf = usePdfDocument();- const [showTabBar] = pdf.state.signals.showTabBar;return (<ModalsProvider>@@ -79,7 +76,7 @@ function PdfBlockContent() {<PdfSidePanelSections /><div class="flex size-full min-w-0 flex-col overflow-hidden"><TopBar />- <Show when={showTabBar()}>+ <Show when={pdf.tabs.isVisible()}><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 />diff --git a/apps/web/src/features/block-pdf/component/DefinitionLookup/DefinitionsAccordion.tsx b/apps/web/src/features/block-pdf/component/DefinitionLookup/DefinitionsAccordion.tsxindex 6b606ade68..9acde02d46 100644--- a/apps/web/src/features/block-pdf/component/DefinitionLookup/DefinitionsAccordion.tsx+++ b/apps/web/src/features/block-pdf/component/DefinitionLookup/DefinitionsAccordion.tsx@@ -1,19 +1,18 @@import { Accordion } from '@kobalte/core/accordion';import { cn } from '@ui';import Scrollbars from 'solid-custom-scrollbars';-import { createMemo, createSignal, For, type JSX } from 'solid-js';+import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';import { styled } from 'solid-styled-components';+import { usePdfDocument } from '../../context/pdf-document-context';import {Color,determineFormat,hexToRgb,type IColor,} from '../../model/Color';-import type Section from '../../model/Section';import type Term from '../../model/Term';-import { keyedTermDataStore } from '../../PdfViewer/TermDataStore';-import { useTableOfContentsValue } from '../../store/tableOfContents';import { CoParseClassName } from '../../type/coParse';+import { decodeDefinitionText } from '../../util/definitionText';import TocUtils from '../../util/TocUtils';import { OpenRefInNewTabIcon } from './OpenRefInNewTabIcon';import {@@ -21,7 +20,6 @@ import {accordionCardStyles,accordionCollapseStyles,accordionHeadStyles,- decodeString,FONT_SIZE,LINE_HEIGHT,} from './shared';@@ -36,6 +34,7 @@ const htmlSpecialEntities = [['<', '<'],['>', '>'],];+const SECTION_MAX_CHARS = 80;const BootstrapCard = styled.div`width: 100%;@@ -60,7 +59,6 @@ const DefinitionText = styled.p<{ truncated: boolean }>`margin: 0;`;-// removed hover styles because they were being applied on individual charactersconst HoverText = styled.span<{color: string;hoverColor: string;@@ -70,8 +68,6 @@ const HoverText = styled.span<{cursor: pointer;`;-const SECTION_MAX_CHARS = 80;-function filterUniqueTerms(terms: (Term | null)[]): Term[] {let uniqueObj: { [key: string]: Term } = {};terms.forEach((t) => {@@ -84,10 +80,16 @@ function filterUniqueTerms(terms: (Term | null)[]): Term[] {return uniqueTerms;}-function computeRelatedTerms(term: Term): Term[] {- const store = keyedTermDataStore();- if (!store) return [];- let simTerms: (Term | null)[] = term.sims.map((t) => store.get(t));+function truncateSectionDescriptor(descriptor: string): string {+ if (descriptor.length <= SECTION_MAX_CHARS) return descriptor;+ return `${descriptor.substring(0, SECTION_MAX_CHARS)}...`;+}++function computeRelatedTerms(+ term: Term,+ getTerm: (id: string) => Term | null+): Term[] {+ let simTerms: (Term | null)[] = term.sims.map(getTerm);simTerms.unshift(term);return filterUniqueTerms(simTerms);}@@ -95,22 +97,20 @@ function computeRelatedTerms(term: Term): Term[] {interface IProps {truncated: boolean;term: Term;+ getTerm: (id: string) => Term | null;onClick: JSX.EventHandler<HTMLElement, MouseEvent>;- setSection: (section: Section | null) => void;- setHoveredDOMRect: (hoveredDOMRect: DOMRect | null) => void;}export function DefinitionsAccordion(props: IProps) {- const tableOfContentsContext = useTableOfContentsValue();- const terms = createMemo(() => computeRelatedTerms(props.term));+ const idToSectionMap = usePdfDocument().outline.sectionReferenceMap;+ const terms = createMemo(() =>+ computeRelatedTerms(props.term, props.getTerm)+ );- /**- * Generate the span's making up the definition text, including definition and section links- */const constructSpans = (elArr: ChildNode[]) => {const spans = elArr.map((el, _idx) => {const element = el as Element;- const decodedString = decodeString(element);+ const decodedString = decodeDefinitionText(element);const className = element.getAttribute('class');const isSection = className === CoParseClassName.SectionReference;const decodedStringArray = decodedString.split(COLORDELIMITER);@@ -139,7 +139,6 @@ export function DefinitionsAccordion(props: IProps) {snippetText = snippetText.replaceAll(entity[0], entity[1]);});if (isSection || className === CoParseClassName.TermReference) {- // Either a section reference or a term referenceconst classID = element.getAttribute(isSection ? 'secId' : 'defId');const id = `${className}_${classID}`;content.push(@@ -195,7 +194,6 @@ export function DefinitionsAccordion(props: IProps) {}});} else if (isSection || className === CoParseClassName.TermReference) {- // Either a section reference or a term referenceconst classID = element.getAttribute(isSection ? 'secId' : 'defId');const id = `${className}_${classID}`;return (@@ -211,14 +209,12 @@ export function DefinitionsAccordion(props: IProps) {</HoverText>);}- // Regular textif (content.length === 0) {return (<span style={{ 'white-space': 'pre-wrap' }}>{decodedString}</span>);}- // Regular textreturn <span>{content}</span>;});return spans;@@ -243,11 +239,12 @@ export function DefinitionsAccordion(props: IProps) {n.nodeName.includes('span'));const spans = constructSpans(elArr);- const nearestSection = TocUtils.getNearestSection({- page: t.pageNum,- yPos: t.yPos,- pageToSectionMap: tableOfContentsContext().pageToSectionMap,- });+ const nearestSection = () =>+ TocUtils.getNearestSection({+ page: t.pageNum,+ yPos: t.yPos,+ idToSectionMap: idToSectionMap(),+ });return (<Accordion.Item value={'definitionCard' + idx()}>@@ -262,17 +259,20 @@ export function DefinitionsAccordion(props: IProps) {}}><AccordionText>- {nearestSection- ? `In ${- nearestSection.fullDescriptor.length >- SECTION_MAX_CHARS- ? nearestSection.fullDescriptor.substring(- 0,- SECTION_MAX_CHARS- ) + '...'- : nearestSection.fullDescriptor- } on page ${t.pageNum + 1} `- : `On page ${t.pageNum + 1}`}+ <Show+ when={nearestSection()}+ fallback={<>On page {t.pageNum + 1}</>}+ >+ {(section) => (+ <>+ In{' '}+ {truncateSectionDescriptor(+ section().fullDescriptor+ )}{' '}+ on page {t.pageNum + 1}+ </>+ )}+ </Show></AccordionText><OpenRefInNewTabIcon reference={t} term={props.term} /></button>diff --git a/apps/web/src/features/block-pdf/component/DefinitionLookup/ReferencesAccordion.tsx b/apps/web/src/features/block-pdf/component/DefinitionLookup/ReferencesAccordion.tsxindex f1f31213f5..2ddc8d7a4a 100644--- a/apps/web/src/features/block-pdf/component/DefinitionLookup/ReferencesAccordion.tsx+++ b/apps/web/src/features/block-pdf/component/DefinitionLookup/ReferencesAccordion.tsx@@ -1,10 +1,10 @@import { Accordion } from '@kobalte/core/accordion';import { Scrollbars } from 'solid-custom-scrollbars';-import { createSignal, Index } from 'solid-js';+import { createMemo, createSignal, Index, Show } from 'solid-js';import { styled } from 'solid-styled-components';+import { usePdfDocument } from '../../context/pdf-document-context';import Reference from '../../model/Reference';import type Term from '../../model/Term';-import { useTableOfContentsValue } from '../../store/tableOfContents';import { OpenRefInNewTabIcon } from './OpenRefInNewTabIcon';import {AccordionText,@@ -31,15 +31,10 @@ interface IProps {}export function ReferencesAccordion(props: IProps) {- const tableOfContents = useTableOfContentsValue();- const idToSectionMap = () => tableOfContents().idToSectionMap;-- const references = () =>- Array.from(props.term.references).map((e) =>- Reference.fromXML(e, {- idToSectionMap: idToSectionMap(),- })- );+ const idToSectionMap = usePdfDocument().outline.sectionReferenceMap;+ const references = createMemo(() =>+ Array.from(props.term.references).map(Reference.fromXML)+ );const [expandedItem, setExpandedItem] = createSignal(['0']);@@ -47,7 +42,7 @@ export function ReferencesAccordion(props: IProps) {<><DefinitionCount>Found {references().length} reference- {references().length > 1 || references().length === 0 ? 's' : ''}+ <Show when={references().length !== 1}>s</Show></DefinitionCount><ScrollbarsautoHide@@ -60,10 +55,12 @@ export function ReferencesAccordion(props: IProps) {<Accordion value={expandedItem()} onChange={setExpandedItem}><Index each={references()}>{(r, idx) => {- let text = 'On page ' + (r().pageNum + 1);- if (r().sectionName) {- text = `In ${r().sectionName} on page ${r().pageNum + 1}`;- }+ const section = () => {+ const sectionId = r().sectionId;+ if (sectionId == null) return;+ return idToSectionMap()[sectionId];+ };+return (<Accordion.Item value={idx.toString()}><BootstrapCard@@ -78,7 +75,19 @@ export function ReferencesAccordion(props: IProps) {setExpandedItem([idx.toString()]);}}>- <AccordionText>{text}</AccordionText>+ <AccordionText>+ <Show+ when={section()}+ fallback={<>On page {r().pageNum + 1}</>}+ >+ {(section) => (+ <>+ In {section().fullDescriptor} on page{' '}+ {r().pageNum + 1}+ </>+ )}+ </Show>+ </AccordionText><OpenRefInNewTabIcon reference={r()} term={props.term} /></button><Accordion.Content>diff --git a/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsx b/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsxindex 9df5014c49..8bfc969abf 100644--- a/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsx+++ b/apps/web/src/features/block-pdf/component/DefinitionLookup/index.tsx@@ -5,32 +5,30 @@ import {offset,shift,} from '@floating-ui/dom';-import { createEffect, createMemo, type JSX, onCleanup, Show } from 'solid-js';-import { createStore, produce } from 'solid-js/store';+import {+ createEffect,+ createMemo,+ createSignal,+ type JSX,+ Match,+ onCleanup,+ Show,+ Switch,+} from 'solid-js';+import { createStore } from 'solid-js/store';import { styled } from 'solid-styled-components';import { usePdfDocument } from '../../context/pdf-document-context';-import type Section from '../../model/Section';+import { usePdfViewer } from '../../context/pdf-viewer-context';import type Term from '../../model/Term';-import { keyedTermDataStore } from '../../PdfViewer/TermDataStore';+import { usePopupStore } from '../../signal/definitionPopup';import { useIsPopup } from '../../signal/pdfViewer';import { useGoToLocation } from '../../signal/tab';-import { usePopupStore } from '../../store/definitionPopup';-import { useGetIdToSectionMap } from '../../store/tableOfContents';import { CoParseClassName } from '../../type/coParse';import TocUtils from '../../util/TocUtils';import { DefinitionsAccordion } from './DefinitionsAccordion';import { ReferencesAccordion } from './ReferencesAccordion';import { parseDefinitionMetadata } from './shared';-// import { useOpenLocation } from '@app/atoms/tab';-// import { useDoEdit } from '@app/atoms/unsaved';-// import {-// usePinnedTerms,-// useWidgetDispatchContext,-// } from '../../context/WidgetContext';-// import { ILocation } from '../../models/Location';-// import SectionPreview from '../SectionPreview';-const DefinitionLabelWrapper = styled.div`margin-right: auto;overflow: hidden;@@ -57,7 +55,6 @@ const Card = styled.div<{ isPinsWindow: boolean }>`height: 100%;box-sizing: border-box;border-radius: 2px;- // No box shadow, take full width, have padding if in pins window${({ isPinsWindow }) =>isPinsWindow? `@@ -99,27 +96,13 @@ type IProps = {});-export interface IState {- left?: number;- width?: number;- activeTab: 'DEFINITION_TAB' | 'REFERENCE_TAB';-- // For section preview- section: Section | null;- hoveredDOMRect: DOMRect | null;-}-export function DefinitionLookup(props: IProps) {- const popupOpen = usePdfDocument().state.derived.popupOpen;+ const pdf = usePdfDocument();+ const popupOpen = usePdfViewer().isPopupOpen;const isPopup = useIsPopup();- const getIdToSectionMap = useGetIdToSectionMap();- // popupAtoms => popupStoreconst popupStore = usePopupStore(isPopup);const termIDToSizingMap = popupStore.termIDToSizingMap;const terms = popupStore.terms;- const termDataStore = keyedTermDataStore();- // const widgetDispatch = useWidgetDispatchContext();- // const pinnedTerms = usePinnedTerms();let termRef: HTMLDivElement | undefined;const pageWidth = popupStore.pageWidth;@@ -155,11 +138,9 @@ export function DefinitionLookup(props: IProps) {return newPageWidth;});- const [state, updateState] = createStore<IState>({- hoveredDOMRect: null,- section: null,- activeTab: 'DEFINITION_TAB',- });+ const [activeTab, setActiveTab] = createSignal<+ 'DEFINITION_TAB' | 'REFERENCE_TAB'+ >('DEFINITION_TAB');const sizing = () =>props.term?.id ? termIDToSizingMap()[props.term.id] : undefined;@@ -172,9 +153,7 @@ export function DefinitionLookup(props: IProps) {if (className === CoParseClassName.SectionReference) {e.stopPropagation();- // when current TOC is using PDF bookmarks, use the AI TOC's ID-to-section- // mapping since the section references are built from the AI TOC- const idToSectionMap = getIdToSectionMap();+ const idToSectionMap = pdf.outline.sectionReferenceMap();const section = TocUtils.getSection({ id, idToSectionMap });openLocation({newTab: true,@@ -184,17 +163,14 @@ export function DefinitionLookup(props: IProps) {});} else if (className === CoParseClassName.TermReference) {e.stopPropagation();- const term = termDataStore?.get('' + id);+ const term = pdf.definitions.getTerm(`${id}`);if (!term) {console.error('Term not found');return;}- if (props.isPinsWindow) {- // widgetDispatch({ type: 'ADD_PINNED_TERM', term, index: props.index });- } else {- props.addNextTerm?.(term);- }+ if (props.isPinsWindow) return;+ props.addNextTerm?.(term);} else {e.stopPropagation();// NOTE this only applies in the non-pins case@@ -252,58 +228,35 @@ export function DefinitionLookup(props: IProps) {<div style={{ display: 'flex' }}><TabButtonclass="definition-popup-tab-button"- isActive={state.activeTab === 'DEFINITION_TAB'}- on:click={() =>- updateState(- produce((draft) => {- draft.activeTab = 'DEFINITION_TAB';- })- )- }+ isActive={activeTab() === 'DEFINITION_TAB'}+ on:click={() => setActiveTab('DEFINITION_TAB')}>Terms</TabButton><TabButtonclass="definition-popup-tab-button"- isActive={state.activeTab === 'REFERENCE_TAB'}- on:click={() =>- updateState(- produce((draft) => {- draft.activeTab = 'REFERENCE_TAB';- })- )- }+ isActive={activeTab() === 'REFERENCE_TAB'}+ on:click={() => setActiveTab('REFERENCE_TAB')}>Uses</TabButton></div></div>- {state.activeTab === 'DEFINITION_TAB' ? (- <DefinitionsAccordion- term={props.term}- truncated={sizing()?.truncated ?? false}- onClick={onClick}- setHoveredDOMRect={(hoveredDOMRect) =>- updateState(- produce((draft) => {- draft.hoveredDOMRect = hoveredDOMRect;- })- )- }- setSection={(section) =>- updateState(- produce((draft) => {- draft.section = section;- })- )- }- />- ) : state.activeTab === 'REFERENCE_TAB' ? (- <ReferencesAccordion term={props.term} />- ) : null}+ <Switch>+ <Match when={activeTab() === 'DEFINITION_TAB'}>+ <DefinitionsAccordion+ term={props.term}+ truncated={sizing()?.truncated ?? false}+ getTerm={pdf.definitions.getTerm}+ onClick={onClick}+ />+ </Match>+ <Match when={activeTab() === 'REFERENCE_TAB'}>+ <ReferencesAccordion term={props.term} />+ </Match>+ </Switch></Card></div>- {/* <SectionPreview section={section} hoveredDOMRect={state.hoveredDOMRect} /> */}<Show when={!props.isPinsWindow && nextTerm()}>{(nextTerm) => (<DefinitionLookupdiff --git a/apps/web/src/features/block-pdf/component/DefinitionLookup/shared.tsx b/apps/web/src/features/block-pdf/component/DefinitionLookup/shared.tsxindex 34f5937407..cb2db46133 100644--- a/apps/web/src/features/block-pdf/component/DefinitionLookup/shared.tsx+++ b/apps/web/src/features/block-pdf/component/DefinitionLookup/shared.tsx@@ -5,23 +5,9 @@ export const AccordionText = styled('span')`line-height: 18px;`;-export const MAX_LINES = 14;export const FONT_SIZE = 16;export const LINE_HEIGHT = 1.1;-/**- * Convert HTML string into text- */-export function decodeString(e: Element): string {- var lineBreaks = /<br\/>/g;- var endBreak = /(?<=.)(<br\/>)$/g;- if (!e.innerHTML) return '';- const decodedString = e.innerHTML- ?.replaceAll(endBreak, '')- .replaceAll(lineBreaks, '\r\n\n');- return decodedString;-}-export function parseDefinitionMetadata(element: Element): {className: string;id: number;diff --git a/apps/web/src/features/block-pdf/component/Document.tsx b/apps/web/src/features/block-pdf/component/Document.tsxindex e5de87e915..44f5b3e3bc 100644--- a/apps/web/src/features/block-pdf/component/Document.tsx+++ b/apps/web/src/features/block-pdf/component/Document.tsx@@ -22,6 +22,7 @@ import { createCallback } from '@solid-primitives/rootless';import { debounce } from '@solid-primitives/scheduled';import { cn } from '@ui';import {+ batch,createDeferred,createEffect,createMemo,@@ -36,9 +37,10 @@ import {untrack,} from 'solid-js';import { Portal } from 'solid-js/web';+import { usePdfComments } from '../context/pdf-comments-context';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import { PageModel } from '../model/Page';-import { useGoToLinkLocation } from '../signal/location';import {initializePdfViewer,useIsPopup,@@ -47,7 +49,9 @@ import {import { usePdfSaveLocation, useSaveModificationData } from '../signal/save';import { useLoadAnnotations } from '../store/annotations';import { useSetSelectionHighlights } from '../store/highlight';+import { PayloadMode } from '../type/placeables';import { type IPageOverlayProps, PageOverlay } from './PageOverlay';+import { RightMarginLayout } from './RightMarginLayout';import { SimpleSearch } from './SimpleSearch';false && observedSize;@@ -57,12 +61,11 @@ const PDF = 72.0;const PDF_TO_CSS_UNITS = CSS / PDF;function InnerDocument() {- const { state } = usePdfDocument();+ const pdfViewer = usePdfViewer();const isPopup = useIsPopup();- const getViewer = () =>- isPopup ? state.signals.popupViewer[0]() : state.signals.rootViewer[0]();+ const viewer = isPopup ? pdfViewer.popup : pdfViewer.root;+ const getViewer = viewer.instance;- // attach new tab listenersconst goToLocationHash = useGoToLocationHash();// TODO (seamus) : Chatted with Rithy. Manual cleanup should not be@@ -83,9 +86,8 @@ function InnerDocument() {cleanupNewTabHandler = () => {};});- // watch the overlays and send the contents to be rendered by PDFViewercreateEffect(() => {- const overlays = state.signals.overlays[0]();+ const overlays = pdfViewer.overlays();if (!overlays || overlays.length === 0) return;getViewer()?.setOverlays(overlays);});@@ -94,13 +96,11 @@ function InnerDocument() {usePdfCommentEffects();}const showOverlays = createMemo(- () =>- (isPopup ? state.derived.popupOpen() : true) &&- state.derived.viewerReady()+ () => (isPopup ? pdfViewer.isPopupOpen() : true) && pdfViewer.root.isReady());const overlayViewsChanged = isPopup- ? state.signals.overlayViewsChangedPopup[0]- : state.signals.overlayViewsChanged[0];+ ? pdfViewer.popup.overlayViews+ : pdfViewer.root.overlayViews;const pageOverlays = () => {const pageViews = createMemo<IPageOverlayProps[]>(@@ -115,7 +115,6 @@ function InnerDocument() {const pageViewDiv = view.div;const viewport = view.textLayer?.viewport ?? view.viewport;- // Use the cached page view if it exists and nothing changedif (cachedPageView &&cachedPageView.pageViewDiv === pageViewDiv &&@@ -147,13 +146,20 @@ function InnerDocument() {if (!container) return '';return (- <Portal mount={container}>- <PageOverlay- pageIndex={pageIndex}- viewport={viewport}- pageViewDiv={pageViewDiv}- />- </Portal>+ <>+ <Portal mount={container}>+ <PageOverlay+ pageIndex={pageIndex}+ viewport={viewport}+ pageViewDiv={pageViewDiv}+ />+ </Portal>+ <Show when={!isPopup}>+ <Portal mount={container}>+ <RightMarginLayout pageIndex={pageIndex} />+ </Portal>+ </Show>+ </>);}}</For>@@ -163,12 +169,10 @@ function InnerDocument() {return <Show when={showOverlays()}>{pageOverlays()}</Show>;}-/** Shows the document loading spinner without unloading the PDF Viewer */function LoadingDocumentSpinnerEffect() {- const viewerHasVisiblePages =- usePdfDocument().state.signals.viewerHasVisiblePages[0];+ const hasVisiblePages = usePdfViewer().root.hasVisiblePages;return (- <Show when={!viewerHasVisiblePages()}>+ <Show when={!hasVisiblePages()}><div class="flex absolute size-full z-viewer-document-loading-spinner"><div class="absolute top-1/2 left-1/2 transform -translate-1/2"><LoadingSpinner />@@ -180,90 +184,24 @@ function LoadingDocumentSpinnerEffect() {export function Document() {const pdf = usePdfDocument();- const { signals, stores, derived } = pdf.state;+ const pdfViewer = usePdfViewer();+ const comments = usePdfComments();const [documentSize, setDocumentSize] = createSignal<DOMRect>();const [documentContainerRef, setDocumentContainerRef] =createSignal<HTMLDivElement>();- 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);+ const [destroying, setDestroying] = createSignal(false);+ const getRootViewer = pdfViewer.root.instance;+ const getPopupViewer = pdfViewer.popup.instance;+ const disableClick = () =>+ pdf.markup.mode() !== PayloadMode.NoMode || pdfViewer.textSelectionActive();+ const beginViewerTextSelection = () => {+ if (pdfViewer.textSelectionActive()) return;+ batch(() => {+ comments.clearSelectedThread();+ pdfViewer.beginTextSelection();+ });};+ const blockElement = pdfViewer.rootElement;let rootViewer: PDFViewer | undefined;let popupViewer: PDFViewer | undefined;@@ -275,11 +213,10 @@ export function Document() {popupViewer = initializePdfViewer();rootViewer = initializePdfViewer(popupViewer);- attachViewerSignals(rootViewer, false);- attachViewerSignals(popupViewer, true);-- setPopupViewer(popupViewer);- setRootViewer(rootViewer);+ pdfViewer.installPair({+ root: rootViewer,+ popup: popupViewer,+ });});let mountRef: HTMLDivElement | undefined;@@ -289,7 +226,6 @@ export function Document() {const viewer = getRootViewer();const size = documentSize();if (!size) return;- // wait for valid dimensionsif (size.width === 0 || size.height === 0) {return;}@@ -300,14 +236,12 @@ export function Document() {onCleanup(() => {setDestroying(true);- popupViewer && detachViewerSignals(popupViewer, true);-if (!rootViewer) {- console.warn('unable to detach signals');+ console.warn('unable to detach viewer listeners');return;}- detachViewerSignals(rootViewer, false);+ pdfViewer.detachListeners();rootViewer.destroy()@@ -315,8 +249,7 @@ export function Document() {.finally(() => {popupViewer = undefined;rootViewer = undefined;- setRootViewer(undefined);- setPopupViewer(undefined);+ pdfViewer.clearPair();setDestroying(false);});});@@ -325,24 +258,18 @@ export function Document() {const canSaveModificationData = pdf.permissions.canEdit;const loadAnnotations = useLoadAnnotations();- const serverModificationData = signals.serverModificationData[0];- const hasServerModificationData = () => !!serverModificationData();const updateModificationDataOnLoad = () =>- canSaveModificationData() && !hasServerModificationData();+ canSaveModificationData() && !pdf.model.hasServerSnapshot();createEffect((prevDocumentId) => {const rootPdfViewer = getRootViewer();const popupPdfViewer = getPopupViewer();if (!rootPdfViewer || !popupPdfViewer) return;- const documentProxy = signals.documentProxy[0]();- const modificationData = stores.modificationData[0];+ const documentProxy = pdf.documentProxy();if (documentProxy) {- const annotationsPromise = loadAnnotations(- documentProxy,- modificationData- );+ const annotationsPromise = loadAnnotations(documentProxy);if (updateModificationDataOnLoad()) {annotationsPromise.then(saveModificationData);@@ -370,9 +297,7 @@ export function Document() {!selection.getRangeAt(0) ||selection.getRangeAt(0).collapsed;- const isPopupOpen = createMemo(derived.popupOpen);- const setGeneralPopupLocation = signals.generalPopupLocation[1];- const setLocationStore = stores.location[1];+ const isPopupOpen = pdfViewer.isPopupOpen;const handleSelection = async (selection: Selection, pageIndex: number) => {const viewer = getRootViewer();@@ -408,14 +333,11 @@ export function Document() {const selectionString = selection.toString();if (selectionString.trim().length === 0) {- setLocationStore('annotation', undefined);- setLocationStore('precise', undefined);+ pdf.setShareLocation(undefined);return;}- // let shouldHandleDefinition = isValidTerm(selectionString);- setLocationStore('annotation', undefined);- setLocationStore('precise', {+ pdf.setShareLocation({type: 'precise',pageIndex: pageIndex + 1,...location,@@ -423,15 +345,14 @@ export function Document() {setSelectionHighlights(selection);- // set anchor element for the definition popup- setGeneralPopupLocation({ pageIndex, element });+ pdf.openSelectionMenu({ pageIndex, element });};const selectionHandler: JSX.EventHandler<HTMLDivElement,MouseEvent | TouchEvent> = createCallback((e) => {- setIsSelecting(false);+ pdfViewer.endTextSelection();if (!(e.target instanceof HTMLElement)) return;@@ -475,12 +396,12 @@ export function Document() {case '+':case '=':e.preventDefault();- if (derived.canZoomIn()) viewer.zoomIn();+ if (pdfViewer.root.canZoomIn()) viewer.zoomIn();break;case '_':case '-':e.preventDefault();- if (derived.canZoomOut()) viewer.zoomOut();+ if (pdfViewer.root.canZoomOut()) viewer.zoomOut();break;case 'PageUp':case 'ArrowLeft':@@ -534,13 +455,13 @@ export function Document() {};const setMouseUp = () => {- setIsSelecting(false);+ pdfViewer.endTextSelection();setMouseDown(false);};const selectStartHandler = () => {if (!mouseDown()) return;- setIsSelecting(true);+ beginViewerTextSelection();};element.addEventListener('mousedown', mouseDownHandler);@@ -554,12 +475,6 @@ export function Document() {});});- const goToLinkLocation = useGoToLinkLocation();- createEffect(() => {- if (signals.locationChanged[0]() || !derived.viewerReady()) return;- goToLinkLocation(pdf.locationParams());- });-const [initialized, setInitialized] = createSignal(false);createEffect(on(@@ -576,7 +491,7 @@ export function Document() {)return;- const currentPage = derived.currentPageNumber();+ const currentPage = pdfViewer.root.currentPageNumber();const pdfDimensions = viewer.pageViewport(currentPage);if (!pdfDimensions) return;@@ -608,46 +523,29 @@ export function Document() {));- createEffect(() => {- setLocationStore('general', {- type: 'general',- pageIndex: derived.currentPageNumber(),- y: 0,- });- });-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 = signals.modificationDataSaveRequired[1];+ const isSaving = createDeferred(pdf.persistence.isSaving);+ const currentRevision = createDeferred(pdf.model.revision);+ const [savedRevision, setSavedRevision] = createSignal(0);createEffect(() => {if (isSaving()) return;- const currOps = currentOperations();- const savedOps = savedOperations();- if (currOps > savedOps) {- setSaveRequired(true);- } else {- setSaveRequired(false);- return;- }+ const revision = currentRevision();+ if (revision <= savedRevision()) return;- saveModificationData().then(() => setSavedOperations(currOps));+ saveModificationData().then(() => setSavedRevision(revision));});}// TODO: hacky location autosave that works on page refresh// without requiring a confirm dialogif (ENABLE_PDF_LOCATION_AUTOSAVE && !pdf.isNested()) {- const isSaving = createDeferred(signals.isSaving[0]);- const viewChanged = createDeferred(signals.visiblePagesChanged[0]);+ const isSaving = createDeferred(pdf.persistence.isSaving);+ const viewChanged = createDeferred(pdfViewer.root.viewArea);const saveLocation = usePdfSaveLocation();const debouncedSaveLocation = debounce(saveLocation, 1000);createEffect(() => {- // listen to root viewer changed view area- // e.g. scroll, zoom, go to, etc.viewChanged();if (untrack(isSaving)) return;diff --git a/apps/web/src/features/block-pdf/component/MarkupToolbar.tsx b/apps/web/src/features/block-pdf/component/MarkupToolbar.tsxindex 6ce86464bb..df1afd773c 100644--- a/apps/web/src/features/block-pdf/component/MarkupToolbar.tsx+++ b/apps/web/src/features/block-pdf/component/MarkupToolbar.tsx@@ -16,14 +16,12 @@ export function MarkupToolbar() {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 showCancel = () => pdf.markup.mode() !== PayloadMode.NoMode;const ownedCommentSelector = useOwnedCommentPlaceableSelector();const showDelete = createMemo(() => {- const uuid = activePlaceableId();+ const uuid = pdf.markup.activeId();if (!uuid) return false;const activePlaceable = placeableIdMap()?.[uuid];if (!activePlaceable) return false;@@ -41,7 +39,9 @@ export function MarkupToolbar() {label="Text Box"variant="ghost"onClick={() => {- setMode(PayloadMode.FreeTextAnnotation);+ pdf.markup.commands.beginPlacement(+ PayloadMode.FreeTextAnnotation+ );}}><Textbox />@@ -50,7 +50,9 @@ export function MarkupToolbar() {size="icon-sm"label="Signature"variant="ghost"- onClick={() => setMode(PayloadMode.Signature)}+ onClick={() =>+ pdf.markup.commands.beginPlacement(PayloadMode.Signature)+ }><Signature /></Button>@@ -60,7 +62,7 @@ export function MarkupToolbar() {label="Comment"variant="ghost"onClick={() => {- setMode(PayloadMode.Thread);+ pdf.markup.commands.beginPlacement(PayloadMode.Thread);}}><ChatTeardrop />@@ -83,7 +85,7 @@ export function MarkupToolbar() {variant="danger"tooltip="Delete"onClick={() => {- const activePlaceableIndex_ = activePlaceableId();+ const activePlaceableIndex_ = pdf.markup.activeId();if (activePlaceableIndex_ == null) return;deletePlaceable(activePlaceableIndex_);}}@@ -98,7 +100,7 @@ export function MarkupToolbar() {variant="danger"tooltip="Cancel"onClick={() => {- setMode(PayloadMode.NoMode);+ pdf.markup.commands.cancelPlacement();}}><Cancel />diff --git a/apps/web/src/features/block-pdf/component/PDFPopup.tsx b/apps/web/src/features/block-pdf/component/PDFPopup.tsxindex 51bde34330..8e721f3482 100644--- a/apps/web/src/features/block-pdf/component/PDFPopup.tsx+++ b/apps/web/src/features/block-pdf/component/PDFPopup.tsx@@ -1,25 +1,12 @@import type { IHighlight } from '@block-pdf/model/Highlight';-import { useSplitLayout } from '@components/app/split-layout/layout';-import { useIsAuthenticated } from '@core/auth';-import { ChatMessageMarkdown } from '@core/component/AI/component/message/ChatMessageMarkdown';import { GeneralizedPopup } from '@core/component/GeneralizedPopup/Popup';-import { createMarkdownFile } from '@core/util/create';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';-import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';import ChatIcon from '@phosphor-icons/core/regular/chat-teardrop.svg?component-solid';-import PasteIcon from '@phosphor-icons/core/regular/clipboard-text.svg?component-solid';import LinkIcon from '@phosphor-icons/core/regular/link.svg?component-solid';import TrashIcon from '@phosphor-icons/core/regular/trash.svg?component-solid';-import { generateTitle } from '@service-cognition/client';-import { createCallback } from '@solid-primitives/rootless';import { Button } from '@ui';import {- createEffect,- createMemo,createSignal,- For,Match,onCleanup,onMount,@@ -27,6 +14,7 @@ import {Switch,} from 'solid-js';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';type PDFPopupProps = {highlightProps: {@@ -53,12 +41,6 @@ type PDFPopupProps = {/** share the currently selected region of the document */share: () => void;};- aiProps?: {- attachmentId: string;- };- insertProps?: {- insertText: (text: string) => void;- };/** where to anchor the popup */anchorRef: HTMLElement;};@@ -68,300 +50,107 @@ function HighlightIcon() {return <div class="size-4 bg-[oklch(0.905_0.182_98.111)] rounded-full"></div>;}-function LoadingContent(props: { lines: number }) {- return (- <div class="flex flex-col justify-center items-start w-full py-2">- <For each={Array.from({ length: props.lines })}>- {() => <div class="bg-edge animate-pulse rounded-md h-2 mb-2 w-full" />}- </For>- <div class="bg-edge animate-pulse rounded-md h-2 mb-2 w-[65%]" />- </div>- );-}-export function PDFPopup(props: PDFPopupProps) {- const _isAuthenticated = useIsAuthenticated();-const pdf = usePdfDocument();+ const rootElement = usePdfViewer().rootElement;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);- const [isLoading, setIsLoading] = createSignal<boolean>(false);- let markdownRootRef!: HTMLDivElement;-- const width = () => (completion() === undefined ? 'w-auto' : '600px');-- const { replaceOrInsertSplit } = useSplitLayout();-- createEffect(() => {- const currentSelection = window.getSelection()?.toString();- if (currentSelection && currentSelection.length > 0) {- setSelectedText(currentSelection);- }- });-- const _selectedText = createMemo(() => {- const currentSelection = selectedText();- if (currentSelection && currentSelection.length > 0) {- return currentSelection;- }- return props.highlightProps.currentHighlight?.text;- });-- const handleCopy = async () => {- const cleanedText = completion()?.content;- if (!cleanedText) {- return;- }- const html = markdownRootRef?.outerHTML ?? null;- if (!html) {- try {- await navigator.clipboard.writeText(cleanedText);- setCopied(true);- setTimeout(() => setCopied(false), 2000);- } catch {}- return;- }-- const clipboardItem = new ClipboardItem({- 'text/plain': new Blob([cleanedText], { type: 'text/plain' }),- 'text/html': new Blob([html], { type: 'text/html' }),- });- let written = false;- // try rich and plain first. Not avail in all browsers and contexts.- try {- await navigator.clipboard.write([clipboardItem]);- written = true;- setCopied(true);- setTimeout(() => setCopied(false), 2000);- } catch {}-- if (!written) {- try {- await navigator.clipboard.writeText(cleanedText);- written = true;- setCopied(true);- setTimeout(() => setCopied(false), 2000);- } catch {}- }- };-- const handleEditInMarkdown = createCallback(async () => {- setIsLoading(true);- const content = completion()?.content;- if (!content) {- return;- }-- const title = await generateTitle(content);- const documentId = await createMarkdownFile({- content,- title: title ?? `${pdf.documentName()} - AI Explanation`,- });-- if (!documentId) {- console.error('Error opening AI message in Notes');- setIsLoading(false);- return;- }-- replaceOrInsertSplit({- type: 'md',- id: documentId,- });- setIsLoading(false);- });onMount(() => {- const handler = (e: Event) => {- e.stopPropagation();+ const stopSelectionChangePropagation = (event: Event) => {+ event.stopPropagation();};-- const blockElement = pdf.rootElement();- if (blockElement) {- blockElement.addEventListener('selectionchange', handler, {- capture: true,- });- }-+ const blockElement = rootElement();+ blockElement?.addEventListener(+ 'selectionchange',+ stopSelectionChangePropagation,+ { capture: true }+ );onCleanup(() => {- if (blockElement) {- blockElement.removeEventListener('selectionchange', handler, {- capture: true,- });- }+ blockElement?.removeEventListener(+ 'selectionchange',+ stopSelectionChangePropagation,+ { capture: true }+ );});});const PDFPopupToolbar = () => {const [locationCopied, setLocationCopied] = createSignal(false);return (- <>- <div class="flex flex-row items-center space-x-2 justify-between w-full">- {/*<Show when={isAuthenticated() && !!selectedText() && props.aiProps}>- {(aiProps) => (- <AskAi- attachmentId={aiProps().attachmentId}- blockName="pdf"- setCompletion={setCompletion}- selectedText={selectedText()!}- />- )}- </Show>*/}- <div class="flex flex-row space-x-2 items-center">- <Show when={completion() && props.insertProps}>- {(insertProps) => (+ <div class="flex flex-row items-center space-x-2 justify-between w-full">+ <div class="flex flex-row space-x-2 items-center">+ <Switch>+ <Match when={!props.highlightProps.currentHighlight}>+ <Show when={props.highlightProps.canCreate}><Buttonvariant="ghost"size="icon-md"- onClick={() =>- insertProps().insertText(completion()!.content)- }- title="Insert AI response"+ onClick={() => {+ props.highlightProps.highlight();+ }}>- <PasteIcon />+ <HighlightIcon /></Button>- )}- </Show>-- <Switch>- <Match when={!props.highlightProps.currentHighlight}>- <Show when={props.highlightProps.canCreate}>- <Button- variant="ghost"- size="icon-md"- onClick={() => {- props.highlightProps.highlight();- }}- >- <HighlightIcon />- </Button>- </Show>- </Match>- <Match when={props.highlightProps.currentHighlight}>- <Show when={props.highlightProps.canEdit}>- <Button- variant="ghost"- size="icon-md"- onClick={() => {- props.highlightProps.removeHighlight();- }}- >- <TrashIcon />- </Button>- </Show>- </Match>- </Switch>-- <Show- when={- props.highlightProps.currentHighlight- ? props.commentProps.canEdit- : props.commentProps.canCreate+ </Show>+ </Match>+ <Match when={props.highlightProps.currentHighlight}>+ <Show when={props.highlightProps.canEdit}>+ <Button+ variant="ghost"+ size="icon-md"+ onClick={() => {+ props.highlightProps.removeHighlight();+ }}+ >+ <TrashIcon />+ </Button>+ </Show>+ </Match>+ </Switch>++ <Show+ when={+ props.highlightProps.currentHighlight+ ? props.commentProps.canEdit+ : props.commentProps.canCreate+ }+ >+ <Button+ variant="ghost"+ size="icon-md"+ onClick={(e: MouseEvent | KeyboardEvent) =>+ props.commentProps.placeComment(e as MouseEvent)}>- <Button- variant="ghost"- size="icon-md"- onClick={(e: MouseEvent | KeyboardEvent) =>- props.commentProps.placeComment(e as MouseEvent)- }- >- <ChatIcon />- </Button>- </Show>- </div>- <Show when={props.shareLinkProps}>- {(shareLinkProps) => (- <Button- variant="ghost"- onClick={() => {- setLocationCopied(true);- shareLinkProps().share();- }}- >- {locationCopied() ? (- <CheckIcon class="text-success" />- ) : (- <LinkIcon />- )}- {locationCopied() ? 'Copied' : 'Share'}- </Button>- )}+ <ChatIcon />+ </Button></Show></div>-- <Show when={completion()}>- {(completion) => (- <div- class="flex flex-col items-center space-x-2 w-full px-2 border-t border-edge mt-1"- style={{- width: width(),+ <Show when={props.shareLinkProps}>+ {(shareLinkProps) => (+ <Button+ variant="ghost"+ onClick={() => {+ setLocationCopied(true);+ shareLinkProps().share();}}><Show- when={- completion().status !== 'loading' &&- completion().content.length > 0+ when={locationCopied()}+ fallback={+ <>+ <LinkIcon />+ Share+ </>}- fallback={<LoadingContent lines={4} />}>- <div class="w-full max-w-full overflow-hidden">- <ChatMessageMarkdown- text={completion().content}- generating={isGenerating}- rootRef={(ref: HTMLDivElement) => {- markdownRootRef = ref;- }}- />- </div>+ <CheckIcon class="text-success" />+ Copied</Show>- <div class="w-full border-t border-edge">- <div class="flex flex-row w-full justify-end text-ink-muted mt-1">- <div class="w-fit mr-2">- <button- class="flex flex-row items-center space-x-1 hover:bg-hover hover-transition-bg rounded-md p-1 text-xs font-sans"- onClick={() => {- !isLoading() && handleEditInMarkdown();- }}- >- <Show- when={!isLoading() && !isGenerating()}- fallback={<LoadingIcon class="size-3 animate-spin" />}- >- <NotesIcon class="size-3 text-note" />- </Show>- <p>Edit in Notes</p>- </button>- </div>- <div class="w-fit">- <button- class="flex flex-row items-center space-x-1 hover:bg-hover hover-transition-bg rounded-md p-1 text-xs font-sans"- onClick={handleCopy}- >- <Show- when={!isGenerating()}- fallback={<LoadingIcon class="size-3 animate-spin" />}- >- <Show- when={!copied()}- fallback={<CheckIcon class="size-3 text-success" />}- >- <ClipboardIcon class="size-3" />- </Show>- </Show>- <p>{copied() ? 'Copied!' : 'Copy'}</p>- </button>- </div>- </div>- </div>- </div>+ </Button>)}</Show>- </>+ </div>);};diff --git a/apps/web/src/features/block-pdf/component/PageNumberInput.tsx b/apps/web/src/features/block-pdf/component/PageNumberInput.tsxindex 0489a3fda9..e3c51b0e97 100644--- a/apps/web/src/features/block-pdf/component/PageNumberInput.tsx+++ b/apps/web/src/features/block-pdf/component/PageNumberInput.tsx@@ -1,11 +1,11 @@import { createCallback } from '@solid-primitives/rootless';import { cn } from '@ui';import { createEffect, createSignal, onCleanup, Show } from 'solid-js';-import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import { useCurrentPageNumber, useGetRootViewer } from '../signal/pdfViewer';export function PageNumberInput() {- const pdf = usePdfDocument();+ const pdfViewer = usePdfViewer();// const context = useContext(BarContext);// if (!context) throw new Error('PageNumberInput must be used within a Bar');// const truncation = context.truncation;@@ -16,7 +16,7 @@ export function PageNumberInput() {const [intermediateVal, setIntermediate] = createSignal<string>('');const inputValue = () => intermediateVal() || currentPageNumber();- const getPageCount = () => pdf.state.derived.pageCount() ?? 1;+ const getPageCount = () => pdfViewer.root.pageCount() ?? 1;const getWidthClass = (value: number | string) => {const strLength = value.toString().length;@@ -44,7 +44,7 @@ export function PageNumberInput() {});createEffect(() => {- const element = pdf.rootElement();+ const element = pdfViewer.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.tsxindex 0cf358dd0e..32b67c0045 100644--- a/apps/web/src/features/block-pdf/component/PageOverlay.tsx+++ b/apps/web/src/features/block-pdf/component/PageOverlay.tsx@@ -26,20 +26,23 @@ import {onMount,Show,} from 'solid-js';+import { usePdfComments } from '../context/pdf-comments-context';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-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 {+ usePopupContextUpdate,+ usePopupStore,+} from '../signal/definitionPopup';import { LocationType, useCreateShareUrl } from '../signal/location';import { useIsPopup } from '../signal/pdfViewer';-import { usePopupContextUpdate, usePopupStore } from '../store/definitionPopup';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 { UserHighlight, useResetUserHighlights } from './UserHighlight';export interface IPageOverlayProps {@@ -55,18 +58,18 @@ export interface IHighlightObj {height: number;color: IColor;threadId: number | null;- highlightId: string; // uuid of the highlight that contains this rect- rectId: string; // unique identifier of this rect+ highlightId: string;+ rectId: string;text?: string;isActive: boolean;}-// This is where all the page-specifc overlays should reside, like placeables, etc.export function PageOverlay(props: IPageOverlayProps) {const analytics = useAnalytics();const pdf = usePdfDocument();- const { signals, stores, derived } = pdf.state;+ const pdfViewer = usePdfViewer();+ const comments = usePdfComments();let pageOverlayRef!: HTMLDivElement;const pageViewDivProp = () => props.pageViewDiv;@@ -74,10 +77,9 @@ export function PageOverlay(props: IPageOverlayProps) {const commentAccess = pdf.permissions.canComment;const isDocumentOwner = pdf.permissions.isOwner;- const [mode, setMode] = signals.placeableMode;- const getPopupViewer = signals.popupViewer[0];- const getRootViewer = signals.rootViewer[0];- const getIdToSectionMap = useGetIdToSectionMap();+ const mode = pdf.markup.mode;+ const getPopupViewer = pdfViewer.popup.instance;+ const getRootViewer = pdfViewer.root.instance;const isPopup = useIsPopup();const popupDispatchCtx = usePopupContextUpdate(isPopup);const popupTerms = usePopupStore(isPopup).terms;@@ -85,13 +87,12 @@ export function PageOverlay(props: IPageOverlayProps) {const isAuth = useIsAuthenticated();const createPlaceable = useCreatePlaceable();const commentPlaceables = useCommentPlaceables();- const disableOverlayClick = signals.disableOverlayClick[0];- const setActiveThreadId = signals.activeCommentThread[1];- const disablePageViewClick = signals.disablePageViewClick[0];- const termDataStore = pdf.state.termDataStore;+ const overlayClicksDisabled = () =>+ mode() !== PayloadMode.NoMode || pdfViewer.textSelectionActive();+ const pageClicksDisabled = pdfViewer.pageClicksDisabled;const onClick = (e: MouseEvent) => {- if (disablePageViewClick()) return;+ if (pageClicksDisabled()) return;if (mode() !== PayloadMode.NoMode) {return;@@ -105,7 +106,6 @@ export function PageOverlay(props: IPageOverlayProps) {const defID = parent?.getAttribute('defid');if (defID) {- // display definition for termconst tokenID = tgt.getAttribute('id');if (!tokenID) {@@ -120,7 +120,7 @@ export function PageOverlay(props: IPageOverlayProps) {return;}- const term = termDataStore?.get(defID);+ const term = pdf.definitions.getTerm(defID);if (!term) {console.error('Term not found on click');@@ -141,11 +141,10 @@ export function PageOverlay(props: IPageOverlayProps) {});analytics.track('block_pdf_definition_open');} else if (secID) {- // display section popupe.stopPropagation();const secIDNumber = parseInt(secID);- const idToSectionMap = getIdToSectionMap();+ const idToSectionMap = pdf.outline.sectionReferenceMap();const { page, y } = TocUtils.getSection({id: secIDNumber,idToSectionMap,@@ -188,7 +187,6 @@ export function PageOverlay(props: IPageOverlayProps) {});const onKeyDown = (e: KeyboardEvent) => {- // Ignore custom handling if editing inside a text placeableif (document.activeElement &&(document.activeElement.tagName === 'TEXTAREA' ||@@ -197,7 +195,6 @@ export function PageOverlay(props: IPageOverlayProps) {return;}const browser = detect();- // Handle copy/cut here since clipboard event listeners are blocked with some placeable typesif (e.key === 'c' &&((browser?.os !== 'Mac OS' && e.ctrlKey) ||@@ -241,7 +238,7 @@ export function PageOverlay(props: IPageOverlayProps) {});});- const disableSelect = signals.disableViewerTextSelection[0];+ const disableSelect = () => comments.selectedThreadId() != null;createEffect(() => {const pageViewDiv = pageViewDivProp();if (!pageViewDiv) return;@@ -254,10 +251,10 @@ export function PageOverlay(props: IPageOverlayProps) {onMount(() => {const resetMode = (_e: MouseEvent) => {- setActiveThreadId(null);- setMode(PayloadMode.NoMode);+ comments.clearActiveThread();+ pdf.markup.commands.cancelPlacement();};- const el = pdf.rootElement();+ const el = pdfViewer.rootElement();if (!el) return;el.addEventListener('click', resetMode);onCleanup(() => el.removeEventListener('click', resetMode));@@ -276,15 +273,14 @@ export function PageOverlay(props: IPageOverlayProps) {return textModes.includes(mode) ? 'pointer' : 'text';};- const [selectionStoreValue, setSelectionStore] = stores.selection;+ const annotationSelection = pdf.annotationSelection;const addNewHighlights = useAddNewHighlights();const doEdit = useDoEdit();- const setActiveHighlightId = signals.activeHighlight[1];const currentPageViewport = () => {- const pageNumber = isPopup- ? derived.popupCurrentPageNumber()- : derived.currentPageNumber();+ const pageNumber = (+ isPopup ? pdfViewer.popup : pdfViewer.root+ ).currentPageNumber();const viewer = isPopup ? getPopupViewer() : getRootViewer();return (viewer?.pageViewport(pageNumber - 1) ?? {@@ -295,10 +291,11 @@ export function PageOverlay(props: IPageOverlayProps) {};const addHighlight = () => {- if (!selectionStoreValue.selection) return;+ const nativeSelection = annotationSelection().nativeSelection;+ if (!nativeSelection) return;const highlights = getHighlightsFromSelection(- selectionStoreValue.selection,+ nativeSelection,null,undefined,null,@@ -316,26 +313,27 @@ export function PageOverlay(props: IPageOverlayProps) {batch(() => {setTimeout(doEdit);addNewHighlights(highlightsUnderSelection);- setSelectionStore('highlightsUnderSelection', highlightsUnderSelection);+ pdf.replaceSelectedHighlights(highlightsUnderSelection);const selection = highlightsUnderSelection.at(0);if (!selection) return;- setActiveHighlightId(selection.uuid);+ pdf.activateHighlight(selection.uuid);});};const removeHighlight = useRemoveHighlight();const removeCurrentHighlight = () => {- if (selectionStoreValue.highlightsUnderSelection.length < 1) return;+ const selectedHighlights = annotationSelection().selectedHighlights;+ if (selectedHighlights.length < 1) return;batch(() => {setTimeout(doEdit);- selectionStoreValue.highlightsUnderSelection.forEach((h) =>- removeHighlight(h.uuid)+ selectedHighlights.forEach((highlight) =>+ removeHighlight(highlight.uuid));- setSelectionStore('highlightsUnderSelection', []);+ pdf.replaceSelectedHighlights([]);});};@@ -344,7 +342,7 @@ export function PageOverlay(props: IPageOverlayProps) {useCreateHighlightCommentAtSelection();const commentProps = createMemo(() => {- const currentHighlight = selectionStoreValue.highlightsUnderSelection.at(0);+ const currentHighlight = annotationSelection().selectedHighlights.at(0);const uuid = currentHighlight?.uuid;// Although the user can technically take ownership of a highlight// when making a comment, deleting the highlight-comment will remove the highlight@@ -364,7 +362,7 @@ export function PageOverlay(props: IPageOverlayProps) {});const highlightProps = createMemo(() => {- const currentHighlight = selectionStoreValue.highlightsUnderSelection.at(0);+ const currentHighlight = annotationSelection().selectedHighlights.at(0);const uuid = currentHighlight?.uuid;const canEdit =isDocumentOwner() || (!!uuid && ownedHighlightSelector(uuid));@@ -392,31 +390,26 @@ export function PageOverlay(props: IPageOverlayProps) {},});- const aiProps = {- attachmentId: pdf.documentId(),- };-- const newPlaceable = signals.newPlaceable[0];- const newPlaceableId = () => newPlaceable()?.internalId;- const isNewPlaceableSelector = createSelector(newPlaceableId);- const activePlaceableId = signals.activePlaceableId[0];- const isActivePlaceableSelector = createSelector(activePlaceableId);+ const draft = pdf.markup.draft;+ const draftId = () => draft()?.internalId;+ const isNewPlaceableSelector = createSelector(draftId);+ const activeId = pdf.markup.activeId;+ const isActivePlaceableSelector = createSelector(activeId);const ownedCommentSelector = useOwnedCommentPlaceableSelector();const showPopup = createMemo(() => {const shouldshow =- !isPopup && !derived.popupOpen() && !!signals.generalPopupLocation[0]();- if (!shouldshow) {- signals.popupSelectedText[1](undefined);- signals.popupCompletion[1](undefined);- }+ !isPopup && !pdfViewer.isPopupOpen() && !!pdf.selectionMenuLocation();return shouldshow;});return (<divref={pageOverlayRef}- class={cn('pageOverlayInner', disableOverlayClick() && 'noClickOverlay')}+ class={cn(+ 'pageOverlayInner',+ overlayClicksDisabled() && 'noClickOverlay'+ )}on:click={(e) => {if (mode() !== PayloadMode.NoMode) {createPlaceable(e);@@ -432,15 +425,14 @@ export function PageOverlay(props: IPageOverlayProps) {}}class="bg-transparent top-0 left-0 absolute">- <Show when={showPopup() && signals.generalPopupLocation[0]()}>- {(generalPopupLocation) => (- <Show when={generalPopupLocation().pageIndex === props.pageIndex}>+ <Show when={showPopup() && pdf.selectionMenuLocation()}>+ {(selectionMenuLocation) => (+ <Show when={selectionMenuLocation().pageIndex === props.pageIndex}><PDFPopupcommentProps={commentProps()}highlightProps={highlightProps()}shareLinkProps={shareLinkProps()}- anchorRef={/*@once*/ generalPopupLocation().element}- aiProps={aiProps}+ anchorRef={/*@once*/ selectionMenuLocation().element}/></Show>)}@@ -455,7 +447,9 @@ export function PageOverlay(props: IPageOverlayProps) {}}class="bg-transparent top-0 left-0 absolute">- {terms().length > 0 && <AbsoluteDefinitionLookups terms={terms()} />}+ <Show when={terms().length > 0}>+ <AbsoluteDefinitionLookups terms={terms()} />+ </Show></div><divstyle={{@@ -479,7 +473,7 @@ export function PageOverlay(props: IPageOverlayProps) {class="top-0 left-0 absolute bg-transparent"inert={pdf.isNested()}>- <For each={stores.modificationData[0].placeables}>+ <For each={pdf.model.modificationData.placeables}>{(placeable) => {return (<Show@@ -523,9 +517,6 @@ export function PageOverlay(props: IPageOverlayProps) {</For></div></div>- <Show when={!isPopup}>- <RightMarginLayout pageNumber={props.pageIndex} />- </Show></div>);}@@ -534,17 +525,18 @@ function UserHighlightNodes(props: {pageIndex: number;viewport: PageViewport;}) {- const { signals, stores } = usePdfDocument().state;+ const pdf = usePdfDocument();+ const comments = usePdfComments();const thisPageHighlights = createMemo(() =>- Object.values(stores.highlights[0][props.pageIndex] ?? {}).filter(- (h) => !!h- )+ Object.values(+ pdf.annotations.highlightsByPage[props.pageIndex] ?? {}+ ).filter((h) => !!h));const viewportHeight = createMemo(() => props.viewport.height);const viewportWidth = createMemo(() => props.viewport.width);- const isActiveHighlightSelector = createSelector(signals.activeHighlight[0]);- const isActiveThreadSelector = createSelector(signals.activeCommentThread[0]);+ const isActiveHighlightSelector = createSelector(pdf.activeHighlightId);+ const isActiveThreadSelector = createSelector(comments.activeThreadId);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.tsxindex 34efd93436..ef2311548e 100644--- a/apps/web/src/features/block-pdf/component/PdfDocument.tsx+++ b/apps/web/src/features/block-pdf/component/PdfDocument.tsx@@ -8,32 +8,31 @@ import type { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';import {createEffect,createResource,+ createSignal,type JSX,onCleanup,onMount,Show,} from 'solid-js';-import { reconcile } from 'solid-js/store';import { fromZodError } from 'zod-validation-error';+import { PdfCommentsProvider } from '../context/pdf-comments-context';import {type PdfDocumentPermissions,PdfDocumentProvider,usePdfDocument,} from '../context/pdf-document-context';+import { PdfViewerProvider, usePdfViewer } from '../context/pdf-viewer-context';import {type LocationBlockParams,type LocationSearchParams,- usePendingLocationNavigationEffect,+ useGoToLinkLocation,+ useGoToLinkLocationFromParams,} from '../signal/location';import { usePdfSave } from '../signal/save';import { useUpdateColorsEffect } from '../signal/setting';-import { useSyncHighlightStore } from '../store/highlight';+import { usePdfCommentProjection } from '../store/comments/commentStore';import { useSyncActivePlaceableWithCommentThread } from '../store/placeables';-import { useTableOfContentsUpdate } from '../store/tableOfContents';-import {- IModificationDataOnServerSchema,- transformModificationDataToClient,-} from '../type/coParse';+import { IModificationDataOnServerSchema } from '../type/coParse';import { preprocess } from '../websocket/preprocess';import { Document } from './Document';@@ -64,7 +63,6 @@ export type PdfDocumentProps = {viewLocation?: GetDocumentResponseDataViewLocation;modificationData?: unknown;isNested?: boolean;- hotkeyScope: string;portalScope?: PortalScope;permissions: PdfDocumentPermissions;locationParams?: LocationSearchParams;@@ -78,15 +76,17 @@ export function PdfDocument(props: PdfDocumentProps) {{(documentId) => (<PdfDocumentProviderdocumentId={documentId}+ documentProxy={props.documentProxy}documentVersionId={props.documentVersionId}documentName={props.documentName}isNested={props.isNested}- hotkeyScope={props.hotkeyScope}portalScope={props.portalScope}permissions={props.permissions}locationParams={props.locationParams}>- <PdfDocumentState {...props} />+ <PdfViewerProvider>+ <PdfDocumentBehavior {...props} />+ </PdfViewerProvider></PdfDocumentProvider>)}</Show>@@ -94,40 +94,37 @@ export function PdfDocument(props: PdfDocumentProps) {}export function PdfDocumentContent() {+ useSyncActivePlaceableWithCommentThread();+return (- <div class="flex size-full relative justify-end overflow-visible z-main-view-layout">+ <div class="flex size-full relative justify-end overflow-visible"><Document /></div>);}-function PdfDocumentState(props: PdfDocumentProps) {+function PdfDocumentBehavior(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 pdfViewer = usePdfViewer();+ const comments = usePdfCommentProjection();const savePdf = usePdfSave();+ const [pendingLocationParams, setPendingLocationParams] =+ createSignal<LocationBlockParams>();+ const goToInitialLocation = useGoToLinkLocation();+ const goToLocationFromParams = useGoToLinkLocationFromParams();+ let imperativeNavigationQueued = false;props.registerMethods?.({goToLocationFromParams: async (params) => {- locationChanged[1](true);- pendingLocationParams[1](JSON.parse(JSON.stringify(params)));+ imperativeNavigationQueued = true;+ setPendingLocationParams({ ...params });},});createEffect(() => {- documentProxy[1](props.documentProxy);- viewLocation[1](pdf.isNested() ? undefined : props.viewLocation);+ pdf.setPersistedViewLocation(+ pdf.isNested() ? undefined : props.viewLocation+ );const modificationData = props.modificationData;if (!modificationData) return;@@ -140,10 +137,26 @@ function PdfDocumentState(props: PdfDocumentProps) {return;}- serverModificationData[1](parsed.data);- setModificationData(- reconcile(transformModificationDataToClient(parsed.data))- );+ pdf.model.commands.hydrateFromServer(parsed.data);+ });++ createEffect(() => {+ if (imperativeNavigationQueued || !pdfViewer.root.isReady()) return;+ void goToInitialLocation(pdf.locationParams());+ });++ createEffect(() => {+ const params = pendingLocationParams();+ if (+ !params ||+ !pdfViewer.root.isReady() ||+ !pdfViewer.root.hasVisiblePages()+ ) {+ return;+ }+ setPendingLocationParams(undefined);+ pdfViewer.root.instance()?.clearAllOverlays();+ void goToLocationFromParams(params);});const [preprocessResource] = createResource(() => {@@ -160,9 +173,9 @@ function PdfDocumentState(props: PdfDocumentProps) {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);+ pdf.definitions.commands.loadTermXml(coparse.defs ?? '');+ pdf.outline.commands.loadCoparse(coparse);+ pdfViewer.replaceOverlays(coparse.overlays);});const debouncedSave = leading(@@ -182,7 +195,7 @@ function PdfDocumentState(props: PdfDocumentProps) {onMount(() => {if (pdf.isNested()) return;const handleBeforeUnload = (event: Event) => {- if (isSaving[0]()) event.preventDefault();+ if (pdf.persistence.isSaving()) event.preventDefault();};window.addEventListener('keydown', preventNativePdfShortcuts);window.addEventListener('beforeunload', handleBeforeUnload);@@ -193,13 +206,15 @@ function PdfDocumentState(props: PdfDocumentProps) {});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>+ <PdfCommentsProvider comments={comments}>+ <div+ ref={pdfViewer.setRootElement}+ class="size-full select-none overscroll-none overflow-hidden flex flex-col"+ onContextMenu={(event) => event.preventDefault()}+ data-tut="App"+ >+ {props.children}+ </div>+ </PdfCommentsProvider>);}diff --git a/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsx b/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsxindex 6f4a80a501..b81994ce87 100644--- a/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsx+++ b/apps/web/src/features/block-pdf/component/PdfSplitToolbar.tsx@@ -13,17 +13,14 @@ import { PageNumberInput } from './PageNumberInput';export function PdfTabsToggle() {const pdf = usePdfDocument();const canEdit = pdf.permissions.canEdit;- const [showTabBar, setShowTabBar] = pdf.state.signals.showTabBar;return (<Show when={canEdit()}><Buttonsize="icon-sm"- label={showTabBar() ? 'Hide Tabs' : 'Show Tabs'}+ label={pdf.tabs.isVisible() ? 'Hide Tabs' : 'Show Tabs'}variant="ghost"- onClick={() => {- setShowTabBar(!showTabBar());- }}+ onClick={pdf.tabs.commands.toggleVisibility}><Tabs /></Button>@@ -44,7 +41,7 @@ export function PdfToolbarControls() {}export function PdfSplitToolbar() {- const [documentProxy] = usePdfDocument().state.signals.documentProxy;+ const documentProxy = usePdfDocument().documentProxy;return (<Show when={documentProxy()}><SplitToolbarLeft>diff --git a/apps/web/src/features/block-pdf/component/Placeable.tsx b/apps/web/src/features/block-pdf/component/Placeable.tsxindex 2b00f6a306..748bb1690b 100644--- a/apps/web/src/features/block-pdf/component/Placeable.tsx+++ b/apps/web/src/features/block-pdf/component/Placeable.tsx@@ -19,7 +19,9 @@ import {Switch,untrack,} from 'solid-js';+import { usePdfComments } from '../context/pdf-comments-context';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import {FreeCommentPlaceable,NewFreeCommentPlaceable,@@ -36,10 +38,11 @@ export const Placeable: Component<{canEdit: boolean;}> = (props) => {const pdf = usePdfDocument();+ const comments = usePdfComments();+ const pdfViewer = usePdfViewer();const isPopup = useIsPopup();- const { signals, derived } = pdf.state;- const getViewer = () =>- isPopup ? signals.popupViewer[0]() : signals.rootViewer[0]();+ const viewer = isPopup ? pdfViewer.popup : pdfViewer.root;+ const getViewer = viewer.instance;const [textAreaRef, setTextAreaRef] = createSignal<HTMLTextAreaElement>();let placeableRef!: HTMLDivElement;@@ -48,11 +51,7 @@ export const Placeable: Component<{const parentId = () => props.pageNum + 1;- const visiblePages = () =>- (isPopup- ? signals.visiblePagesChangedPopup[0]()- : signals.visiblePagesChanged[0]()- )?.visiblePages;+ const visiblePages = () => viewer.viewArea()?.visiblePages;const visiblePageNumbers = createMemo((prev: Set<number>) => {const visiblePageIds = visiblePages()?.ids ?? new Set();const equals = setEquals(prev, visiblePageIds);@@ -61,10 +60,7 @@ export const Placeable: Component<{}, new Set());const updatePlaceablePosition = useUpdatePlaceablePosition();- const setActivePlaceableId = signals.activePlaceableId[1];- const setActiveCommentThreadId = signals.activeCommentThread[1];-- const [isPopupDrag, setIsPopupDrag] = signals.isPopupDrag;+ const popupDragActive = pdf.markup.dragActive;const [mousePosition, setMousePosition] = createSignal({ x: 0, y: 0 });const [dragOffset, setDragOffset] = createSignal({ x: 0, y: 0 });@@ -75,7 +71,7 @@ export const Placeable: Component<{clearTimeout(mouseDownTimeout);};const setMouseDown = (e: MouseEvent) => {- setActivePlaceableId(props.id);+ pdf.markup.commands.activate(props.id);setIsResizing(undefined);setClickOffset({x: e.clientX - xCoord(),@@ -157,7 +153,6 @@ export const Placeable: Component<{});});- // this lets us change the bounding rects on scroll/zoomcreateEffect(() => {if (!visiblePages()) return;setPdfPageRects({});@@ -197,11 +192,10 @@ export const Placeable: Component<{if (!props.canEdit) return;if (!mouseDown()) return;if (isResizing()) return;- setActivePlaceableId(props.id);+ pdf.markup.commands.activate(props.id);let pdfPageX = e.clientX;let pdfPageY = e.clientY;- // prevent the placeable from being dragged outside the viewer boundsif (!placeableIntersectsViewer()) {const viewerRect = viewerEl.getBoundingClientRect();@@ -240,7 +234,6 @@ export const Placeable: Component<{};const onMouseMove = (e: MouseEvent) => {- // bypass the create effect and call the drag handler directlyif (textAreaRef() === undefined) {onMouseMoveDrag(e);return;@@ -268,7 +261,7 @@ export const Placeable: Component<{const { x, y } = dragOffset();const hasPressed = mouseDown();const hasMoved = x !== 0 || y !== 0;- setIsPopupDrag(hasPressed || hasMoved);+ pdf.markup.commands.setDragActive(hasPressed || hasMoved);});onMount(() => {@@ -279,18 +272,15 @@ export const Placeable: Component<{const isDragged =mouseDown() && !(dragOffset().x === 0 && dragOffset().y === 0);const otherPlaceableDragged =- (!isPopup && isPopupDrag()) || (isPopup && !isPopupDrag());+ (!isPopup && popupDragActive()) || (isPopup && !popupDragActive());if (!isDragged && otherPlaceableDragged) return;- // outside clickif (!isDragged) {- setActivePlaceableId(undefined);+ pdf.markup.commands.clearActive();return;}- // prevents the comment click outside handler from triggering after- // the effect handler resets the blocking on drag position resete.stopImmediatePropagation();resetPlaceablePosition();@@ -326,8 +316,7 @@ export const Placeable: Component<{});});- const currentScale = () =>- (isPopup ? derived.popupCurrentScale() : derived.currentScale()) ?? 1;+ const currentScale = () => viewer.currentScale() ?? 1;const scale = createMemo(() =>getViewer()?.getScale({ pageNumber: 1 })?.scale ??@@ -392,7 +381,7 @@ export const Placeable: Component<{if (!props.canEdit) return;if (!isThreadPlaceable(props.placeable)) {- setActiveCommentThreadId(null);+ comments.clearActiveThread();}setMouseDown(e);}}@@ -406,7 +395,6 @@ export const Placeable: Component<{xPct = (xCoord() + dragOffset().x) / scaledPageWidth();yPct = (yCoord() + dragOffset().y) / scaledPageHeight();} else {- // we need to update to the new page coordinate systemconst pageRect = pdfPageRects()[intersectingPage()];const { x, y } = mousePosition();xPct = (x - pageRect.left - width() / 2) / pageRect.width;diff --git a/apps/web/src/features/block-pdf/component/RightMarginLayout.test.tsx b/apps/web/src/features/block-pdf/component/RightMarginLayout.test.tsxnew file mode 100644index 0000000000..b878ef97a6--- /dev/null+++ b/apps/web/src/features/block-pdf/component/RightMarginLayout.test.tsx@@ -0,0 +1,140 @@+import { createPdfDraftThreadId } from '@block-pdf/type/comments';+import type { ThreadId } from '@core/comments/commentType';+import { render, screen } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { beforeEach, expect, it, vi } from 'vitest';+import { RightMarginLayout } from './RightMarginLayout';++const state = vi.hoisted(() => ({+ mounts: 0,+ unmounts: 0,+ threads: (() => []) as () => Array<{+ threadId: ThreadId;+ layout: { calculatedYPos: number };+ }>,+}));++vi.mock('@block-pdf/store/comments/commentLayout', () => ({+ usePageCommentLayout: () => ({+ threads: state.threads,+ setThreadHeight: vi.fn(),+ }),+}));++vi.mock('@block-pdf/store/comments/commentOperations', () => ({+ useCreateComment: () => vi.fn(),+ useDeleteComment: () => vi.fn(),+ useUpdateComment: () => vi.fn(),+}));++vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'user-id',+}));++vi.mock('../context/pdf-comments-context', () => ({+ usePdfComments: () => ({+ activeThreadId: () => null,+ selectedThreadId: () => null,+ byId: () => new Map(),+ activateThread: vi.fn(),+ clearActiveThread: vi.fn(),+ selectThread: vi.fn(),+ }),+}));++vi.mock('../context/pdf-document-context', () => ({+ usePdfDocument: () => ({+ documentId: () => 'document-id',+ isNested: () => false,+ permissions: {+ canComment: () => true,+ isOwner: () => true,+ },+ }),+}));++vi.mock('@core/comments/Thread', async () => {+ const { createContext, createEffect, onCleanup, onMount } = await import(+ 'solid-js'+ );++ return {+ baseCommentTheme: { text: { base: '' } },+ CommentsContext: createContext(),+ Thread: (props: {+ comment: { threadId: ThreadId };+ layout: { calculatedYPos: number };+ }) => {+ const element = document.createElement('div');+ element.dataset.testid = 'thread';++ createEffect(() => {+ element.textContent = `${props.comment.threadId}:${props.layout.calculatedYPos}`;+ });+ onMount(() => {+ state.mounts += 1;+ });+ onCleanup(() => {+ state.unmounts += 1;+ });++ return element;+ },+ };+});++beforeEach(() => {+ state.mounts = 0;+ state.unmounts = 0;+});++it('preserves a thread component when its measured layout changes', async () => {+ const [threads, setThreads] = createSignal([+ {+ threadId: 1,+ layout: { calculatedYPos: 10 },+ },+ ]);+ state.threads = threads;++ render(() => <RightMarginLayout pageIndex={0} />);+ expect(screen.getByTestId('thread').textContent).toBe('1:10');+ expect(state.mounts).toBe(1);++ setThreads([+ {+ threadId: 1,+ layout: { calculatedYPos: 20 },+ },+ ]);++ expect(screen.getByTestId('thread').textContent).toBe('1:20');+ expect(state.mounts).toBe(1);+ expect(state.unmounts).toBe(0);+});++it('renders drafts with distinct client thread identities', () => {+ const highlightDraftId = createPdfDraftThreadId(+ 'highlight',+ 'highlight-anchor'+ );+ const freeDraftId = createPdfDraftThreadId('free', 'free-anchor');+ const [threads] = createSignal([+ {+ threadId: highlightDraftId,+ layout: { calculatedYPos: 10 },+ },+ {+ threadId: freeDraftId,+ layout: { calculatedYPos: 20 },+ },+ ]);+ state.threads = threads;++ render(() => <RightMarginLayout pageIndex={0} />);++ expect(+ screen.getAllByTestId('thread').map((thread) => thread.textContent)+ ).toEqual([`${highlightDraftId}:10`, `${freeDraftId}:20`]);+ expect(state.mounts).toBe(2);+});diff --git a/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx b/apps/web/src/features/block-pdf/component/RightMarginLayout.tsxindex 50be67ceef..e749055576 100644--- a/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx+++ b/apps/web/src/features/block-pdf/component/RightMarginLayout.tsx@@ -1,7 +1,9 @@import {GUTTER_MARGIN,MIN_RIGHT_COLUMN_WIDTH,+ THREAD_WIDTH,} from '@block-pdf/signal/viewerThreeColumnLayout';+import { usePageCommentLayout } from '@block-pdf/store/comments/commentLayout';import {useCreateComment,useDeleteComment,@@ -15,43 +17,41 @@ import {Thread,} from '@core/comments/Thread';import { useUserId } from '@core/context/user';-import { createMemo, createSelector, For } from 'solid-js';+import { Key } from '@solid-primitives/keyed';+import { createSelector } from 'solid-js';+import { usePdfComments } from '../context/pdf-comments-context';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 {};- const baseStyles = {- minWidth: MIN_RIGHT_COLUMN_WIDTH + 'px',- width: rightWidth - GUTTER_MARGIN * 2 + 'px',- };-- const right =- rightWidth <= MIN_RIGHT_COLUMN_WIDTH ? -marginWidth : -rightWidth;- return {- right: right + GUTTER_MARGIN + 'px',- ...baseStyles,- };- });+const rightMarginStyle = {+ minWidth: `${MIN_RIGHT_COLUMN_WIDTH}px`,+ width: `${THREAD_WIDTH - GUTTER_MARGIN * 2}px`,+ right: `${-THREAD_WIDTH + GUTTER_MARGIN}px`,+};+export function RightMarginLayout(props: { pageIndex: number }) {return (<div- class="rightMargin absolute [transition: width 0.05s linear, right 0.05s linear]"- style={styles()}+ class="rightMargin absolute top-0 z-pdf-comments pointer-events-auto [transition: width 0.05s linear, right 0.05s linear]"+ style={rightMarginStyle}>- <CommentsAndSuggestions pageNumber={props.pageNumber} />+ <CommentsAndSuggestions pageIndex={props.pageIndex} /></div>);}-const useCommentsContext = (): CommentsContextType => {+const useCommentsContext = (+ setThreadHeight: CommentsContextType['setThreadHeight']+): CommentsContextType => {const pdf = usePdfDocument();- const { signals, stores, derived } = pdf.state;- const setActiveThread = signals.activeCommentThread[1];- const setThreadHeight = stores.threadHeight[1];+ const comments = usePdfComments();+ const commentsById = comments.byId;+ const setActiveThread = (threadId: ThreadId | null) => {+ if (threadId == null) {+ comments.clearActiveThread();+ } else {+ comments.activateThread(threadId);+ }+ };const createComment = useCreateComment();const updateComment = useUpdateComment();@@ -61,11 +61,10 @@ const useCommentsContext = (): CommentsContextType => {const ownedComment = (id: CommentId) => {const currentUserId = userId();return (- currentUserId != null &&- derived.commentMap()?.get(id)?.owner === currentUserId+ currentUserId != null && commentsById().get(id)?.owner === currentUserId);};- const getCommentById = (id: CommentId) => derived.commentMap()?.get(id);+ const getCommentById = (id: CommentId) => commentsById().get(id);const commentsContext: CommentsContextType = {setActiveThread,@@ -87,18 +86,15 @@ const useCommentsContext = (): CommentsContextType => {return commentsContext;};-function CommentsAndSuggestions(props: { pageNumber: number }) {- const { signals, stores } = usePdfDocument().state;- const threadsOnPage = createMemo(- () => stores.threadsOnPagePosition[0][props.pageNumber] ?? []+function CommentsAndSuggestions(props: { pageIndex: number }) {+ const comments = usePdfComments();+ const { threads, setThreadHeight } = usePageCommentLayout(+ () => props.pageIndex);- const [activeCommentThread, setActiveThreadId] = signals.activeCommentThread;- const isActiveThreadSelector = createSelector(activeCommentThread);+ const isActiveThreadSelector = createSelector(comments.activeThreadId);- const [selectedThreadId, setSelectedThreadId] =- signals.selectingCommentThread;- const isSelectingThreadSelector = createSelector(selectedThreadId);+ const isSelectingThreadSelector = createSelector(comments.selectedThreadId);const commentTheme = (threadId: ThreadId | null) => {const isSelecting = isSelectingThreadSelector(threadId);@@ -114,31 +110,31 @@ function CommentsAndSuggestions(props: { pageNumber: number }) {const handleThreadMouseDown = (threadId: ThreadId) => (e: MouseEvent) => {e.stopPropagation();- setSelectedThreadId(threadId);+ comments.selectThread(threadId);const handleMouseUp = (e: MouseEvent) => {e.stopPropagation();- setActiveThreadId(threadId);+ comments.activateThread(threadId);document.removeEventListener('mouseup', handleMouseUp, true);};document.addEventListener('mouseup', handleMouseUp, true);};- const commentsContext = useCommentsContext();+ const commentsContext = useCommentsContext(setThreadHeight);return (<CommentsContext.Provider value={commentsContext}>- <For each={threadsOnPage()}>+ <Key each={threads()} by="threadId">{(root) => (<Thread- comment={root}- layout={root.layout}- isActive={isActiveThreadSelector(root.threadId)}- theme={commentTheme(root.threadId)}- handleMouseDown={handleThreadMouseDown(root.threadId)}+ comment={root()}+ layout={root().layout}+ isActive={isActiveThreadSelector(root().threadId)}+ theme={commentTheme(root().threadId)}+ handleMouseDown={handleThreadMouseDown(root().threadId)}/>)}- </For>+ </Key></CommentsContext.Provider>);}diff --git a/apps/web/src/features/block-pdf/component/SimpleSearch.test.tsx b/apps/web/src/features/block-pdf/component/SimpleSearch.test.tsxnew file mode 100644index 0000000000..2540c9d56d--- /dev/null+++ b/apps/web/src/features/block-pdf/component/SimpleSearch.test.tsx@@ -0,0 +1,111 @@+import type { FindBarController } from '@core/component/createFindBarController';+import {+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from '@solidjs/testing-library';+import { createSignal, Show } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { PdfViewerProvider, usePdfViewer } from '../context/pdf-viewer-context';+import { SimpleSearch } from './SimpleSearch';++const search = vi.hoisted(() => ({+ close: vi.fn(),+ jumpToResult: vi.fn(),+ start: vi.fn(),+}));++vi.mock('../signal/search', () => ({+ useJumpToResult: () => search.jumpToResult,+ useSearchClose: () => search.close,+ useSearchResults: () => () => null,+ useSearchStart: () => search.start,+}));++vi.mock('@core/component/FindBar', () => ({+ FindBar: (props: { controller: FindBarController }) => (+ <>+ <input+ placeholder="Find"+ value={props.controller.query()}+ onInput={(event) =>+ props.controller.setQuery(event.currentTarget.value)+ }+ />+ <button+ aria-label="Close find bar"+ onClick={() => props.controller.close()}+ />+ </>+ ),+}));++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++function SearchOwner(props: { documentId: string }) {+ const pdfViewer = usePdfViewer();+ return (+ <div+ data-testid="search-root"+ data-document-id={props.documentId}+ ref={pdfViewer.setRootElement}+ >+ <SimpleSearch />+ </div>+ );+}++describe('SimpleSearch', () => {+ it('keeps search state local to its keyed viewer owner', async () => {+ const [documentId, setDocumentId] = createSignal('document-1');++ render(() => (+ <Show when={documentId()} keyed>+ {(id) => (+ <PdfViewerProvider>+ <SearchOwner documentId={id} />+ </PdfViewerProvider>+ )}+ </Show>+ ));++ const firstRoot = screen.getByTestId('search-root');+ fireEvent.keyDown(firstRoot, {+ key: 'f',+ ctrlKey: true,+ metaKey: true,+ });+ const input = await screen.findByPlaceholderText('Find');+ fireEvent.input(input, { target: { value: 'retained query' } });++ fireEvent.click(screen.getByRole('button', { name: 'Close find bar' }));+ expect(screen.queryByPlaceholderText('Find')).toBeNull();++ fireEvent.keyDown(screen.getByTestId('search-root'), {+ key: 'f',+ ctrlKey: true,+ metaKey: true,+ });+ expect(+ ((await screen.findByPlaceholderText('Find')) as HTMLInputElement).value+ ).toBe('retained query');++ setDocumentId('document-2');+ await waitFor(() =>+ expect(screen.getByTestId('search-root')).not.toBe(firstRoot)+ );+ fireEvent.keyDown(screen.getByTestId('search-root'), {+ key: 'f',+ ctrlKey: true,+ metaKey: true,+ });+ expect(+ ((await screen.findByPlaceholderText('Find')) as HTMLInputElement).value+ ).toBe('');+ });+});diff --git a/apps/web/src/features/block-pdf/component/SimpleSearch.tsx b/apps/web/src/features/block-pdf/component/SimpleSearch.tsxindex a43c7ca9bf..2ba502894c 100644--- a/apps/web/src/features/block-pdf/component/SimpleSearch.tsx+++ b/apps/web/src/features/block-pdf/component/SimpleSearch.tsx@@ -2,7 +2,7 @@ import type { FindBarController } from '@core/component/createFindBarController'import { FindBar } from '@core/component/FindBar';import { IS_MAC } from '@core/constant/isMac';import { createEffect, createSignal, onCleanup, Show, untrack } from 'solid-js';-import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import {useJumpToResult,useSearchClose,@@ -11,19 +11,18 @@ import {} from '../signal/search';export function SimpleSearch() {- const pdf = usePdfDocument();+ const pdfViewer = usePdfViewer();+ const rootElement = pdfViewer.rootElement;const searchStart = useSearchStart();const searchResults = useSearchResults();const jumpToResult = useJumpToResult();const closeSearchBar = useSearchClose();- const [locationPending] = pdf.state.signals.searchLocationPending;+ const locationPending = pdfViewer.searchNavigationPending;const [inputEl, setInputEl] = createSignal<HTMLInputElement>();-- const [isOpen, setIsOpen] = pdf.state.signals.isSearchOpen;- const [searchText, setSearchText] = pdf.state.signals.search;+ const [isOpen, setIsOpen] = createSignal(false);+ const [searchText, setSearchText] = createSignal('');const [isPending, setIsPending] = createSignal(false);- // Re-run the active search when the bar opens (or re-opens with prior text).createEffect(() => {if (untrack(locationPending)) return;const text = untrack(searchText);@@ -74,8 +73,6 @@ export function SimpleSearch() {setIsOpen(false);};- // PDF.js owns the search state (queries, results, cursor). Expose it as a- // FindBarController so it can drive the shared <FindBar> UI.const controller: FindBarController = {isOpen,query: searchText,@@ -114,7 +111,7 @@ export function SimpleSearch() {};createEffect(() => {- const element = pdf.rootElement();+ const element = rootElement();if (!element) return;element.addEventListener('keydown', handleHotkey);onCleanup(() => {diff --git a/apps/web/src/features/block-pdf/component/Tabs.tsx b/apps/web/src/features/block-pdf/component/Tabs.tsxindex 99796c6753..2ac6681667 100644--- a/apps/web/src/features/block-pdf/component/Tabs.tsx+++ b/apps/web/src/features/block-pdf/component/Tabs.tsx@@ -9,11 +9,10 @@ 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';+import { usePdfViewer } from '../context/pdf-viewer-context';interface IInternalTabProps {label: string;- location: string;- index: number;id: number;tabCount: number;clickHandler: () => void;@@ -21,13 +20,11 @@ interface IInternalTabProps {}function Tab(props: IInternalTabProps) {- const [activeTabId] = usePdfDocument().state.signals.activeTabId;+ const activeTabId = usePdfDocument().tabs.activeId;const currentPageNumber = useCurrentPageNumber();const active = () => props.id === activeTabId();- // TODO (seamus) Tab label should be able to pull information from pdf- // section data.const label = () => (active() ? `Page ${currentPageNumber()}` : props.label);return (@@ -54,8 +51,8 @@ function Tab(props: IInternalTabProps) {export function Tabs() {const pdf = usePdfDocument();- const [tabs] = pdf.state.stores.tabData;- const [viewerHasVisiblePages] = pdf.state.signals.viewerHasVisiblePages;+ const tabs = pdf.tabs.items;+ const viewerHasVisiblePages = usePdfViewer().root.hasVisiblePages;const createTab = useCreateTab();const deleteTab = useDeleteTab();const navigate = useNavigateToTab();@@ -63,19 +60,17 @@ export function Tabs() {<Show when={viewerHasVisiblePages()}><div class="w-full h-7 rounded-full flex px-1.5 shrink items-center"><For each={tabs}>- {(tab, index) => (+ {(tab) => (<Tablabel={tab.label}- location={tab.locationHash || ''}- index={index()}id={tab.id}- tabCount={tabs.length}+ tabCount={pdf.tabs.count()}clickHandler={() => navigate(tab.id)}deleteTab={() => deleteTab(tab.id)}/>)}</For>- <Show when={tabs.length < MAX_TAB_COUNT}>+ <Show when={pdf.tabs.count() < MAX_TAB_COUNT}><buttononClick={() => createTab()}class="shrink-0 p-2 aspect-square rounded-lg flex items-center justify-center hover:bg-hover hover-transition-bg"diff --git a/apps/web/src/features/block-pdf/component/TopBar.tsx b/apps/web/src/features/block-pdf/component/TopBar.tsxindex 47caad1085..b449a695aa 100644--- a/apps/web/src/features/block-pdf/component/TopBar.tsx+++ b/apps/web/src/features/block-pdf/component/TopBar.tsx@@ -46,7 +46,7 @@ import { PdfSplitToolbar } from './PdfSplitToolbar';export function TopBar() {const pdf = usePdfDocument();- const [documentProxy] = pdf.state.signals.documentProxy;+ const documentProxy = pdf.documentProxy;const isAuth = useIsAuthenticated();const documentId = useBlockId();const blockName = useBlockName();diff --git a/apps/web/src/features/block-pdf/component/UserHighlight.tsx b/apps/web/src/features/block-pdf/component/UserHighlight.tsxindex 648d7f50a0..a160c2f0da 100644--- a/apps/web/src/features/block-pdf/component/UserHighlight.tsx+++ b/apps/web/src/features/block-pdf/component/UserHighlight.tsx@@ -1,126 +1,70 @@import { createCallback } from '@solid-primitives/rootless';import { cn } from '@ui';import {+ batch,createMemo,type JSX,onCleanup,onMount,type VoidProps,} from 'solid-js';+import { usePdfComments } from '../context/pdf-comments-context';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import { Color, type IColor } from '../model/Color';import type { IHighlight } from '../model/Highlight';+import { usePopupContextUpdate } from '../signal/definitionPopup';import { useIsPopup } from '../signal/pdfViewer';-import { usePopupContextUpdate } from '../store/definitionPopup';import type { IHighlightObj } from './PageOverlay';-// TODO: only check for highlight IDs within the block DOM subtreeexport const highlightIdSelector = (highlightId: string) =>`[data-highlight-id="${highlightId}"]`;export const useResetUserHighlights = () => {- const { activeCommentThread, activeHighlight, hoverHighlight } =- usePdfDocument().state.signals;- const setActiveThread = activeCommentThread[1];- const setHoverHighlight = hoverHighlight[1];- const setActiveHighlight = activeHighlight[1];+ const pdf = usePdfDocument();+ const comments = usePdfComments();return createCallback(() => {- setActiveThread(null);- setActiveHighlight(null);- setHoverHighlight(null);+ batch(() => {+ comments.clearActiveThread();+ pdf.clearActiveHighlight();+ pdf.clearHoveredHighlight();+ });});};const isHighlightComment = (highlight: IHighlight) =>highlight.thread != null || highlight.hasTempThread;-// export const useGoToHighlight = () => {-// const getRootViewer = useGetRootViewer();-// const selectHighlight = useHighlightSelection();-// const getHighlightByUuid = useGetHighlightByUuid();-//-// return async (highlightId: string) => {-// const viewer = getRootViewer();-// if (!viewer) return;-//-// let highlightElement: HTMLElement | null = document.querySelector(-// highlightIdSelector(highlightId)-// );-//-// if (!highlightElement) {-// const highlight = getHighlightByUuid(highlightId);-// if (!highlight) return;-// const pageIndex = highlight.pageNum + 1;-// viewer.scrollTo({-// pageNumber: pageIndex,-// yPos: highlight.rects[0].top,-// });-// }-//-// // this lets us wait for the highlight to be added to the DOM before selecting it-// return new Promise<void>((resolve) => {-// const observer = new IntersectionObserver((_entries) => {-// observer.disconnect();-// // select highlight should jump to the highlight as long as the elemnent is in the DOM-// selectHighlight(highlightId);-// resolve();-// });-//-// const mutationObserver = new MutationObserver(() => {-// highlightElement = document.querySelector(-// highlightIdSelector(highlightId)-// );-// if (highlightElement) {-// mutationObserver.disconnect();-// observer.observe(highlightElement);-// }-// });-//-// mutationObserver.observe(document.body, {-// childList: true,-// subtree: true,-// });-//-// // If the element is already in the DOM, start observing it immediately-// if (highlightElement) {-// observer.observe(highlightElement);-// }-// });-// };-// };-// TODO: handle highlight selection in a different documentexport const useHighlightSelection = () => {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];+ const comments = usePdfComments();+ const rootElement = usePdfViewer().rootElement;return (highlightId: string, element?: HTMLElement) => {- const highlight = derived.highlightsUuidMap()?.[highlightId];+ const highlight = pdf.annotations.highlightsByUuid()[highlightId];if (!highlight) return;- // handle comments and regular highlights differentlyif (isHighlightComment(highlight)) {- setActiveThread(highlight.thread?.threadId ?? null);+ const threadId = highlight.thread?.threadId;+ if (threadId == null) {+ comments.clearActiveThread();+ } else {+ comments.activateThread(threadId);+ }} else {- setActiveHighlight(highlightId);- setActiveThread(null);+ pdf.activateHighlight(highlightId);+ comments.clearActiveThread();}- // Find the highlight element in the DOMconst highlightElement =element ??- .rootElement()- ?.querySelector<HTMLElement>(highlightIdSelector(highlightId));+ rootElement()?.querySelector<HTMLElement>(+ highlightIdSelector(highlightId)+ );if (!highlightElement) return;- // Check if the highlight is in the viewportconst rect = highlightElement.getBoundingClientRect();const isInViewport =rect.top >= 0 &&@@ -129,21 +73,19 @@ export const useHighlightSelection = () => {(window.innerHeight || document.documentElement.clientHeight) &&rect.right <= (window.innerWidth || document.documentElement.clientWidth);- // show menu for regular highlight onlyif (!isHighlightComment(highlight)) {- setSelectionStore('highlightsUnderSelection', [highlight]);- setGeneralPopupLocation({+ pdf.replaceSelectedHighlights([highlight]);+ pdf.openSelectionMenu({pageIndex: highlight.pageNum,element: highlightElement,});- setLocationStore('annotation', {+ pdf.setShareLocation({type: 'annotation',pageIndex: highlight.pageNum,id: highlight.uuid,});}- // If not in viewport, scroll to the highlightif (!isInViewport) {setTimeout(() =>@@ -157,19 +99,15 @@ export const useHighlightSelection = () => {};};-/** User Highlight object which stores both regular highlights and comments.- * Note that comments have a thread id associated with them. */export function UserHighlight(props: VoidProps<IHighlightObj>) {let highlightRef!: HTMLDivElement;let textRef!: HTMLDivElement;- const { signals } = usePdfDocument().state;+ const pdf = usePdfDocument();+ const comments = usePdfComments();const isPopup = useIsPopup();const popupDispatchCtx = usePopupContextUpdate(isPopup);const highlightSelection = useHighlightSelection();- const setActiveThread = signals.activeCommentThread[1];- const [hoverHighlight, setHoverHighlight] = signals.hoverHighlight;- const setActiveHighlight = signals.activeHighlight[1];onMount(() => {const handleSelectStart = (e: MouseEvent) => {@@ -207,7 +145,7 @@ export function UserHighlight(props: VoidProps<IHighlightObj>) {};const isHover = createMemo(- () => hoverHighlight() === (props.threadId || props.highlightId)+ () => pdf.hoveredHighlightId() === (props.threadId || props.highlightId));const alphaColor = createMemo((): IColor => {@@ -225,31 +163,32 @@ export function UserHighlight(props: VoidProps<IHighlightObj>) {};});- 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 resettinge.stopPropagation();e.stopImmediatePropagation();popupDispatchCtx({type: 'REMOVE_POPUPS',});- setGeneralPopupLocation(null);+ pdf.closeSelectionMenu();if (props.threadId) {- setNoScroll(true);- setActiveThread(props.isActive ? null : props.threadId);- setTimeout(() => setNoScroll(false), 10);+ comments.suppressScrolling();+ if (props.isActive) {+ comments.clearActiveThread();+ } else {+ comments.activateThread(props.threadId);+ }+ setTimeout(() => comments.restoreScrolling(), 10);} else {- setActiveThread(null);+ comments.clearActiveThread();highlightSelection(props.highlightId,e.target instanceof HTMLElement ? e.target : undefined);}- setActiveHighlight(props.highlightId);+ pdf.activateHighlight(props.highlightId);});return (@@ -276,8 +215,8 @@ export function UserHighlight(props: VoidProps<IHighlightObj>) {props.isActive && props.threadId ? '2px solid #FACC15' : undefined,}}on:click={clickHandler}- onMouseOver={() => setHoverHighlight(props.highlightId)}- onMouseOut={() => setHoverHighlight(null)}+ onMouseOver={() => pdf.hoverHighlight(props.highlightId)}+ onMouseOut={() => pdf.clearHoveredHighlight()}><divref={textRef}diff --git a/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx b/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsxindex 405d7771e4..cd229c141f 100644--- a/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx+++ b/apps/web/src/features/block-pdf/component/placeables/FreeCommentPlaceable.tsx@@ -1,21 +1,20 @@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';+import { type Component, Show } from 'solid-js';+import { usePdfComments } from '../../context/pdf-comments-context';export const FreeCommentPlaceable: Component<{payload: NonNullable<IThreadPlaceable['payload']>;}> = (props) => {const isActiveThreadSelector = useIsActiveThreadSelector();- const [, setActiveThreadId] =- usePdfDocument().state.signals.activeCommentThread;+ const comments = usePdfComments();return (<CommentIndicatorthreadId={props.payload.threadId}isActive={isActiveThreadSelector(props.payload.threadId)}- setActive={() => setActiveThreadId(props.payload.threadId)}+ setActive={() => comments.activateThread(props.payload.threadId)}numComments={props.payload.comments.length}/>);@@ -31,10 +30,8 @@ function CommentIndicator(props: {isActive: boolean;setActive?: () => void;}) {- const [, setNoScrollToActiveCommentThread] =- usePdfDocument().state.signals.noScrollToActiveCommentThread;+ const comments = usePdfComments();- // SCUFFED, decide how to define this colorreturn (<divclass={cn(@@ -44,18 +41,18 @@ function CommentIndicator(props: {: 'bg-[oklch(0.93_0.034_272.788)] text-[oklch(0.585_0.233_277.117)] hover:bg-[oklch(0.87_0.065_274.039)] hover:text-[oklch(0.511_0.262_276.966)]')}on:mousedown={() => {- setNoScrollToActiveCommentThread(true);+ comments.suppressScrolling();props.setActive?.();}}on:mouseup={() => {- setNoScrollToActiveCommentThread(false);+ comments.restoreScrolling();}}>- {props.numComments > 1 && !props.isActive && (+ <Show when={props.numComments > 1 && !props.isActive}><div class="size-2.5 absolute top-[-3.5px] right-[-3.5px] bg-[oklch(0.785_0.115_274.713)] text-[oklch(0.457_0.24_277.023)] flex items-center justify-center rounded-full text-[6px]">{props.numComments}</div>- )}+ </Show><svgxmlns="http://www.w3.org/2000/svg"fill="none"diff --git a/apps/web/src/features/block-pdf/component/placeables/Signature.tsx b/apps/web/src/features/block-pdf/component/placeables/Signature.tsxindex a4ba1cadf4..9ee0a2c21f 100644--- a/apps/web/src/features/block-pdf/component/placeables/Signature.tsx+++ b/apps/web/src/features/block-pdf/component/placeables/Signature.tsx@@ -15,6 +15,7 @@ import {} from 'solid-js';import { themeReactive } from '../../../theme/signals/themeReactive';import { usePdfDocument } from '../../context/pdf-document-context';+import { usePdfViewer } from '../../context/pdf-viewer-context';import { useDeletePlaceable, useModifyPayload } from '../../store/placeables';import { type AllowableEdits, PayloadMode } from '../../type/placeables';@@ -32,6 +33,7 @@ interface SignatureEditorProps {function SignatureEditor(props: SignatureEditorProps) {const pdf = usePdfDocument();+ const rootElement = usePdfViewer().rootElement;let canvasRef!: HTMLCanvasElement;let signaturePad: SignaturePad | undefined;@@ -39,19 +41,15 @@ function SignatureEditor(props: SignatureEditorProps) {signaturePad = new SignaturePad(canvasRef);});- const [, setActivePlaceable] = pdf.state.signals.activePlaceableId;const modifyPayload = useModifyPayload();const deletePlaceable = useDeletePlaceable();- const [, setNewPlaceable] = pdf.state.signals.newPlaceable;const updatePlaceable = createCallback((e: MouseEvent) => {e.preventDefault();e.stopPropagation();- setNewPlaceable((prev) =>- prev?.internalId === props.id ? undefined : prev- );- setActivePlaceable(undefined);+ pdf.markup.commands.clearDraftIf(props.id);+ pdf.markup.commands.clearActive();if (!signaturePad?.isEmpty()) {modifyPayload(props.id, PayloadMode.Signature, {@@ -74,7 +72,7 @@ function SignatureEditor(props: SignatureEditorProps) {);onMount(() => {- const el = pdf.rootElement();+ const el = rootElement();if (!el) {setBlockRect(undefined);return;diff --git a/apps/web/src/features/block-pdf/component/placeables/TextBox.tsx b/apps/web/src/features/block-pdf/component/placeables/TextBox.tsxindex 93fe6aaf94..2908e9aeae 100644--- a/apps/web/src/features/block-pdf/component/placeables/TextBox.tsx+++ b/apps/web/src/features/block-pdf/component/placeables/TextBox.tsx@@ -26,8 +26,7 @@ interface TextBoxProps {export function TextBox(props: TextBoxProps) {let textAreaRef!: HTMLTextAreaElement;const [text, setText] = createSignal(props.payload.text);- const [, setActivePlaceable] =- usePdfDocument().state.signals.activePlaceableId;+ const markup = usePdfDocument().markup;const modifyPayload = useModifyPayload();const deletePlaceable = useDeletePlaceable();@@ -92,7 +91,7 @@ export function TextBox(props: TextBoxProps) {onInput={(e) => setText(e.currentTarget.value)}onBlur={() => {updatePlaceable();- setActivePlaceable(undefined);+ markup.commands.clearActive();}}/>);diff --git a/apps/web/src/features/block-pdf/context/pdf-comments-context.tsx b/apps/web/src/features/block-pdf/context/pdf-comments-context.tsxnew file mode 100644index 0000000000..747334a4d8--- /dev/null+++ b/apps/web/src/features/block-pdf/context/pdf-comments-context.tsx@@ -0,0 +1,71 @@+import type { CommentId, ThreadId } from '@core/comments/commentType';+import {+ type Accessor,+ createContext,+ createMemo,+ createSignal,+ type FlowComponent,+ useContext,+} from 'solid-js';+import type { CommentStore } from '../type/comments';++type PdfCommentsContextValue = {+ all: Accessor<CommentStore>;+ byId: Accessor<Map<CommentId, CommentStore[number]>>;+ activeThreadId: Accessor<ThreadId | null>;+ selectedThreadId: Accessor<ThreadId | null>;+ scrollingSuppressed: Accessor<boolean>;+ activateThread: (threadId: ThreadId) => void;+ clearActiveThread: () => void;+ selectThread: (threadId: ThreadId) => void;+ clearSelectedThread: () => void;+ suppressScrolling: () => void;+ restoreScrolling: () => void;+};++const PdfCommentsContext = createContext<PdfCommentsContextValue>();++export const PdfCommentsProvider: FlowComponent<{+ comments: Accessor<CommentStore>;+}> = (props) => {+ const [activeThreadId, setActiveThreadId] = createSignal<ThreadId | null>(+ null+ );+ const [selectedThreadId, setSelectedThreadId] = createSignal<ThreadId | null>(+ null+ );+ const [scrollingSuppressed, setScrollingSuppressed] = createSignal(false);+ const byId = createMemo(() => {+ const comments = new Map<CommentId, CommentStore[number]>();+ for (const comment of props.comments()) comments.set(comment.id, comment);+ return comments;+ });++ return (+ <PdfCommentsContext.Provider+ value={{+ all: props.comments,+ byId,+ activeThreadId,+ selectedThreadId,+ scrollingSuppressed,+ activateThread: setActiveThreadId,+ clearActiveThread: () => setActiveThreadId(null),+ selectThread: setSelectedThreadId,+ clearSelectedThread: () => setSelectedThreadId(null),+ suppressScrolling: () => setScrollingSuppressed(true),+ restoreScrolling: () => setScrollingSuppressed(false),+ }}+ >+ {props.children}+ </PdfCommentsContext.Provider>+ );+};++export function usePdfComments() {+ const context = useContext(PdfCommentsContext);+ if (!context) {+ throw new Error('usePdfComments must be used within PdfCommentsProvider');+ }+ return context;+}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.tsxindex ed8900f722..448d2238d0 100644--- a/apps/web/src/features/block-pdf/context/pdf-document-context.tsx+++ b/apps/web/src/features/block-pdf/context/pdf-document-context.tsx@@ -1,16 +1,38 @@import type { PortalScope } from '@core/component/ScopedPortal';+import type { GetDocumentResponseDataViewLocation } from '@service-storage/generated/schemas/getDocumentResponseDataViewLocation';+import type { PDFDocumentProxy } from 'pdfjs-dist/types/src/display/api';import {type Accessor,+ batch,createContext,createSignal,type FlowComponent,useContext,} from 'solid-js';-import type { LocationSearchParams } from '../signal/location';+import type { IHighlight } from '../model/Highlight';import {- createPdfDocumentState,- type PdfDocumentState,-} from './pdf-document-state';+ createPdfAnnotations,+ type PdfAnnotations,+} from '../primitives/pdf-annotations';+import {+ createPdfDefinitions,+ type PdfDefinitions,+} from '../primitives/pdf-definitions';+import {+ createPdfDocumentModel,+ type PdfDocumentModel,+} from '../primitives/pdf-document-model';+import { createPdfMarkup, type PdfMarkup } from '../primitives/pdf-markup';+import { createPdfOutline, type PdfOutline } from '../primitives/pdf-outline';+import {+ createPdfPersistence,+ type PdfPersistence,+} from '../primitives/pdf-persistence';+import { createPdfTabs, type PdfTabs } from '../primitives/pdf-tabs';+import type {+ LocationSearchParams,+ PdfShareLocation,+} from '../signal/location';export type PdfDocumentPermissions = {canComment: boolean;@@ -18,12 +40,22 @@ export type PdfDocumentPermissions = {isOwner: boolean;};+export type PdfSelectionMenuLocation = {+ pageIndex: number;+ element: HTMLElement;+};++export type PdfAnnotationSelection = {+ nativeSelection: Selection | null;+ selectedHighlights: IHighlight[];+};+export type PdfDocumentContextValue = {documentId: Accessor<string>;+ documentProxy: Accessor<PDFDocumentProxy | undefined>;documentVersionId: Accessor<number | undefined>;documentName: Accessor<string>;isNested: Accessor<boolean>;- hotkeyScope: Accessor<string>;portalScope: Accessor<PortalScope>;permissions: {canComment: Accessor<boolean>;@@ -31,17 +63,42 @@ export type PdfDocumentContextValue = {isOwner: Accessor<boolean>;};locationParams: Accessor<LocationSearchParams>;- rootElement: Accessor<HTMLElement | undefined>;- setRootElement: (element: HTMLElement | undefined) => void;- state: PdfDocumentState;+ persistedViewLocation: Accessor<+ GetDocumentResponseDataViewLocation | undefined+ >;+ setPersistedViewLocation: (+ location: GetDocumentResponseDataViewLocation | undefined+ ) => void;+ shareLocation: Accessor<PdfShareLocation | undefined>;+ setShareLocation: (location: PdfShareLocation | undefined) => void;+ selectionMenuLocation: Accessor<PdfSelectionMenuLocation | null>;+ annotationSelection: Accessor<PdfAnnotationSelection>;+ activeHighlightId: Accessor<string | null>;+ hoveredHighlightId: Accessor<string | null>;+ openSelectionMenu: (location: PdfSelectionMenuLocation) => void;+ closeSelectionMenu: () => void;+ setNativeSelection: (selection: Selection) => void;+ replaceSelectedHighlights: (highlights: IHighlight[]) => void;+ resetSelection: () => void;+ activateHighlight: (uuid: string) => void;+ clearActiveHighlight: () => void;+ hoverHighlight: (uuid: string) => void;+ clearHoveredHighlight: () => void;+ annotations: PdfAnnotations;+ definitions: PdfDefinitions;+ markup: PdfMarkup;+ model: PdfDocumentModel;+ persistence: PdfPersistence;+ tabs: PdfTabs;+ outline: PdfOutline;};export type PdfDocumentProviderProps = {documentId: string;+ documentProxy?: PDFDocumentProxy;documentVersionId?: number;documentName: string;isNested?: boolean;- hotkeyScope: string;portalScope?: PortalScope;permissions: PdfDocumentPermissions;locationParams?: LocationSearchParams;@@ -53,13 +110,35 @@ export const PdfDocumentProvider: FlowComponent<PdfDocumentProviderProps> = (props) => {const documentId = () => props.documentId;- const [rootElement, setRootElement] = createSignal<HTMLElement>();+ const definitions = createPdfDefinitions();+ const markup = createPdfMarkup();+ const model = createPdfDocumentModel();+ const [persistedViewLocation, setPersistedViewLocation] =+ createSignal<GetDocumentResponseDataViewLocation>();+ const [shareLocation, setShareLocation] = createSignal<PdfShareLocation>();+ const [selectionMenuLocation, setSelectionMenuLocation] =+ createSignal<PdfSelectionMenuLocation | null>(null);+ const [annotationSelection, setAnnotationSelection] =+ createSignal<PdfAnnotationSelection>({+ nativeSelection: null,+ selectedHighlights: [],+ });+ const [activeHighlightId, setActiveHighlightId] = createSignal<string | null>(+ null+ );+ const [hoveredHighlightId, setHoveredHighlightId] = createSignal<+ string | null+ >(null);+ const persistence = createPdfPersistence();+ const tabs = createPdfTabs();+ const outline = createPdfOutline();+ const annotations = createPdfAnnotations(documentId);const context: PdfDocumentContextValue = {documentId,+ documentProxy: () => props.documentProxy,documentVersionId: () => props.documentVersionId,documentName: () => props.documentName,isNested: () => props.isNested ?? false,- hotkeyScope: () => props.hotkeyScope,portalScope: () => props.portalScope ?? 'split',permissions: {canComment: () => props.permissions.canComment,@@ -67,9 +146,47 @@ export const PdfDocumentProvider: FlowComponent<PdfDocumentProviderProps> = (isOwner: () => props.permissions.isOwner,},locationParams: () => props.locationParams ?? {},- rootElement,- setRootElement,- state: createPdfDocumentState(documentId),+ persistedViewLocation,+ setPersistedViewLocation,+ shareLocation,+ setShareLocation,+ selectionMenuLocation,+ annotationSelection,+ activeHighlightId,+ hoveredHighlightId,+ openSelectionMenu: setSelectionMenuLocation,+ closeSelectionMenu: () => setSelectionMenuLocation(null),+ setNativeSelection: (nativeSelection) =>+ setAnnotationSelection({+ nativeSelection,+ selectedHighlights: [],+ }),+ replaceSelectedHighlights: (selectedHighlights) =>+ setAnnotationSelection((previous) => ({+ ...previous,+ selectedHighlights,+ })),+ resetSelection: () => {+ batch(() => {+ setSelectionMenuLocation(null);+ setAnnotationSelection({+ nativeSelection: null,+ selectedHighlights: [],+ });+ setActiveHighlightId(null);+ });+ },+ activateHighlight: setActiveHighlightId,+ clearActiveHighlight: () => setActiveHighlightId(null),+ hoverHighlight: setHoveredHighlightId,+ clearHoveredHighlight: () => setHoveredHighlightId(null),+ annotations,+ definitions,+ markup,+ model,+ persistence,+ tabs,+ outline,};return (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.tsdeleted file mode 100644index 78d3a088a2..0000000000--- a/apps/web/src/features/block-pdf/context/pdf-document-state.ts+++ /dev/null@@ -1,378 +0,0 @@-import type { Completion } from '@core/client/completion';-import type { CommentId, 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<ThreadId | 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<CommentId, 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/context/pdf-viewer-context.tsx b/apps/web/src/features/block-pdf/context/pdf-viewer-context.tsxnew file mode 100644index 0000000000..d16eec9038--- /dev/null+++ b/apps/web/src/features/block-pdf/context/pdf-viewer-context.tsx@@ -0,0 +1,78 @@+import {+ type Accessor,+ createContext,+ createSignal,+ type ParentComponent,+ useContext,+} from 'solid-js';+import {+ createPdfViewerRuntime,+ type PdfViewerRuntime,+} from '../primitives/pdf-viewer-runtime';++export type PdfViewerContextValue = PdfViewerRuntime & {+ rootElement: Accessor<HTMLElement | undefined>;+ setRootElement: (element: HTMLElement | undefined) => void;+ pageClicksDisabled: Accessor<boolean>;+ textSelectionActive: Accessor<boolean>;+ searchNavigationPending: Accessor<boolean>;+ beginTextSelection: () => void;+ endTextSelection: () => void;+ beginSearchNavigation: () => void;+ endSearchNavigation: () => void;+ runWithPageClicksDisabled: (operation: () => void) => void;+};++const PdfViewerContext = createContext<PdfViewerContextValue>();++export const PdfViewerProvider: ParentComponent = (props) => {+ const runtime = createPdfViewerRuntime();+ const [rootElement, setRootElement] = createSignal<HTMLElement>();+ const [pageClicksDisabled, setPageClicksDisabled] = createSignal(false);+ const [textSelectionActive, setTextSelectionActive] = createSignal(false);+ const [searchNavigationPending, setSearchNavigationPending] =+ createSignal(false);++ const value: PdfViewerContextValue = {+ ...runtime,+ rootElement,+ setRootElement,+ pageClicksDisabled,+ textSelectionActive,+ searchNavigationPending,+ beginTextSelection() {+ setTextSelectionActive(true);+ },+ endTextSelection() {+ setTextSelectionActive(false);+ },+ beginSearchNavigation() {+ setSearchNavigationPending(true);+ },+ endSearchNavigation() {+ setSearchNavigationPending(false);+ },+ runWithPageClicksDisabled(operation) {+ setPageClicksDisabled(true);+ try {+ operation();+ } finally {+ setPageClicksDisabled(false);+ }+ },+ };++ return (+ <PdfViewerContext.Provider value={value}>+ {props.children}+ </PdfViewerContext.Provider>+ );+};++export function usePdfViewer(): PdfViewerContextValue {+ const context = useContext(PdfViewerContext);+ if (!context) {+ throw new Error('usePdfViewer must be used within a PdfViewerProvider');+ }+ return context;+}diff --git a/apps/web/src/features/block-pdf/model/Reference.ts b/apps/web/src/features/block-pdf/model/Reference.tsindex 8674ff6096..9ad4ae6801 100644--- a/apps/web/src/features/block-pdf/model/Reference.ts+++ b/apps/web/src/features/block-pdf/model/Reference.ts@@ -1,60 +1,42 @@-import TocUtils from '../util/TocUtils';-import type Section from './Section';-interface IReference {pageNum: number;yPos: number;- sectionName: string;+ sectionId: number | null;context: string;}class Reference implements IReference {pageNum: number;yPos: number;- sectionName: string;+ sectionId: number | null;context: string;- constructor({ pageNum, yPos, sectionName, context }: IReference) {+ constructor({ pageNum, yPos, sectionId, context }: IReference) {if (typeof pageNum !== 'number' || pageNum < 0) {console.error('Invalid reference pageNum');} else if (typeof yPos !== 'number' || !yPos) {console.error('Invalid reference yPos');- } else if (typeof sectionName !== 'string') {- console.error('Invalid reference sectionName');} else if (!context || typeof context !== 'string') {console.error('Invalid reference context');}this.pageNum = pageNum;this.yPos = yPos;- this.sectionName = sectionName;+ this.sectionId = sectionId;this.context = context;}- static fromXML(- xml: Element,- {- idToSectionMap,- }: {- idToSectionMap: Partial<Record<number, Section>>;- }- ): Reference {- const sectionID = parseInt(xml.getAttribute('section') || '');- let sectionName: string;- try {- const section = TocUtils.getSection({ id: sectionID, idToSectionMap });- sectionName = section?.fullDescriptor || '';- } catch (_e) {- sectionName = '';- }-+ static fromXML(xml: Element): Reference {const context = document.createElement('textarea');context.innerHTML = xml.textContent || '';+ const rawSectionId = xml.getAttribute('section');+ const parsedSectionId =+ rawSectionId == null ? Number.NaN : parseInt(rawSectionId, 10);return new Reference({pageNum: parseInt(xml.getAttribute('page') || ''),yPos: parseInt(xml.getAttribute('y') || ''),- sectionName: sectionName,+ sectionId: Number.isNaN(parsedSectionId) ? null : parsedSectionId,context: context.value,});}diff --git a/apps/web/src/features/block-pdf/model/Section.ts b/apps/web/src/features/block-pdf/model/Section.tsindex fad5a16789..b5ec167deb 100644--- a/apps/web/src/features/block-pdf/model/Section.ts+++ b/apps/web/src/features/block-pdf/model/Section.ts@@ -1,5 +1,4 @@import { v7 as uuid7 } from 'uuid';-import type { PageModel } from './Page';function decodeHTMLString(strToDecode: string): string {const parser = new DOMParser();@@ -24,8 +23,6 @@ export interface ISection {numRefs: number;showBookmark: boolean;bookmarkTitle: string | null;- nextSection?: ISection | null;- prevSection?: ISection | null;cloned?: boolean;uuid?: string;}@@ -68,16 +65,12 @@ class Section {public fullTitle: string;public numRefs: number;public uuid: string;- public nextSection: ISection | null;- public prevSection: ISection | null;public fullDescriptor: string;public lowerCaseFullDescriptor: string;public showBookmark: boolean;public bookmarkTitle: string | null;public cloned: boolean = false;- public pages: PageModel[] | null;-constructor({id,title,@@ -90,8 +83,6 @@ class Section {numRefs,showBookmark = true,bookmarkTitle = null,- nextSection = null,- prevSection = null,cloned = false,uuid,}: ISection) {@@ -107,9 +98,6 @@ class Section {this.numRefs = numRefs;this.showBookmark = showBookmark;- this.nextSection = nextSection; // Set after construction if not provided- this.prevSection = prevSection; // Set after construction if not provided-// Derived propsthis.typeCased = cloned? (type ?? '')@@ -136,8 +124,6 @@ class Section {this.titleCased ? `: ${this.titleCased}` : ''}`: this.titleCased;-- this.pages = null;}public static parseSegmentType(@@ -195,8 +181,6 @@ class Section {numRefs,showBookmark,bookmarkTitle,- nextSection,- prevSection,} = this;const clone = new Section({id,@@ -210,8 +194,6 @@ class Section {numRefs,showBookmark,bookmarkTitle,- nextSection,- prevSection,cloned: true,});clone.titleCased = this.titleCased;@@ -223,64 +205,6 @@ class Section {return clone;}- public static appearsBefore(- section: Pick<Section, 'page' | 'y'>,- otherSection: Pick<Section, 'page' | 'y'>- ) {- return (- section.page < otherSection.page ||- (section.page === otherSection.page && section.y < otherSection.y)- );- }-- public shouldDisplay({- page,- yPos,- }: {- page: number;- yPos: number;- }): boolean {- const bufferedY = yPos;- const { page: nextPage, y: nextY } = this.nextSection ?? {};-- // Should not display if section is on a later page- if (this.page > page) {- return false;- }-- if (page === this.page) {- // On same page as section- if (bufferedY > this.y) {- // Currently below section title- if (nextPage === page && nextY != null) {- // Next section is on same page- // Return true if next section is below the current y-position- return bufferedY < nextY;- } else {- return true;- }- }-- return false;- }-- // On page after section- // If this is the last section- if (nextPage == null || nextY == null) {- // Last section- return true;- } else if (page < nextPage) {- // Current page between this section and next section- return true;- } else if (nextPage === page) {- // Next section is on current page- // return yPos + buffer < this.nextY- return bufferedY < nextY;- }-- return false;- }-static getFullTitle(sectionNode: Element): string {const title = sectionNode.getAttribute('title');const type = sectionNode.getAttribute('type');@@ -304,13 +228,3 @@ class Section {}export default Section;--/**- * Stringifyable version of a Section object- *- * Specifically, this is used for searching sections- */-export type StringifyableSection = Pick<- Section,- 'lowerCaseFullDescriptor' | 'id' | 'numRefs' | 'fullTitle' | 'page' | 'y'->;diff --git a/apps/web/src/features/block-pdf/model/TocItem.ts b/apps/web/src/features/block-pdf/model/TocItem.tsdeleted file mode 100644index 24e6c50c31..0000000000--- a/apps/web/src/features/block-pdf/model/TocItem.ts+++ /dev/null@@ -1,24 +0,0 @@-import type Section from './Section';--/**- * Wrapper on Section to store Table of Contents-related information, namely- * what sections are under this section and whether the item is expanded- */-class TocItem {- public section: Section;- public children: TocItem[];- public uuid: string;- public expanded?: boolean;-- constructor(section: Section, children: TocItem[]) {- this.section = section;- this.children = children;- this.uuid = `${Date.now()}-${section.id}`;- }-- public clone(children?: TocItem[]): TocItem {- return new TocItem(this.section, children || this.children);- }-}--export default TocItem;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-annotations.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-annotations.test.tsnew file mode 100644index 0000000000..886062c9ce--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-annotations.test.ts@@ -0,0 +1,295 @@+import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';+import type { CreateUnthreadedAnchorResponse } from '@service-storage/generated/schemas/createUnthreadedAnchorResponse';+import type { DeleteCommentResponse } from '@service-storage/generated/schemas/deleteCommentResponse';+import type { DeleteUnthreadedAnchorResponse } from '@service-storage/generated/schemas/deleteUnthreadedAnchorResponse';+import type { EditAnchorResponse } from '@service-storage/generated/schemas/editAnchorResponse';+import type { EditCommentResponse } from '@service-storage/generated/schemas/editCommentResponse';+import { waitFor } from '@solidjs/testing-library';+import { createRoot } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { IHighlight } from '../model/Highlight';+import { createPdfAnnotations, type PdfAnnotations } from './pdf-annotations';++const annotationQueries = vi.hoisted(() => ({+ getPdfAnchors: vi.fn(async (_documentId: string) => []),+ getPdfComments: vi.fn(async (_documentId: string) => []),+}));++vi.mock('../queries/annotations', () => annotationQueries);++function setup(documentId: string): {+ annotations: PdfAnnotations;+ dispose: () => void;+} {+ return createRoot((dispose) => ({+ annotations: createPdfAnnotations(() => documentId),+ dispose,+ }));+}++async function waitForInitialResources(annotations: PdfAnnotations) {+ await waitFor(() => {+ expect(annotations.anchors()).toEqual([]);+ expect(annotations.commentThreads()).toEqual([]);+ });+}++function createHighlight(+ uuid: string,+ overrides: Partial<IHighlight> = {}+): IHighlight {+ return {+ uuid,+ pageNum: 2,+ rects: [{ top: 0.1, left: 0.2, width: 0.3, height: 0.04 }],+ color: { red: 253, green: 224, blue: 71, alpha: 0.4 },+ type: 1,+ thread: null,+ text: 'highlight text',+ pageViewport: { width: 600, height: 800 },+ hasTempThread: false,+ existsOnServer: false,+ owner: 'user-1',+ ...overrides,+ };+}++function createServerHighlight(+ uuid: string,+ threadId?: number+): CreateUnthreadedAnchorResponse {+ return {+ uuid,+ documentId: 'document-1',+ anchorType: 'highlight',+ page: 2,+ highlightRects: [{ id: 1, top: 0.1, left: 0.2, width: 0.3, height: 0.04 }],+ red: 253,+ green: 224,+ blue: 71,+ alpha: 0.4,+ highlightType: 1,+ pageViewportWidth: 600,+ pageViewportHeight: 800,+ text: 'server highlight',+ owner: 'user-1',+ threadId,+ };+}++function createCommentResponse(+ threadId: number,+ commentId: number+): CreateCommentResponse {+ return {+ documentId: 'document-1',+ thread: {+ threadId,+ documentId: 'document-1',+ owner: 'user-1',+ resolved: false,+ },+ comments: [+ {+ commentId,+ threadId,+ owner: 'user-1',+ text: 'first comment',+ },+ ],+ };+}++beforeEach(() => {+ annotationQueries.getPdfAnchors.mockClear();+ annotationQueries.getPdfComments.mockClear();+});++describe('createPdfAnnotations', () => {+ it('starts empty, projects highlight indexes, and isolates authorities', async () => {+ const first = setup('document-1');+ const second = setup('document-2');+ await Promise.all([+ waitForInitialResources(first.annotations),+ waitForInitialResources(second.annotations),+ ]);+ const highlight = createHighlight('highlight-1');++ first.annotations.commands.beginNewHighlightCommentDrafts([highlight]);++ expect({+ anchorQueryDocumentIds: annotationQueries.getPdfAnchors.mock.calls.map(+ ([documentId]) => documentId+ ),+ commentQueryDocumentIds: annotationQueries.getPdfComments.mock.calls.map(+ ([documentId]) => documentId+ ),+ firstHighlight: first.annotations.highlightsByUuid()['highlight-1']?.uuid,+ secondHighlights: second.annotations.highlightsByUuid(),+ exposesAnchorMutate: 'mutate' in first.annotations.anchors,+ exposesCommentThreadMutate: 'mutate' in first.annotations.commentThreads,+ }).toEqual({+ anchorQueryDocumentIds: ['document-1', 'document-2'],+ commentQueryDocumentIds: ['document-1', 'document-2'],+ firstHighlight: 'highlight-1',+ secondHighlights: {},+ exposesAnchorMutate: false,+ exposesCommentThreadMutate: false,+ });++ first.dispose();+ second.dispose();+ });++ it('applies resource response transitions in response order', async () => {+ const { annotations, dispose } = setup('document-1');+ await waitForInitialResources(annotations);+ const firstAnchor = createServerHighlight('highlight-1');+ const secondAnchor = createServerHighlight('highlight-2');+ const createdComment = createCommentResponse(31, 41);++ annotations.commands.applyCreatedAnchor(firstAnchor);+ annotations.commands.applyCreatedAnchor(secondAnchor);+ annotations.commands.applyEditedAnchor({+ ...firstAnchor,+ text: 'edited highlight',+ } as EditAnchorResponse);+ annotations.commands.applyCreatedComment(createdComment);+ annotations.commands.applyEditedComment({+ ...createdComment.comments[0],+ documentId: 'document-1',+ documentName: 'document.pdf',+ documentOwner: 'user-1',+ text: 'edited comment',+ } as EditCommentResponse);++ expect({+ anchors: annotations.anchors()?.map((anchor) => ({+ uuid: anchor.uuid,+ text: 'text' in anchor ? anchor.text : null,+ })),+ comments: annotations+ .commentThreads()+ ?.flatMap((thread) =>+ thread.comments.map(({ commentId, text }) => ({ commentId, text }))+ ),+ }).toEqual({+ anchors: [+ { uuid: 'highlight-2', text: 'server highlight' },+ { uuid: 'highlight-1', text: 'edited highlight' },+ ],+ comments: [{ commentId: 41, text: 'edited comment' }],+ });++ annotations.commands.applyDeletedComment({+ commentId: 41,+ documentId: 'document-1',+ thread: { threadId: 31, deleted: false },+ } satisfies DeleteCommentResponse);+ annotations.commands.applyDeletedAnchor({+ uuid: 'highlight-1',+ documentId: 'document-1',+ threadId: 31,+ } as DeleteUnthreadedAnchorResponse);++ expect({+ anchorUuids: annotations.anchors()?.map((anchor) => anchor.uuid),+ commentThreads: annotations.commentThreads(),+ }).toEqual({+ anchorUuids: ['highlight-2'],+ commentThreads: [],+ });+ dispose();+ });++ it('projects server anchors and threads into highlights', async () => {+ const { annotations, dispose } = setup('document-1');+ await waitForInitialResources(annotations);+ const anchor = createServerHighlight('highlight-1', 31);++ annotations.commands.applyCreatedAnchor(anchor);+ expect(annotations.highlightsByUuid()).toEqual({});++ annotations.commands.applyCreatedComment(createCommentResponse(31, 41));++ await waitFor(() => {+ expect(annotations.highlightsByUuid()['highlight-1']).toEqual({+ owner: 'user-1',+ existsOnServer: true,+ pageNum: 2,+ rects: [+ {+ id: 1,+ top: 0.1,+ left: 0.2,+ width: 0.3,+ height: 0.04,+ },+ ],+ color: { red: 253, green: 224, blue: 71, alpha: 0.4 },+ hasTempThread: false,+ uuid: 'highlight-1',+ text: 'server highlight',+ type: 1,+ pageViewport: { width: 600, height: 800 },+ thread: {+ threadId: 31,+ rootId: 41,+ anchorId: 'highlight-1',+ page: 2,+ comments: [+ {+ commentId: 41,+ threadId: 31,+ owner: 'user-1',+ text: 'first comment',+ },+ ],+ isResolved: false,+ },+ });+ });+ dispose();+ });++ it('reverts converted drafts and removes newly created drafts', async () => {+ const { annotations, dispose } = setup('document-1');+ await waitForInitialResources(annotations);+ const existing = createHighlight('existing-highlight');+ const created = createHighlight('created-highlight');++ annotations.commands.beginNewHighlightCommentDrafts([existing, created]);+ expect(annotations.highlightsByUuid()[created.uuid]?.hasTempThread).toBe(+ true+ );+ annotations.commands.beginExistingHighlightCommentDraft(existing);+ expect(annotations.highlightsByUuid()[existing.uuid]?.hasTempThread).toBe(+ true+ );++ expect(+ annotations.commands.cancelTemporaryHighlightCommentDraft(existing.uuid)+ ).toBe(true);+ expect(+ annotations.commands.cancelTemporaryHighlightCommentDraft(created.uuid)+ ).toBe(false);++ expect({+ existing: annotations.highlightsByUuid()[existing.uuid],+ created: annotations.highlightsByUuid()[created.uuid],+ hasHighlights: annotations.hasHighlights(),+ }).toEqual({+ existing: {+ ...existing,+ thread: null,+ hasTempThread: false,+ },+ created: undefined,+ hasHighlights: true,+ });++ annotations.commands.cancelTemporaryHighlightCommentDraft(existing.uuid);+ expect(annotations.hasHighlights()).toBe(false);+ dispose();+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-annotations.ts b/apps/web/src/features/block-pdf/primitives/pdf-annotations.tsnew file mode 100644index 0000000000..e7e29a0e7f--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-annotations.ts@@ -0,0 +1,284 @@+import type { Comment } from '@service-storage/generated/schemas/comment';+import type { CommentThread } from '@service-storage/generated/schemas/commentThread';+import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';+import type { CreateUnthreadedAnchorResponse } from '@service-storage/generated/schemas/createUnthreadedAnchorResponse';+import type { DeleteCommentResponse } from '@service-storage/generated/schemas/deleteCommentResponse';+import type { DeleteUnthreadedAnchorResponse } from '@service-storage/generated/schemas/deleteUnthreadedAnchorResponse';+import type { EditAnchorResponse } from '@service-storage/generated/schemas/editAnchorResponse';+import type { EditCommentResponse } from '@service-storage/generated/schemas/editCommentResponse';+import {+ type Accessor,+ batch,+ createEffect,+ createMemo,+ createResource,+ createSignal,+} from 'solid-js';+import { createStore, produce, reconcile } from 'solid-js/store';+import type { IHighlight } from '../model/Highlight';+import { getPdfAnchors, getPdfComments } from '../queries/annotations';++export type HighlightUuidMap = Partial<Record<string, IHighlight>>;+export type HighlightPageMap = Partial<Record<number, HighlightUuidMap>>;++export function createPdfAnnotations(documentId: Accessor<string>) {+ const [highlightsByPage, setHighlightsByPage] = createStore<HighlightPageMap>(+ {}+ );+ const [convertedHighlightDraftId, setConvertedHighlightDraftId] =+ createSignal<string>();+ const [commentThreadsResource, { mutate: mutateCommentThreads }] =+ createResource(documentId, getPdfComments);+ const [anchorsResource, { mutate: mutateAnchors }] = createResource(+ documentId,+ getPdfAnchors+ );++ const highlightsByUuid = createMemo(() => {+ const result: HighlightUuidMap = {};+ for (const pageHighlights of Object.values(highlightsByPage)) {+ if (!pageHighlights) continue;+ for (const [uuid, highlight] of Object.entries(pageHighlights)) {+ result[uuid] = highlight;+ }+ }+ return result;+ });++ const hasHighlights = () =>+ Object.values(highlightsByPage).some(+ (pageHighlights) => Object.values(pageHighlights ?? {}).length > 0+ );++ createEffect(() => {+ setHighlightsByPage(reconcile({}));++ const anchors = anchorsResource();+ if (!anchors || anchors.length === 0) return;++ const commentThreads = commentThreadsResource() ?? [];+ const highlightAnchors = anchors.filter(+ (anchor) => anchor.anchorType === 'highlight'+ );++ const mappedAnchors = highlightAnchors.flatMap((anchor) => {+ const commentThread = commentThreads.find(+ (thread) => thread.thread.threadId === anchor.threadId+ );+ if (!commentThread && anchor.threadId) return [];++ 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) {+ setHighlightsByPage(highlight.pageNum, (previous) => ({+ ...previous,+ [highlight.uuid]: highlight,+ }));+ }+ });+ });++ const commands = {+ applyCreatedAnchor(response: CreateUnthreadedAnchorResponse) {+ mutateAnchors((previous) => [...(previous ?? []), response]);+ },+ applyDeletedAnchor(response: DeleteUnthreadedAnchorResponse) {+ mutateAnchors((previous) =>+ (previous ?? []).filter((anchor) => anchor.uuid !== response.uuid)+ );+ if (response.threadId != null) {+ mutateCommentThreads((previous) =>+ (previous ?? []).filter(+ (thread) => thread.thread.threadId !== response.threadId+ )+ );+ }+ },+ applyEditedAnchor(response: EditAnchorResponse) {+ mutateAnchors((previous) => [+ ...(previous ?? []).filter((anchor) => anchor.uuid !== response.uuid),+ response,+ ]);+ },+ applyCreatedComment(response: CreateCommentResponse) {+ const commentThread: CommentThread = {+ thread: response.thread,+ comments: response.comments,+ };+ const anchor = response.anchor;+ batch(() => {+ if (anchor) {+ mutateAnchors((previous) => [...(previous ?? []), anchor]);+ }++ mutateCommentThreads((previous) => {+ let replacedExistingThread = false;+ const next = (previous ?? []).map((thread) => {+ if (thread.thread.threadId !== commentThread.thread.threadId) {+ return thread;+ }+ replacedExistingThread = true;+ return commentThread;+ });+ if (!replacedExistingThread) next.push(commentThread);+ return next;+ });+ });+ },+ applyEditedComment(response: EditCommentResponse) {+ mutateCommentThreads((previous) =>+ (previous ?? []).map((thread) => {+ if (thread.thread.threadId !== response.threadId) return thread;+ return {+ thread: thread.thread,+ comments: thread.comments.map((comment) => {+ if (comment.commentId !== response.commentId) return comment;+ const editedComment: Comment = response;+ return editedComment;+ }),+ };+ })+ );+ },+ applyDeletedComment(response: DeleteCommentResponse) {+ batch(() => {+ if (response.thread.deleted) {+ mutateCommentThreads((previous) =>+ (previous ?? []).filter(+ (thread) => thread.thread.threadId !== response.thread.threadId+ )+ );+ } else {+ mutateCommentThreads((previous) =>+ (previous ?? []).map((thread) => {+ if (thread.thread.threadId !== response.thread.threadId) {+ return thread;+ }+ return {+ thread: thread.thread,+ comments: thread.comments.filter(+ (comment) => comment.commentId !== response.commentId+ ),+ };+ })+ );+ }++ if (response.anchor?.deleted) {+ mutateAnchors((previous) =>+ (previous ?? []).filter(+ (anchor) => anchor.uuid !== response.anchor?.uuid+ )+ );+ }+ });+ },+ beginExistingHighlightCommentDraft(highlight: IHighlight) {+ batch(() => {+ setConvertedHighlightDraftId(highlight.uuid);+ setHighlightsByPage(highlight.pageNum, highlight.uuid, (previous) => ({+ ...previous,+ hasTempThread: true,+ }));+ });+ },+ beginNewHighlightCommentDrafts(highlights: IHighlight[]) {+ setHighlightsByPage(+ produce((state) => {+ for (const highlight of highlights) {+ const pageHighlights = state[highlight.pageNum];+ const temporaryHighlight = {+ ...highlight,+ hasTempThread: true,+ };+ if (pageHighlights) {+ pageHighlights[highlight.uuid] = temporaryHighlight;+ } else {+ state[highlight.pageNum] = {+ [highlight.uuid]: temporaryHighlight,+ };+ }+ }+ })+ );+ },+ cancelTemporaryHighlightCommentDraft(uuid: string) {+ const highlight = highlightsByUuid()[uuid];+ const convertedExistingHighlight = convertedHighlightDraftId() === uuid;+ if (!highlight) {+ if (convertedExistingHighlight) setConvertedHighlightDraftId(undefined);+ return convertedExistingHighlight;+ }++ if (convertedExistingHighlight) {+ batch(() => {+ setConvertedHighlightDraftId(undefined);+ setHighlightsByPage(+ highlight.pageNum,+ uuid,+ (previous) =>+ previous && {+ ...previous,+ thread: null,+ hasTempThread: false,+ }+ );+ });+ return true;+ }++ setHighlightsByPage(+ highlight.pageNum,+ produce((pageHighlights) => {+ if (!pageHighlights) return;+ delete pageHighlights[uuid];+ })+ );+ return false;+ },+ };++ return {+ anchors: () => anchorsResource(),+ commentThreads: () => commentThreadsResource(),+ highlightsByPage,+ highlightsByUuid,+ hasHighlights,+ commands,+ };+}++export type PdfAnnotations = ReturnType<typeof createPdfAnnotations>;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-definitions.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-definitions.test.tsnew file mode 100644index 0000000000..0468de1420--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-definitions.test.ts@@ -0,0 +1,178 @@+import { createRoot } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';+import Term from '../model/Term';+import { createPdfDefinitions, type PdfDefinitions } from './pdf-definitions';++vi.mock('../util/estimateTextWidth', () => ({+ estimateTextWidth: () => 100,+}));++function setup(): {+ definitions: PdfDefinitions;+ dispose: () => void;+} {+ return createRoot((dispose) => ({+ definitions: createPdfDefinitions(),+ dispose,+ }));+}++function createTerm(id: string, name = `Term ${id}`) {+ const document = new DOMParser().parseFromString(+ '<root><definition><span>Definition</span></definition></root>',+ 'application/xml'+ );+ return new Term({+ id,+ name,+ definition: document.querySelector('definition')!,+ pageNum: 1,+ yPos: 20,+ numRefs: 0,+ references: document.getElementsByTagName('reference'),+ sims: [],+ });+}++const termXml = (id: string, name: string) => `+ <root>+ <term id="${id}" name="${name}" page="1" y="20">+ <definition><span>${name} definition</span></definition>+ <references />+ </term>+ </root>+`;++function popupSnapshot(+ popup: PdfDefinitions['root'] | PdfDefinitions['popup']+) {+ return {+ terms: popup.terms(),+ element: popup.element(),+ termIDToSizingMap: popup.termIDToSizingMap(),+ pageWidth: popup.pageWidth(),+ };+}++describe('createPdfDefinitions', () => {+ it('starts with independent empty root and popup state', () => {+ const { definitions, dispose } = setup();++ expect(definitions.root).not.toBe(definitions.popup);+ expect(popupSnapshot(definitions.root)).toEqual({+ terms: [],+ element: null,+ termIDToSizingMap: {},+ pageWidth: null,+ });+ expect(popupSnapshot(definitions.popup)).toEqual({+ terms: [],+ element: null,+ termIDToSizingMap: {},+ pageWidth: null,+ });+ dispose();+ });++ it('dispatches root and popup actions independently', () => {+ const { definitions, dispose } = setup();+ const rootElement = document.createElement('span');+ const popupElement = document.createElement('span');+ const first = createTerm('1');+ const second = createTerm('2');++ definitions.commands.dispatchRoot({+ type: 'SET_TERM_FROM_ELEMENT',+ term: first,+ pageWidth: 800,+ element: rootElement,+ });+ definitions.commands.dispatchRoot({+ type: 'ADD_NEXT_TERM',+ term: first,+ });+ definitions.commands.dispatchRoot({+ type: 'ADD_NEXT_TERM',+ term: second,+ });+ definitions.commands.dispatchPopup({+ type: 'SET_TERM_FROM_ELEMENT',+ term: second,+ pageWidth: 700,+ element: popupElement,+ });++ expect(popupSnapshot(definitions.root)).toEqual({+ terms: [first, second],+ element: rootElement,+ termIDToSizingMap: {+ '1': { width: 550, truncated: false },+ '2': { width: 550, truncated: false },+ },+ pageWidth: 800,+ });+ expect(popupSnapshot(definitions.popup)).toEqual({+ terms: [second],+ element: popupElement,+ termIDToSizingMap: {+ '2': { width: 550, truncated: false },+ },+ pageWidth: 700,+ });++ definitions.commands.dispatchRoot({+ type: 'REMOVE_NEXT_TERMS',+ index: 0,+ });+ expect(definitions.root.terms()).toEqual([first]);+ definitions.commands.dispatchRoot({ type: 'REMOVE_POPUPS' });++ expect(popupSnapshot(definitions.root)).toEqual({+ terms: [],+ element: null,+ termIDToSizingMap: {},+ pageWidth: null,+ });+ expect(definitions.popup.terms()).toEqual([second]);+ dispose();+ });++ it('shares cloned term lookup across root and popup state', () => {+ const { definitions, dispose } = setup();+ definitions.commands.loadTermXml(termXml('1', 'First'));++ const rootTerm = definitions.getTerm('1')!;+ const popupTerm = definitions.getTerm('1')!;+ definitions.commands.dispatchRoot({ type: 'SET_TERM', term: rootTerm });+ definitions.commands.dispatchPopup({ type: 'SET_TERM', term: popupTerm });++ expect(rootTerm).not.toBe(popupTerm);+ expect(definitions.root.terms()[0].id).toBe('1');+ expect(definitions.popup.terms()[0].id).toBe('1');+ rootTerm.name = 'Changed';+ expect(definitions.getTerm('1')?.name).toBe('First');+ dispose();+ });++ it('loads term XML once per authority', () => {+ const first = setup();+ const second = setup();++ first.definitions.commands.loadTermXml(termXml('1', 'First'));+ first.definitions.commands.loadTermXml(termXml('2', 'Ignored'));+ second.definitions.commands.loadTermXml(termXml('2', 'Second'));+ first.definitions.commands.dispatchRoot({+ type: 'SET_TERM',+ term: first.definitions.getTerm('1')!,+ });++ expect(first.definitions.getTerm('1')?.name).toBe('First');+ expect(first.definitions.getTerm('2')).toBeNull();+ expect(first.definitions.root.terms()).toHaveLength(1);+ expect(second.definitions.getTerm('1')).toBeNull();+ expect(second.definitions.getTerm('2')?.name).toBe('Second');+ expect(second.definitions.root.terms()).toEqual([]);+ first.dispose();+ second.dispose();+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-definitions.ts b/apps/web/src/features/block-pdf/primitives/pdf-definitions.tsnew file mode 100644index 0000000000..9186c47293--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-definitions.ts@@ -0,0 +1,279 @@+import { createStore, produce } from 'solid-js/store';+import Term from '../model/Term';+import { decodeDefinitionText } from '../util/definitionText';+import { InvalidActionError } from '../util/errors';+import { estimateTextWidth } from '../util/estimateTextWidth';+import { XMLUtils } from '../util/XMLUtils';++const MIN_SIDE_PADDING = 20;+const WIDTH_PADDING = 50;+const MAX_LINES = 14;++class TermLexicon {+ readonly #terms = new Map<string, Term>();+ #loaded = false;++ get(id: string): Term | null {+ return this.#terms.get(id)?.clone() ?? null;+ }++ load(xml: string) {+ if (this.#loaded) return;++ const terms = XMLUtils.parse(xml).getElementsByTagName('term');+ for (const termNode of Array.from(terms).sort((a, b) => {+ const aId = a.getAttribute('id') || '';+ const bId = b.getAttribute('id') || '';+ return parseInt(aId) - parseInt(bId);+ })) {+ const id = termNode.getAttribute('id') || '';+ const term = new Term({+ id,+ name: termNode.getAttribute('name') || '',+ definition: termNode.getElementsByTagName('definition')[0],+ pageNum: parseInt(termNode.getAttribute('page') || ''),+ yPos: parseInt(termNode.getAttribute('y') || ''),+ numRefs:+ termNode+ .getElementsByTagName('references')[0]+ ?.getElementsByTagName('reference').length ?? 0,+ references: termNode+ .getElementsByTagName('references')[0]+ ?.getElementsByTagName('reference'),+ sims: termNode.getAttribute('sims')+ ? (termNode.getAttribute('sims') || '').trim().split(' ')+ : [],+ });+ this.#terms.set(id, term);+ }++ this.#loaded = true;+ }+}++function calculateSizing(+ term: Readonly<Term>,+ draft: DefinitionPopupState+): {+ width: number;+ truncated: boolean;+} {+ const text = Array.from(term.definition.childNodes)+ .filter((node) => node.nodeName.includes('span'))+ .map((element) => decodeDefinitionText(element as Element))+ .join('');++ const rowWidth = draft.pageWidth ?? 0;+ let width = 0;+ let truncated = false;++ const maxWidth = rowWidth - WIDTH_PADDING - 2 * MIN_SIDE_PADDING;+ const minWidth = Math.min(550, maxWidth);+ const targetWidth = Math.min(550, maxWidth);++ const singleLineWidth = estimateTextWidth(text);+ if (singleLineWidth < targetWidth) {+ width = Math.max(minWidth, singleLineWidth + WIDTH_PADDING);+ } else {+ let targetLines = 3;+ const numLinesWithTargetWidth = Math.ceil(singleLineWidth / targetWidth);+ if (numLinesWithTargetWidth <= targetLines) {+ width = targetWidth;+ } else {+ if (numLinesWithTargetWidth > 5) {+ targetLines += Math.ceil((numLinesWithTargetWidth - 5) / 2);+ }+ width = Math.min(+ maxWidth,+ (targetWidth * numLinesWithTargetWidth) / targetLines+ );+ }++ const estimatedLines = Math.ceil(singleLineWidth / width);+ width += WIDTH_PADDING;+ if (estimatedLines > MAX_LINES) {+ truncated = true;+ }+ }++ return {+ width,+ truncated,+ };+}++function updateTermIds(draft: DefinitionPopupState): void {+ draft.termIDs = [...new Set(draft.terms.map((term) => term.id))];+}++function updateTermSizing(draft: DefinitionPopupState): void {+ draft.termIDToSizingMap = Object.fromEntries(+ draft.terms.map((term) => [term.id, calculateSizing(term, draft)])+ );+}++export interface DefinitionPopupState {+ terms: Term[];+ termIDs: string[];+ termIDToSizingMap: Partial<+ Record<+ string,+ {+ width: number;+ truncated: boolean;+ }+ >+ >;+ pageWidth: number | null;+ element: Element | null;+}++type SetRectsAction = {+ type: 'SET_RECTS';+ pageWidth: number;+};++type SetTermAction = {+ type: 'SET_TERM';+ term: Term;+};++type SetTermFromElementAction = {+ type: 'SET_TERM_FROM_ELEMENT';+ term: Term;+ pageWidth: number;+ element: Element;+};++type AddNextTermAction = {+ type: 'ADD_NEXT_TERM';+ term: Term;+};++type RemoveNextTermsAction = {+ type: 'REMOVE_NEXT_TERMS';+ index: number;+};++type RemovePopupsAction = {+ type: 'REMOVE_POPUPS';+};++export type DefinitionPopupAction =+ | SetTermAction+ | RemovePopupsAction+ | AddNextTermAction+ | RemoveNextTermsAction+ | SetTermFromElementAction+ | SetRectsAction;++function reducePopup(+ draft: DefinitionPopupState,+ action: DefinitionPopupAction+) {+ switch (action.type) {+ case 'SET_RECTS':+ draft.pageWidth = action.pageWidth;+ updateTermSizing(draft);+ break;+ case 'SET_TERM_FROM_ELEMENT':+ draft.pageWidth = action.pageWidth;+ draft.element = action.element;+ draft.terms = [action.term];+ updateTermIds(draft);+ updateTermSizing(draft);+ break;+ case 'SET_TERM':+ draft.terms = [action.term];+ updateTermIds(draft);+ updateTermSizing(draft);+ break;+ case 'ADD_NEXT_TERM':+ if (draft.terms.length === 0) {+ console.error(+ 'Invalid state, cannot add term if there is not already a term'+ );+ return;+ }+ if (draft.termIDs.includes(action.term.id)) {+ return;+ }+ draft.terms.push(action.term);+ updateTermIds(draft);+ updateTermSizing(draft);+ break;+ case 'REMOVE_NEXT_TERMS': {+ const { index } = action;+ if (index === draft.terms.length - 1) {+ return;+ }+ if (index < 0 || index >= draft.terms.length) {+ console.error('Invalid term index provided');+ }+ draft.terms = draft.terms.slice(0, index + 1);+ updateTermIds(draft);+ updateTermSizing(draft);+ break;+ }+ case 'REMOVE_POPUPS':+ draft.terms = [];+ draft.pageWidth = null;+ draft.element = null;+ updateTermIds(draft);+ updateTermSizing(draft);+ break;+ default:+ throw new InvalidActionError(action);+ }+}++function createDefinitionPopupState(): DefinitionPopupState {+ return {+ terms: [],+ termIDs: [],+ termIDToSizingMap: {},+ pageWidth: null,+ element: null,+ };+}++function createDefinitionView(store: DefinitionPopupState) {+ return {+ terms: () => store.terms,+ element: () => store.element,+ termIDToSizingMap: () => store.termIDToSizingMap,+ pageWidth: () => store.pageWidth,+ };+}++export function createPdfDefinitions() {+ const [root, setRoot] = createStore(createDefinitionPopupState());+ const [popup, setPopup] = createStore(createDefinitionPopupState());+ const termData = new TermLexicon();++ const dispatchRoot = (action: DefinitionPopupAction) => {+ setRoot(+ produce<DefinitionPopupState>((state) => reducePopup(state, action))+ );+ };+ const dispatchPopup = (action: DefinitionPopupAction) => {+ setPopup(+ produce<DefinitionPopupState>((state) => reducePopup(state, action))+ );+ };++ return {+ root: createDefinitionView(root),+ popup: createDefinitionView(popup),+ getTerm: (id: string) => termData.get(id),+ commands: {+ dispatchRoot,+ dispatchPopup,+ loadTermXml: (xml: string) => {+ termData.load(xml);+ },+ },+ };+}++export type PdfDefinitions = ReturnType<typeof createPdfDefinitions>;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-document-model.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-document-model.test.tsnew file mode 100644index 0000000000..2d2fbb864c--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-document-model.test.ts@@ -0,0 +1,138 @@+import { createRoot } from 'solid-js';+import { describe, expect, it } from 'vitest';+import {+ type IModificationDataOnServer,+ transformModificationDataToServer,+} from '../type/coParse';+import {+ type IPlaceable,+ PayloadMode,+ type PayloadType,+} from '../type/placeables';+import {+ createPdfDocumentModel,+ type PdfDocumentModel,+} from './pdf-document-model';++function textPlaceable(text: string): IPlaceable {+ return {+ internalId: 'placeable-1',+ allowableEdits: {+ allowResize: true,+ allowTranslate: true,+ allowRotate: true,+ allowDelete: true,+ lockAspectRatio: false,+ },+ wasEdited: false,+ wasDeleted: false,+ pageRange: new Set([0]),+ position: {+ xPct: 0.1,+ yPct: 0.2,+ widthPct: 0.3,+ heightPct: 0.4,+ rotation: 0,+ },+ payload: {+ color: { red: 0, green: 0, blue: 0, alpha: 1 },+ fontSize: 10,+ bold: false,+ fontFamily: 'Times New Roman',+ text,+ italic: false,+ underlined: false,+ textType: 'pdf-text',+ },+ payloadType: PayloadMode.FreeTextAnnotation,+ shouldLockOnSave: false,+ originalPage: 0,+ originalIndex: -1,+ };+}++function withModel(run: (model: PdfDocumentModel) => void) {+ createRoot((dispose) => {+ try {+ run(createPdfDocumentModel());+ } finally {+ dispose();+ }+ });+}++describe('createPdfDocumentModel', () => {+ it('starts empty and hydrates the server baseline without recording an edit', () => {+ withModel((model) => {+ const snapshot = transformModificationDataToServer({+ bookmarks: [],+ pinnedTermsNames: ['defined term'],+ placeables: [textPlaceable('from server')],+ }) satisfies IModificationDataOnServer;++ expect(model.modificationData).toEqual({+ bookmarks: [],+ placeables: [],+ pinnedTermsNames: [],+ });+ expect(model.serverSnapshot()).toBeUndefined();+ expect(model.hasServerSnapshot()).toBe(false);+ expect(model.revision()).toBe(0);++ model.commands.hydrateFromServer(snapshot);++ expect(model.serverSnapshot()).toBe(snapshot);+ expect(model.hasServerSnapshot()).toBe(true);+ expect(model.modificationData.bookmarks).toEqual([]);+ expect(model.modificationData.pinnedTermsNames).toEqual(['defined term']);+ expect(model.modificationData.placeables).toHaveLength(1);+ expect(model.modificationData.placeables[0]?.payload).toMatchObject({+ text: 'from server',+ });+ expect(model.modificationData.placeables[0]?.internalId).toEqual(+ expect.any(String)+ );+ expect(model.revision()).toBe(0);+ });+ });++ it('owns placeable replacement, edits, deletion, and revision changes', () => {+ withModel((model) => {+ const original = textPlaceable('before');+ const updated = textPlaceable('after');+ const mismatched = {+ ...updated,+ payloadType: PayloadMode.Signature as PayloadType,+ } as IPlaceable;++ model.commands.appendPlaceable(original);+ expect(model.modificationData.placeables).toEqual([original]);+ expect(model.revision()).toBe(0);++ model.commands.replacePlaceables([original]);+ expect(model.modificationData.placeables).toEqual([original]);+ expect(model.revision()).toBe(0);++ expect(model.commands.updatePlaceable(-1, updated)).toBe(false);+ expect(model.commands.updatePlaceable(1, updated)).toBe(false);+ expect(model.commands.updatePlaceable(0, mismatched)).toBe(false);+ expect(model.commands.removePlaceable(-1)).toBe(false);+ expect(model.commands.removePlaceable(1)).toBe(false);+ expect(model.revision()).toBe(0);++ expect(model.commands.updatePlaceable(0, updated)).toBe(true);+ expect(model.modificationData.placeables[0]).toEqual({+ ...updated,+ wasEdited: true,+ });+ expect(model.revision()).toBe(1);++ expect(model.commands.removePlaceable(0)).toBe(true);+ expect(model.modificationData.placeables).toEqual([]);+ expect(model.revision()).toBe(2);++ model.commands.recordEdit();+ expect(model.revision()).toBe(3);+ });+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-document-model.ts b/apps/web/src/features/block-pdf/primitives/pdf-document-model.tsnew file mode 100644index 0000000000..01829f8d0b--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-document-model.ts@@ -0,0 +1,75 @@+import { createSignal } from 'solid-js';+import { createStore, reconcile } from 'solid-js/store';+import {+ type IModificationData,+ type IModificationDataOnServer,+ transformModificationDataToClient,+} from '../type/coParse';+import type { IPlaceable } from '../type/placeables';++export function createPdfDocumentModel() {+ const [modificationData, setModificationData] =+ createStore<IModificationData>({+ bookmarks: [],+ placeables: [],+ pinnedTermsNames: [],+ });+ const [serverSnapshot, setServerSnapshot] =+ createSignal<IModificationDataOnServer>();+ const [revision, setRevision] = createSignal(0);++ const commands = {+ hydrateFromServer(snapshot: IModificationDataOnServer) {+ setServerSnapshot(snapshot);+ setModificationData(+ reconcile(transformModificationDataToClient(snapshot))+ );+ },+ replacePlaceables(placeables: IPlaceable[]) {+ setModificationData('placeables', reconcile(placeables));+ },+ appendPlaceable(placeable: IPlaceable) {+ setModificationData('placeables', (previous) => [...previous, placeable]);+ },+ updatePlaceable(index: number, candidate: IPlaceable) {+ if (index < 0) return false;++ const current = modificationData.placeables.at(index);+ if (!current || candidate.payloadType !== current.payloadType) {+ return false;+ }++ setModificationData('placeables', index, {+ ...candidate,+ wasEdited: true,+ });+ setRevision((previous) => previous + 1);+ return true;+ },+ removePlaceable(index: number) {+ if (index < 0 || index >= modificationData.placeables.length) {+ return false;+ }++ setModificationData('placeables', (previous) => [+ ...previous.slice(0, index),+ ...previous.slice(index + 1),+ ]);+ setRevision((previous) => previous + 1);+ return true;+ },+ recordEdit() {+ setRevision((previous) => previous + 1);+ },+ };++ return {+ modificationData,+ serverSnapshot,+ revision,+ hasServerSnapshot: () => serverSnapshot() != null,+ commands,+ };+}++export type PdfDocumentModel = ReturnType<typeof createPdfDocumentModel>;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-markup.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-markup.test.tsnew file mode 100644index 0000000000..8887501a80--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-markup.test.ts@@ -0,0 +1,166 @@+import { createRoot } from 'solid-js';+import { describe, expect, it } from 'vitest';+import type { IPlaceable } from '../type/placeables';+import { PayloadMode } from '../type/placeables';+import { createPdfMarkup, type PdfMarkup } from './pdf-markup';++function textPlaceable(id: string, xPct: number): IPlaceable {+ return {+ internalId: id,+ allowableEdits: {+ allowResize: true,+ allowTranslate: true,+ allowRotate: true,+ allowDelete: true,+ lockAspectRatio: false,+ },+ wasEdited: false,+ wasDeleted: false,+ pageRange: new Set([0]),+ position: {+ xPct,+ yPct: 0.2,+ widthPct: 0.3,+ heightPct: 0.4,+ rotation: 0,+ },+ payload: {+ color: { red: 0, green: 0, blue: 0, alpha: 1 },+ fontSize: 10,+ bold: false,+ fontFamily: 'Times New Roman',+ text: 'draft',+ italic: false,+ underlined: false,+ textType: 'pdf-text',+ },+ payloadType: PayloadMode.FreeTextAnnotation,+ shouldLockOnSave: false,+ originalPage: 0,+ originalIndex: -1,+ };+}++function setup(): {+ markup: PdfMarkup;+ dispose: () => void;+} {+ return createRoot((dispose) => ({+ markup: createPdfMarkup(),+ dispose,+ }));+}++describe('createPdfMarkup', () => {+ it('coordinates placement, activation, drafts, and drag state', () => {+ const { markup, dispose } = setup();+ const firstDraft = textPlaceable('draft-1', 0.1);+ const movedDraft = textPlaceable('draft-1', 0.6);++ expect({+ mode: markup.mode(),+ activeId: markup.activeId(),+ draft: markup.draft(),+ dragActive: markup.dragActive(),+ }).toEqual({+ mode: PayloadMode.NoMode,+ activeId: undefined,+ draft: undefined,+ dragActive: false,+ });++ markup.commands.beginPlacement(PayloadMode.Signature);+ markup.commands.activate('draft-1');+ markup.commands.setDraft(firstDraft);+ markup.commands.setDraft(movedDraft);+ markup.commands.setDragActive(true);++ expect({+ mode: markup.mode(),+ activeId: markup.activeId(),+ draft: markup.draft(),+ dragActive: markup.dragActive(),+ }).toEqual({+ mode: PayloadMode.Signature,+ activeId: 'draft-1',+ draft: movedDraft,+ dragActive: true,+ });++ markup.commands.cancelPlacement();+ markup.commands.clearActive();+ markup.commands.clearDraft();+ markup.commands.setDragActive(false);++ expect({+ mode: markup.mode(),+ activeId: markup.activeId(),+ draft: markup.draft(),+ dragActive: markup.dragActive(),+ }).toEqual({+ mode: PayloadMode.NoMode,+ activeId: undefined,+ draft: undefined,+ dragActive: false,+ });+ dispose();+ });++ it('clears active and draft values only when ids match', () => {+ const { markup, dispose } = setup();+ const draft = textPlaceable('draft-1', 0.1);++ markup.commands.activate('draft-1');+ markup.commands.setDraft(draft);+ markup.commands.clearActiveIf('other');+ markup.commands.clearDraftIf('other');++ expect({+ activeId: markup.activeId(),+ draft: markup.draft(),+ }).toEqual({+ activeId: 'draft-1',+ draft,+ });++ markup.commands.clearActiveIf('draft-1');+ markup.commands.clearDraftIf('draft-1');++ expect({+ activeId: markup.activeId(),+ draft: markup.draft(),+ }).toEqual({+ activeId: undefined,+ draft: undefined,+ });+ dispose();+ });++ it('isolates markup authorities', () => {+ const first = setup();+ const second = setup();++ first.markup.commands.beginPlacement(PayloadMode.Thread);+ first.markup.commands.activate('draft-1');+ first.markup.commands.setDraft(textPlaceable('draft-1', 0.1));+ first.markup.commands.setDragActive(true);++ expect({+ firstMode: first.markup.mode(),+ firstActiveId: first.markup.activeId(),+ secondMode: second.markup.mode(),+ secondActiveId: second.markup.activeId(),+ secondDraft: second.markup.draft(),+ secondDragActive: second.markup.dragActive(),+ }).toEqual({+ firstMode: PayloadMode.Thread,+ firstActiveId: 'draft-1',+ secondMode: PayloadMode.NoMode,+ secondActiveId: undefined,+ secondDraft: undefined,+ secondDragActive: false,+ });+ first.dispose();+ second.dispose();+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-markup.ts b/apps/web/src/features/block-pdf/primitives/pdf-markup.tsnew file mode 100644index 0000000000..4b55bd4e43--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-markup.ts@@ -0,0 +1,55 @@+import { createSignal } from 'solid-js';+import {+ type IPlaceable,+ PayloadMode,+ type PayloadType,+} from '../type/placeables';++type PlacementMode = Exclude<PayloadType, typeof PayloadMode.NoMode>;++export function createPdfMarkup() {+ const [mode, setMode] = createSignal<PayloadType>(PayloadMode.NoMode);+ const [activeId, setActiveId] = createSignal<string>();+ const [draft, setDraft] = createSignal<IPlaceable>();+ const [dragActive, setDragActive] = createSignal(false);++ const commands = {+ beginPlacement(nextMode: PlacementMode) {+ setMode(nextMode);+ },+ cancelPlacement() {+ setMode(PayloadMode.NoMode);+ },+ activate(id: string) {+ setActiveId(id);+ },+ clearActive() {+ setActiveId(undefined);+ },+ clearActiveIf(id: string) {+ setActiveId((activeId) => (activeId === id ? undefined : activeId));+ },+ setDraft(placeable: IPlaceable) {+ setDraft(placeable);+ },+ clearDraft() {+ setDraft(undefined);+ },+ clearDraftIf(id: string) {+ setDraft((draft) => (draft?.internalId === id ? undefined : draft));+ },+ setDragActive(active: boolean) {+ setDragActive(active);+ },+ };++ return {+ mode,+ activeId,+ draft,+ dragActive,+ commands,+ };+}++export type PdfMarkup = ReturnType<typeof createPdfMarkup>;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-outline.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-outline.test.tsnew file mode 100644index 0000000000..b0aeb57153--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-outline.test.ts@@ -0,0 +1,170 @@+/**+ * @vitest-environment jsdom+ */+import { createRoot } from 'solid-js';+import { describe, expect, it } from 'vitest';+import type Section from '../model/Section';+import type { ICoParse } from '../type/coParse';+import TocUtils from '../util/TocUtils';+import { createPdfOutline, type PdfOutline } from './pdf-outline';++function setup(): { outline: PdfOutline; dispose: () => void } {+ return createRoot((dispose) => ({+ outline: createPdfOutline(),+ dispose,+ }));+}++function coparse(toc: string) {+ return { toc } as ICoParse;+}++function sectionMapSnapshot(map: Partial<Record<number, Section>>) {+ return Object.values(map)+ .filter((section): section is Section => section != null)+ .map((section) => ({+ id: section.id,+ page: section.page,+ y: section.y,+ title: section.title,+ }));+}++const firstToc = `+ <document>+ <section+ id="10"+ title="Root section"+ literal="1"+ page="0"+ y="12.5"+ qualified="1 Root section"+ show="true"+ type="SECTION"+ >+ <section+ id="11"+ title="Nested section"+ literal="1.1"+ page="1"+ y="33.25"+ qualified="1.1 Nested section"+ show="true"+ type="SECTION"+ >+ <reference />+ </section>+ </section>+ </document>+`;++const replacementToc = `+ <document>+ <section+ id="20"+ title="Replacement section"+ literal="2"+ page="2"+ y="48.75"+ qualified="2 Replacement section"+ show="true"+ type="SECTION"+ />+ </document>+`;++describe('createPdfOutline', () => {+ it('loads the section-reference map', () => {+ const { outline, dispose } = setup();++ expect(outline.sectionReferenceMap()).toEqual({});++ outline.commands.loadCoparse(coparse(firstToc));++ expect(sectionMapSnapshot(outline.sectionReferenceMap())).toEqual([+ {+ id: 10,+ page: 0,+ y: 12.5,+ title: 'Root section',+ },+ {+ id: 11,+ page: 1,+ y: 33.25,+ title: 'Nested section',+ },+ ]);++ const rootSection = outline.sectionReferenceMap()[10]!;+ expect({+ id: rootSection.id,+ title: rootSection.title,+ literal: rootSection.literal,+ page: rootSection.page,+ y: rootSection.y,+ qualified: rootSection.qualified,+ type: rootSection.type,+ fullTitle: rootSection.fullTitle,+ numRefs: rootSection.numRefs,+ showBookmark: rootSection.showBookmark,+ bookmarkTitle: rootSection.bookmarkTitle,+ }).toEqual({+ id: 10,+ title: 'Root section',+ literal: '1',+ page: 0,+ y: 12.5,+ qualified: '1 Root section',+ type: 'SECTION',+ fullTitle: 'Root section',+ numRefs: 1,+ showBookmark: true,+ bookmarkTitle: ' 1 Root section: Root Section',+ });++ expect(+ TocUtils.getNearestSection({+ page: 1,+ yPos: 30,+ idToSectionMap: outline.sectionReferenceMap(),+ })?.id+ ).toBe(10);+ expect(+ TocUtils.getNearestSection({+ page: 1,+ yPos: 34,+ idToSectionMap: outline.sectionReferenceMap(),+ })?.id+ ).toBe(11);+ expect(+ TocUtils.getNearestSection({+ page: 0,+ yPos: 10,+ idToSectionMap: outline.sectionReferenceMap(),+ })+ ).toBeNull();+ dispose();+ });++ it('replaces stale AI section IDs and isolates outline instances', () => {+ const first = setup();+ const second = setup();++ first.outline.commands.loadCoparse(coparse(firstToc));+ first.outline.commands.loadCoparse(coparse(replacementToc));++ expect(sectionMapSnapshot(first.outline.sectionReferenceMap())).toEqual([+ {+ id: 20,+ page: 2,+ y: 48.75,+ title: 'Replacement section',+ },+ ]);+ expect(second.outline.sectionReferenceMap()).toEqual({});++ first.dispose();+ second.dispose();+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-outline.ts b/apps/web/src/features/block-pdf/primitives/pdf-outline.tsnew file mode 100644index 0000000000..32249c7ea2--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-outline.ts@@ -0,0 +1,76 @@+import { createSignal } from 'solid-js';+import Section from '../model/Section';+import type { ICoParse } from '../type/coParse';+import { XMLUtils } from '../util/XMLUtils';++function addSectionReference(+ node: Element,+ mapping: Partial<Record<number, Section>>+): void {+ const id = node.getAttribute('id') || '';+ const title = node.getAttribute('title') || '';+ const literal = node.getAttribute('literal');+ const page = parseInt(node.getAttribute('page') || '');+ const y = parseFloat(node.getAttribute('y') || '');+ const qualified = node.getAttribute('qualified') || '';+ const numRefs = node.getElementsByTagName('reference').length;+ const type = Section.parseSegmentType(node.getAttribute('type'));+ const fullTitle = Section.getFullTitle(node);++ const showBookmark =+ !node.getAttribute('show') || node.getAttribute('show') === 'true';+ const bookmarkTitle = node.getAttribute('bookmark');++ const idNum = parseInt(id, 10);++ if (isNaN(idNum)) {+ console.error('Invalid section ID');+ }++ const section = new Section({+ id: idNum,+ title,+ literal,+ page,+ y,+ qualified,+ type,+ fullTitle,+ numRefs,+ showBookmark,+ bookmarkTitle,+ });++ mapping[section.id] = section;+ for (const child of node.children) {+ if (child.tagName === 'section') {+ addSectionReference(child, mapping);+ }+ }+}++export type PdfOutline = ReturnType<typeof createPdfOutline>;++export function createPdfOutline() {+ const [sectionReferenceMap, setSectionReferenceMap] = createSignal<+ Partial<Record<number, Section>>+ >({});++ return {+ sectionReferenceMap,+ commands: {+ loadCoparse(coparse: ICoParse) {+ const firstChild = XMLUtils.parse(coparse.toc || '').firstChild as+ | Element+ | undefined;+ const mapping: Partial<Record<number, Section>> = {};+ for (const child of firstChild?.children ?? []) {+ if (child.tagName === 'section') {+ addSectionReference(child, mapping);+ }+ }+ setSectionReferenceMap(mapping);+ },+ },+ };+}diff --git a/apps/web/src/features/block-pdf/primitives/pdf-persistence.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-persistence.test.tsnew file mode 100644index 0000000000..06957fa5f8--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-persistence.test.ts@@ -0,0 +1,108 @@+import { createRoot } from 'solid-js';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createPdfPersistence, type PdfPersistence } from './pdf-persistence';++function createDeferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((resolvePromise) => {+ resolve = resolvePromise;+ });+ return { promise, resolve };+}++function setup(): {+ persistence: PdfPersistence;+ dispose: () => void;+} {+ return createRoot((dispose) => ({+ persistence: createPdfPersistence(),+ dispose,+ }));+}++afterEach(() => {+ vi.restoreAllMocks();+});++describe('createPdfPersistence', () => {+ it('skips saves that are not required', async () => {+ const { persistence, dispose } = setup();+ let saves = 0;++ await persistence.runSave(+ async () => {+ saves += 1;+ },+ () => false+ );++ expect({ saves, isSaving: persistence.isSaving() }).toEqual({+ saves: 0,+ isSaving: false,+ });+ dispose();+ });++ it('tracks one save until it settles', async () => {+ const { persistence, dispose } = setup();+ const deferred = createDeferred();++ const saving = persistence.runSave(+ () => deferred.promise,+ () => true+ );+ expect(persistence.isSaving()).toBe(true);++ deferred.resolve();+ await saving;++ expect(persistence.isSaving()).toBe(false);+ dispose();+ });++ it('stays saving until two overlapping saves settle', async () => {+ const { persistence, dispose } = setup();+ const first = createDeferred();+ const second = createDeferred();++ const firstSaving = persistence.runSave(+ () => first.promise,+ () => true+ );+ const secondSaving = persistence.runSave(+ () => second.promise,+ () => true+ );+ expect(persistence.isSaving()).toBe(true);++ first.resolve();+ await firstSaving;+ expect(persistence.isSaving()).toBe(true);++ second.resolve();+ await secondSaving;+ expect(persistence.isSaving()).toBe(false);+ dispose();+ });++ it('logs rejected saves and clears saving state without rejecting', async () => {+ const { persistence, dispose } = setup();+ const error = new Error('save failed');+ const consoleError = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});++ await expect(+ persistence.runSave(+ async () => {+ throw error;+ },+ () => true+ )+ ).resolves.toBeUndefined();++ expect(consoleError).toHaveBeenCalledWith('Error saving PDF', error);+ expect(persistence.isSaving()).toBe(false);+ dispose();+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-persistence.ts b/apps/web/src/features/block-pdf/primitives/pdf-persistence.tsnew file mode 100644index 0000000000..007b2a0bad--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-persistence.ts@@ -0,0 +1,33 @@+import type { Accessor } from 'solid-js';+import { createSignal } from 'solid-js';++export function createPdfPersistence() {+ const [savingCount, setSavingCount] = createSignal(0);+ const isSaving: Accessor<boolean> = () => savingCount() > 0;++ const runSave = async (+ save: () => Promise<void>,+ shouldSave: () => boolean+ ) => {+ let saving = false;+ try {+ if (!shouldSave()) return;+ saving = true;+ setSavingCount((previous) => previous + 1);+ await save();+ } catch (error) {+ console.error('Error saving PDF', error);+ } finally {+ if (saving) {+ setSavingCount((previous) => previous - 1);+ }+ }+ };++ return {+ isSaving,+ runSave,+ };+}++export type PdfPersistence = ReturnType<typeof createPdfPersistence>;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-tabs.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-tabs.test.tsnew file mode 100644index 0000000000..e887694a61--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-tabs.test.ts@@ -0,0 +1,147 @@+import { createRoot } from 'solid-js';+import { describe, expect, it } from 'vitest';+import { createPdfTabs, type PdfTabs } from './pdf-tabs';++function setup(): {+ tabs: PdfTabs;+ dispose: () => void;+} {+ return createRoot((dispose) => ({+ tabs: createPdfTabs(),+ dispose,+ }));+}++describe('createPdfTabs', () => {+ it('starts with one hidden active tab', () => {+ const { tabs, dispose } = setup();++ expect({+ items: tabs.items,+ activeId: tabs.activeId(),+ isVisible: tabs.isVisible(),+ count: tabs.count(),+ }).toEqual({+ items: [{ id: 0, label: 'Page 1', locationHash: '#page=1' }],+ activeId: 0,+ isVisible: false,+ count: 1,+ });+ dispose();+ });++ it('creates monotonically numbered tabs and controls visibility', () => {+ const { tabs, dispose } = setup();++ const firstId = tabs.commands.create({+ label: 'Page 2',+ locationHash: '#page=2',+ });+ const secondId = tabs.commands.create({+ label: 'Page 3',+ locationHash: '#page=3',+ });+ tabs.commands.remove(secondId);+ const thirdId = tabs.commands.create({+ label: 'Page 4',+ locationHash: '#page=4',+ });++ expect({+ ids: tabs.items.map((tab) => tab.id),+ createdIds: [firstId, secondId, thirdId],+ isVisible: tabs.isVisible(),+ count: tabs.count(),+ }).toEqual({+ ids: [0, 1, 3],+ createdIds: [1, 2, 3],+ isVisible: true,+ count: 3,+ });++ tabs.commands.toggleVisibility();+ expect(tabs.isVisible()).toBe(false);+ dispose();+ });++ it('owns activation history, metadata updates, and removal targets', () => {+ const { tabs, dispose } = setup();+ const firstId = tabs.commands.create({+ label: 'Page 2',+ locationHash: '#page=2',+ });+ const secondId = tabs.commands.create({+ label: 'Page 3',+ locationHash: '#page=3',+ });++ expect(tabs.commands.activate(firstId)).toBe(true);+ expect(tabs.commands.activate(99)).toBe(false);+ tabs.commands.updateCurrent({+ label: 'Page 4',+ locationHash: '#page=4',+ });+ tabs.commands.updateCurrent({+ label: 'Page 5',+ locationHash: '',+ });++ expect(tabs.items.find((tab) => tab.id === firstId)).toEqual({+ id: firstId,+ label: 'Page 5',+ locationHash: '#page=4',+ });++ expect(tabs.commands.activate(secondId)).toBe(true);+ expect(tabs.commands.remove(secondId)).toBe(firstId);+ expect(tabs.commands.activate(firstId)).toBe(true);+ expect(tabs.commands.remove(firstId)).toBe(0);+ expect(tabs.items).toEqual([+ { id: 0, label: 'Page 1', locationHash: '#page=1' },+ ]);+ dispose();+ });++ it('falls back to the first remaining tab when history is removed', () => {+ const { tabs, dispose } = setup();+ const firstId = tabs.commands.create({+ label: 'Page 2',+ locationHash: '#page=2',+ });+ tabs.commands.create({+ label: 'Page 3',+ locationHash: '#page=3',+ });++ expect(tabs.commands.remove(0)).toBe(firstId);+ expect(tabs.items.map((tab) => tab.id)).toEqual([1, 2]);+ dispose();+ });++ it('isolates tab authorities', () => {+ const first = setup();+ const second = setup();++ first.tabs.commands.create({+ label: 'Page 2',+ locationHash: '#page=2',+ });+ first.tabs.commands.activate(1);++ expect({+ firstCount: first.tabs.count(),+ firstActiveId: first.tabs.activeId(),+ secondCount: second.tabs.count(),+ secondActiveId: second.tabs.activeId(),+ secondVisible: second.tabs.isVisible(),+ }).toEqual({+ firstCount: 2,+ firstActiveId: 1,+ secondCount: 1,+ secondActiveId: 0,+ secondVisible: false,+ });+ first.dispose();+ second.dispose();+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-tabs.ts b/apps/web/src/features/block-pdf/primitives/pdf-tabs.tsnew file mode 100644index 0000000000..9f53cf8f2b--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-tabs.ts@@ -0,0 +1,72 @@+import { createSignal } from 'solid-js';+import { createStore } from 'solid-js/store';++export type TabInfo = {+ label: string;+ locationHash?: string;+ id: number;+};++const initialTab = (): TabInfo => ({+ id: 0,+ label: 'Page 1',+ locationHash: '#page=1',+});++export function createPdfTabs() {+ const [items, setItems] = createStore<TabInfo[]>([initialTab()]);+ const [activeId, setActiveId] = createSignal(0);+ const [isVisible, setIsVisible] = createSignal(false);+ let nextId = 0;+ let history = [0];++ const commands = {+ create(info: Omit<TabInfo, 'id'>) {+ nextId += 1;+ const id = nextId;+ setItems([...items, { ...info, id }]);+ setIsVisible(true);+ return id;+ },+ activate(id: number) {+ if (!items.some((tab) => tab.id === id)) return false;+ setActiveId(id);+ history = [...history, id];+ return true;+ },+ updateCurrent(info: Omit<TabInfo, 'id'>) {+ const index = items.findIndex((tab) => tab.id === activeId());+ if (index === -1) return false;++ setItems(index, 'label', info.label);+ if (info.locationHash) {+ setItems(index, 'locationHash', info.locationHash);+ }+ return true;+ },+ remove(id: number) {+ const remaining = items.filter((tab) => tab.id !== id);+ setItems(remaining);+ history = history.filter((tabId) => tabId !== id);++ if (history.length === 0 && remaining.length > 0) {+ history = [remaining[0].id];+ }++ return history.at(-1) ?? remaining[0]?.id ?? 0;+ },+ toggleVisibility() {+ setIsVisible((visible) => !visible);+ },+ };++ return {+ items,+ activeId,+ isVisible,+ count: () => items.length,+ commands,+ };+}++export type PdfTabs = ReturnType<typeof createPdfTabs>;diff --git a/apps/web/src/features/block-pdf/primitives/pdf-viewer-runtime.test.ts b/apps/web/src/features/block-pdf/primitives/pdf-viewer-runtime.test.tsnew file mode 100644index 0000000000..0c7aec6f5d--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-viewer-runtime.test.ts@@ -0,0 +1,345 @@+import type { PDFPageView } from 'pdfjs-dist/web/pdf_viewer';+import { createComputed, createRoot } from 'solid-js';+import { describe, expect, it } from 'vitest';+import type { PDFViewer } from '../PdfViewer';+import {+ createEventBus,+ FindState,+ type IVisiblePage,+ type TEvents,+} from '../PdfViewer/EventBus';+import {+ createPdfViewerRuntime,+ type PdfViewerRuntime,+} from './pdf-viewer-runtime';++function createViewer() {+ return { event: createEventBus() } as unknown as PDFViewer;+}++function updateViewArea(pageNumber: number): TEvents['updateviewarea'] {+ const page = {+ id: pageNumber,+ x: 0,+ y: 0,+ view: {} as IVisiblePage['view'],+ percent: 100,+ widthPercent: 100,+ };+ return {+ source: {},+ location: {+ pageNumber,+ scale: 1,+ top: 0,+ left: 0,+ rotation: 0,+ pdfOpenParams: '',+ unscaledYPos: 0,+ viewportScale: 1,+ },+ visiblePages: {+ first: page,+ last: page,+ views: [page],+ ids: new Set([pageNumber]),+ },+ };+}++function overlayViews(+ pages: Array<{ id: number; height: number }>+): TEvents['overlayViewsChanged'] {+ return {+ views: pages.map(+ ({ id, height }) =>+ ({+ id,+ viewport: { height },+ }) as unknown as PDFPageView+ ),+ };+}++function setup(): {+ viewer: PdfViewerRuntime;+ snapshots: Array<{+ root: PDFViewer | undefined;+ popup: PDFViewer | undefined;+ }>;+ dispose: () => void;+} {+ return createRoot((dispose) => {+ const viewer = createPdfViewerRuntime();+ const snapshots: Array<{+ root: PDFViewer | undefined;+ popup: PDFViewer | undefined;+ }> = [];+ createComputed(() => {+ snapshots.push({+ root: viewer.root.instance(),+ popup: viewer.popup.instance(),+ });+ });+ return { viewer, snapshots, dispose };+ });+}++describe('createPdfViewerRuntime', () => {+ it('installs and clears the viewer pair atomically', () => {+ const { viewer, snapshots, dispose } = setup();+ const root = createViewer();+ const popup = createViewer();++ viewer.installPair({ root, popup });+ viewer.detachListeners();+ viewer.clearPair();++ expect(snapshots).toEqual([+ { root: undefined, popup: undefined },+ { root, popup },+ { root: undefined, popup: undefined },+ ]);+ dispose();+ });++ it('owns one shared overlay value', () => {+ const { viewer, dispose } = setup();+ const overlays = ['overlay-1', 'overlay-2'];++ expect(viewer.overlays()).toBeUndefined();+ viewer.replaceOverlays(overlays);++ expect(viewer.overlays()).toBe(overlays);+ dispose();+ });++ it('projects root and popup events into separate domain state', () => {+ const { viewer, dispose } = setup();+ const root = createViewer();+ const popup = createViewer();+ const rootOverlayViews = overlayViews([+ { id: 1, height: 720 },+ { id: 3, height: 900 },+ ]);+ const popupOverlayViews = overlayViews([{ id: 2, height: 400 }]);+ const rootViewArea = updateViewArea(3);+ const popupViewArea = updateViewArea(2);+ const findControlState = {+ source: {},+ matchesCount: { current: 1, total: 2 },+ state: FindState.FOUND,+ previous: false,+ rawQuery: 'query',+ } as TEvents['updatefindcontrolstate'];+ const findMatchesCount = {+ source: {},+ matchesCount: { current: 2, total: 2 },+ } as TEvents['updatefindmatchescount'];+ viewer.installPair({ root, popup });++ root.event.dispatch('pagesloaded', { source: {}, pagesCount: 8 });+ root.event.dispatch('pagechanging', {+ source: {},+ pageNumber: 3,+ previous: 2,+ pageLabel: null,+ });+ root.event.dispatch('scalechanging', {+ source: {},+ scale: 1,+ presetValue: undefined,+ });+ root.event.dispatch('overlayViewsChanged', rootOverlayViews);+ root.event.dispatch('updateviewarea', rootViewArea);+ root.event.dispatch('updatefindcontrolstate', findControlState);+ root.event.dispatch('updatefindmatchescount', findMatchesCount);+ root.event.dispatch('popupvisibilitychanged', {+ source: {},+ isOpen: true,+ target: document.createElement('div'),+ });++ popup.event.dispatch('pagechanging', {+ source: {},+ pageNumber: 2,+ previous: 1,+ pageLabel: null,+ });+ popup.event.dispatch('scalechanging', {+ source: {},+ scale: 1.5,+ presetValue: undefined,+ });+ popup.event.dispatch('overlayViewsChanged', popupOverlayViews);+ popup.event.dispatch('updateviewarea', popupViewArea);++ expect({+ rootPage: viewer.root.currentPageNumber(),+ rootScale: viewer.root.currentScale(),+ rootPageCount: viewer.root.pageCount(),+ rootReady: viewer.root.isReady(),+ rootVisible: viewer.root.hasVisiblePages(),+ canZoomIn: viewer.root.canZoomIn(),+ canZoomOut: viewer.root.canZoomOut(),+ popupPage: viewer.popup.currentPageNumber(),+ popupScale: viewer.popup.currentScale(),+ popupOpen: viewer.isPopupOpen(),+ }).toEqual({+ rootPage: 3,+ rootScale: 1,+ rootPageCount: 8,+ rootReady: true,+ rootVisible: true,+ canZoomIn: true,+ canZoomOut: true,+ popupPage: 2,+ popupScale: 1.5,+ popupOpen: true,+ });+ expect(viewer.root.overlayViews()).toBe(rootOverlayViews);+ expect(viewer.root.viewArea()).toBe(rootViewArea);+ expect(viewer.root.findControlState()).toBe(findControlState);+ expect(viewer.root.findMatchesCount()).toBe(findMatchesCount);+ expect(viewer.root.pageHeights).toEqual({ 0: 720, 2: 900 });+ expect(viewer.popup.overlayViews()).toBe(popupOverlayViews);+ expect(viewer.popup.viewArea()).toBe(popupViewArea);+ dispose();+ });++ it('detaches listeners, resets projections, and retains page heights', () => {+ const { viewer, dispose } = setup();+ const root = createViewer();+ const popup = createViewer();+ const rootOverlayViews = overlayViews([{ id: 2, height: 640 }]);+ viewer.installPair({ root, popup });+ root.event.dispatch('pagesloaded', { source: {}, pagesCount: 4 });+ root.event.dispatch('pagechanging', {+ source: {},+ pageNumber: 2,+ previous: 1,+ pageLabel: null,+ });+ root.event.dispatch('scalechanging', {+ source: {},+ scale: 1,+ presetValue: undefined,+ });+ root.event.dispatch('overlayViewsChanged', rootOverlayViews);+ root.event.dispatch('updateviewarea', updateViewArea(2));+ root.event.dispatch('updatefindcontrolstate', {+ source: {},+ matchesCount: { current: 0, total: 0 },+ state: FindState.PENDING,+ previous: false,+ rawQuery: 'query',+ } as TEvents['updatefindcontrolstate']);+ root.event.dispatch('updatefindmatchescount', {+ source: {},+ matchesCount: { current: 0, total: 0 },+ } as TEvents['updatefindmatchescount']);+ root.event.dispatch('popupvisibilitychanged', {+ source: {},+ isOpen: true,+ target: document.createElement('div'),+ });+ popup.event.dispatch('pagechanging', {+ source: {},+ pageNumber: 3,+ previous: 2,+ pageLabel: null,+ });+ popup.event.dispatch('scalechanging', {+ source: {},+ scale: 2,+ presetValue: undefined,+ });+ popup.event.dispatch(+ 'overlayViewsChanged',+ overlayViews([{ id: 1, height: 300 }])+ );+ popup.event.dispatch('updateviewarea', updateViewArea(1));++ viewer.detachListeners();++ root.event.dispatch('pagesloaded', { source: {}, pagesCount: 99 });+ popup.event.dispatch('pagechanging', {+ source: {},+ pageNumber: 99,+ previous: 3,+ pageLabel: null,+ });++ expect({+ rootInstance: viewer.root.instance(),+ popupInstance: viewer.popup.instance(),+ rootPage: viewer.root.currentPageNumber(),+ rootScale: viewer.root.currentScale(),+ rootPageCount: viewer.root.pageCount(),+ rootReady: viewer.root.isReady(),+ rootVisible: viewer.root.hasVisiblePages(),+ rootOverlayViews: viewer.root.overlayViews(),+ rootViewArea: viewer.root.viewArea(),+ rootFindControlState: viewer.root.findControlState(),+ rootFindMatchesCount: viewer.root.findMatchesCount(),+ popupPage: viewer.popup.currentPageNumber(),+ popupScale: viewer.popup.currentScale(),+ popupOverlayViews: viewer.popup.overlayViews(),+ popupViewArea: viewer.popup.viewArea(),+ popupOpen: viewer.isPopupOpen(),+ pageHeights: viewer.root.pageHeights,+ }).toEqual({+ rootInstance: root,+ popupInstance: popup,+ rootPage: 1,+ rootScale: undefined,+ rootPageCount: undefined,+ rootReady: false,+ rootVisible: false,+ rootOverlayViews: undefined,+ rootViewArea: undefined,+ rootFindControlState: undefined,+ rootFindMatchesCount: undefined,+ popupPage: 1,+ popupScale: undefined,+ popupOverlayViews: undefined,+ popupViewArea: undefined,+ popupOpen: false,+ pageHeights: { 1: 640 },+ });+ dispose();+ });++ it('isolates viewer runtimes', () => {+ const first = setup();+ const second = setup();+ const root = createViewer();+ const popup = createViewer();++ first.viewer.installPair({ root, popup });+ first.viewer.replaceOverlays(['overlay-1']);+ root.event.dispatch('pagesloaded', { source: {}, pagesCount: 2 });++ expect({+ firstRoot: first.viewer.root.instance(),+ firstPopup: first.viewer.popup.instance(),+ firstOverlays: first.viewer.overlays(),+ firstReady: first.viewer.root.isReady(),+ secondRoot: second.viewer.root.instance(),+ secondPopup: second.viewer.popup.instance(),+ secondOverlays: second.viewer.overlays(),+ secondReady: second.viewer.root.isReady(),+ }).toEqual({+ firstRoot: root,+ firstPopup: popup,+ firstOverlays: ['overlay-1'],+ firstReady: true,+ secondRoot: undefined,+ secondPopup: undefined,+ secondOverlays: undefined,+ secondReady: false,+ });+ first.dispose();+ second.dispose();+ });+});diff --git a/apps/web/src/features/block-pdf/primitives/pdf-viewer-runtime.ts b/apps/web/src/features/block-pdf/primitives/pdf-viewer-runtime.tsnew file mode 100644index 0000000000..62a1d8b2b2--- /dev/null+++ b/apps/web/src/features/block-pdf/primitives/pdf-viewer-runtime.ts@@ -0,0 +1,194 @@+import { batch, createSignal } from 'solid-js';+import { createStore, reconcile } from 'solid-js/store';+import type { PDFViewer } from '../PdfViewer';+import type { TEvents } from '../PdfViewer/EventBus';+import { ZOOM_MAX, ZOOM_MIN } from '../PdfViewer/zoom';++type ViewerPair = {+ root: PDFViewer;+ popup: PDFViewer;+};++export function createPdfViewerRuntime() {+ const [pair, setPair] = createSignal<ViewerPair>();+ const [overlays, setOverlays] = createSignal<string[]>();+ const [rootCurrentPageNumber, setRootCurrentPageNumber] = createSignal(1);+ const [rootCurrentScale, setRootCurrentScale] = createSignal<number>();+ const [rootPageCount, setRootPageCount] = createSignal<number>();+ const [rootOverlayViews, setRootOverlayViews] =+ createSignal<TEvents['overlayViewsChanged']>();+ const [rootViewArea, setRootViewArea] =+ createSignal<TEvents['updateviewarea']>();+ const [rootFindControlState, setRootFindControlState] =+ createSignal<TEvents['updatefindcontrolstate']>();+ const [rootFindMatchesCount, setRootFindMatchesCount] =+ createSignal<TEvents['updatefindmatchescount']>();+ const [rootPageHeights, setRootPageHeights] = createStore<+ Partial<Record<number, number>>+ >({});+ const [popupCurrentPageNumber, setPopupCurrentPageNumber] = createSignal(1);+ const [popupCurrentScale, setPopupCurrentScale] = createSignal<number>();+ const [popupOverlayViews, setPopupOverlayViews] =+ createSignal<TEvents['overlayViewsChanged']>();+ const [popupViewArea, setPopupViewArea] =+ createSignal<TEvents['updateviewarea']>();+ const [isPopupOpen, setIsPopupOpen] = createSignal(false);++ const onRootPagesLoaded = (event: TEvents['pagesloaded']) => {+ setRootPageCount(event.pagesCount);+ };+ const onRootScaleChanging = (event: TEvents['scalechanging']) => {+ setRootCurrentScale(event.scale);+ };+ const onRootPageChanging = (event: TEvents['pagechanging']) => {+ setRootCurrentPageNumber(event.pageNumber);+ };+ const onRootOverlayViewsChanged = (event: TEvents['overlayViewsChanged']) => {+ const updated: Partial<Record<number, number>> = {};+ for (const pageView of event.views) {+ updated[pageView.id - 1] = pageView.viewport.height;+ }+ batch(() => {+ setRootOverlayViews(event);+ setRootPageHeights(reconcile(updated));+ });+ };+ const onPopupVisibilityChanged = (+ event: TEvents['popupvisibilitychanged']+ ) => {+ setIsPopupOpen(event.isOpen);+ };+ const onRootViewArea = (event: TEvents['updateviewarea']) => {+ setRootViewArea(event);+ };+ const onRootFindControlState = (event: TEvents['updatefindcontrolstate']) => {+ setRootFindControlState(event);+ };+ const onRootFindMatchesCount = (event: TEvents['updatefindmatchescount']) => {+ setRootFindMatchesCount(event);+ };+ const onPopupScaleChanging = (event: TEvents['scalechanging']) => {+ setPopupCurrentScale(event.scale);+ };+ const onPopupPageChanging = (event: TEvents['pagechanging']) => {+ setPopupCurrentPageNumber(event.pageNumber);+ };+ const onPopupOverlayViewsChanged = (+ event: TEvents['overlayViewsChanged']+ ) => {+ setPopupOverlayViews(event);+ };+ const onPopupViewArea = (event: TEvents['updateviewarea']) => {+ setPopupViewArea(event);+ };++ const attachRootListeners = (viewer: PDFViewer) => {+ viewer.event.on('pagesloaded', onRootPagesLoaded);+ viewer.event.on('scalechanging', onRootScaleChanging);+ viewer.event.on('pagechanging', onRootPageChanging);+ viewer.event.on('overlayViewsChanged', onRootOverlayViewsChanged);+ viewer.event.on('popupvisibilitychanged', onPopupVisibilityChanged);+ viewer.event.on('updateviewarea', onRootViewArea);+ viewer.event.on('updatefindcontrolstate', onRootFindControlState);+ viewer.event.on('updatefindmatchescount', onRootFindMatchesCount);+ };++ const attachPopupListeners = (viewer: PDFViewer) => {+ viewer.event.on('scalechanging', onPopupScaleChanging);+ viewer.event.on('pagechanging', onPopupPageChanging);+ viewer.event.on('overlayViewsChanged', onPopupOverlayViewsChanged);+ viewer.event.on('updateviewarea', onPopupViewArea);+ };++ const detachPopupListeners = (viewer: PDFViewer) => {+ viewer.event.off('scalechanging', onPopupScaleChanging);+ viewer.event.off('pagechanging', onPopupPageChanging);+ viewer.event.off('overlayViewsChanged', onPopupOverlayViewsChanged);+ viewer.event.off('updateviewarea', onPopupViewArea);+ setPopupCurrentScale(undefined);+ setPopupCurrentPageNumber(1);+ setPopupOverlayViews(undefined);+ setPopupViewArea(undefined);+ };++ const detachRootListeners = (viewer: PDFViewer) => {+ viewer.event.off('pagesloaded', onRootPagesLoaded);+ viewer.event.off('scalechanging', onRootScaleChanging);+ viewer.event.off('pagechanging', onRootPageChanging);+ viewer.event.off('overlayViewsChanged', onRootOverlayViewsChanged);+ viewer.event.off('popupvisibilitychanged', onPopupVisibilityChanged);+ viewer.event.off('updateviewarea', onRootViewArea);+ viewer.event.off('updatefindcontrolstate', onRootFindControlState);+ viewer.event.off('updatefindmatchescount', onRootFindMatchesCount);+ setRootPageCount(undefined);+ setRootCurrentScale(undefined);+ setRootCurrentPageNumber(1);+ setRootOverlayViews(undefined);+ setIsPopupOpen(false);+ setRootViewArea(undefined);+ setRootFindControlState(undefined);+ setRootFindMatchesCount(undefined);+ };++ const commands = {+ installPair(viewers: ViewerPair) {+ attachRootListeners(viewers.root);+ attachPopupListeners(viewers.popup);+ setPair(viewers);+ },+ detachListeners() {+ const viewers = pair();+ if (!viewers) return;+ detachPopupListeners(viewers.popup);+ detachRootListeners(viewers.root);+ },+ clearPair() {+ setPair(undefined);+ },+ replaceOverlays(value: string[]) {+ setOverlays(value);+ },+ };++ return {+ root: {+ instance: () => pair()?.root,+ currentPageNumber: rootCurrentPageNumber,+ currentScale: rootCurrentScale,+ pageCount: rootPageCount,+ isReady: () => {+ const count = rootPageCount();+ return count != null && count > 0;+ },+ hasVisiblePages: () => {+ const ids = rootViewArea()?.visiblePages.ids;+ return ids != null && ids.size > 0;+ },+ canZoomIn: () => {+ const scale = rootCurrentScale();+ return !!(scale && scale < ZOOM_MAX);+ },+ canZoomOut: () => {+ const scale = rootCurrentScale();+ return !!(scale && scale > ZOOM_MIN);+ },+ overlayViews: rootOverlayViews,+ viewArea: rootViewArea,+ findControlState: rootFindControlState,+ findMatchesCount: rootFindMatchesCount,+ pageHeights: rootPageHeights,+ },+ popup: {+ instance: () => pair()?.popup,+ currentPageNumber: popupCurrentPageNumber,+ currentScale: popupCurrentScale,+ overlayViews: popupOverlayViews,+ viewArea: popupViewArea,+ },+ isPopupOpen,+ overlays,+ ...commands,+ };+}++export type PdfViewerRuntime = ReturnType<typeof createPdfViewerRuntime>;diff --git a/apps/web/src/features/block-pdf/signal/definitionPopup.ts b/apps/web/src/features/block-pdf/signal/definitionPopup.tsnew file mode 100644index 0000000000..88ec0e5480--- /dev/null+++ b/apps/web/src/features/block-pdf/signal/definitionPopup.ts@@ -0,0 +1,14 @@+import { usePdfDocument } from '../context/pdf-document-context';+import type { DefinitionPopupAction } from '../primitives/pdf-definitions';++export function usePopupContextUpdate(+ isPopup: boolean+): (action: DefinitionPopupAction) => void {+ const commands = usePdfDocument().definitions.commands;+ return isPopup ? commands.dispatchPopup : commands.dispatchRoot;+}++export function usePopupStore(isPopup: boolean) {+ const definitions = usePdfDocument().definitions;+ return isPopup ? definitions.popup : definitions.root;+}diff --git a/apps/web/src/features/block-pdf/signal/location.ts b/apps/web/src/features/block-pdf/signal/location.tsindex ad1c102c8e..e62f5b5db2 100644--- a/apps/web/src/features/block-pdf/signal/location.ts+++ b/apps/web/src/features/block-pdf/signal/location.ts@@ -9,9 +9,10 @@ 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, createEffect, createMemo } from 'solid-js';+import type { Accessor } from 'solid-js';import { z } from 'zod';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';export { URL_PARAMS };@@ -43,13 +44,6 @@ export enum LocationType {Annotation = 'annotation',}-type LocationTypeMap = {- general: GeneralLocation;- precise: PreciseLocation;- annotation: AnnotationLocation;- search: SearchLocation;-};-/*** Types of PDF locations, ordered by increasing precision.*/@@ -88,6 +82,8 @@ export interface AnnotationLocation {id: string;}+export type PdfShareLocation = PreciseLocation | AnnotationLocation;+export interface SearchLocation {type: 'search';pageIndex: number;@@ -110,54 +106,10 @@ export const PdfOrderInfoSchema = z.object({export type PdfOrderInfo = z.infer<typeof PdfOrderInfoSchema>;const useIsViewerReadyForScroll = () => {- const pdf = usePdfDocument();- const [viewerHasVisiblePages] = pdf.state.signals.viewerHasVisiblePages;- return createMemo(- () => pdf.state.derived.viewerReady() && viewerHasVisiblePages()- );+ const rootViewer = usePdfViewer().root;+ return () => rootViewer.isReady() && rootViewer.hasVisiblePages();};-export function usePendingLocationNavigationEffect() {- const pdf = usePdfDocument();- const [rootViewer] = pdf.state.signals.rootViewer;- const [pendingLocationParams] = pdf.state.signals.pendingLocationParams;- const goToLinkLocationFromParams = useGoToLinkLocationFromParams();- const isViewerReady = useIsViewerReadyForScroll();-- createEffect(() => {- const params = pendingLocationParams();- if (isViewerReady() && params) {- // TODO: do we need to clear all overlays here- rootViewer()?.clearAllOverlays();-- void goToLinkLocationFromParams(params);- }- });-}--export function useSetLocationStore() {- const [, setLocation] = usePdfDocument().state.stores.location;-- const setLocationStore = <T extends PdfLocationType>(- type: T,- location: Omit<LocationTypeMap[T], 'type'> | undefined- ): void => {- if (type === 'precise') {- setLocation('annotation', undefined);- }-- const l: LocationTypeMap[T] | undefined = location- ? ({- ...location,- type,- } as LocationTypeMap[T])- : undefined;- setLocation(type, l);- };-- return createCallback(setLocationStore);-}-/*** Converts a location into URL parameters for sharing.*@@ -232,25 +184,23 @@ export function selectLocationForFidelity(export function useCreateShareUrl() {const pdf = usePdfDocument();- const [locationStore] = pdf.state.stores.location;+ const rootViewer = usePdfViewer().root;const referralCode = useReferralCode();- /**- * Creates a shareable URL with location information at the specified fidelity level.- *- * @param fidelity - Desired fidelity level for the share URL- * @param copy - Whether to copy the URL to the clipboard- * @returns URL string with location parameters- */const createShareUrl = (fidelity: PdfLocationType,copy: boolean = true): string => {+ const shareLocation = pdf.shareLocation();const locations = {- general: locationStore.general,- precise: locationStore.precise,- annotation: locationStore.annotation,- search: locationStore.search,+ general: {+ type: 'general',+ pageIndex: rootViewer.currentPageNumber(),+ y: 0,+ } satisfies GeneralLocation,+ precise: shareLocation?.type === 'precise' ? shareLocation : undefined,+ annotation:+ shareLocation?.type === 'annotation' ? shareLocation : undefined,};const selectedLocation = selectLocationForFidelity(fidelity, locations);const url = locationToUrl(selectedLocation);@@ -458,7 +408,6 @@ async function applyCustomHighlights(return;}- // Log pageMatches and pageMatchesLength for debuggingconst pageMatches = findController.pageMatches;const pageMatchesLength = findController.pageMatchesLength;@@ -504,17 +453,11 @@ async function applyCustomHighlights(viewer.markPageHighlightsSelected(pageIndex);}-/**- * Go to the given location in the pdf viewer- *- * @param location - The location to go to- */function useGoToPdfLocation() {- const pdf = usePdfDocument();- const [rootViewer] = pdf.state.signals.rootViewer;- const [findControllerStateEventSignal] =- pdf.state.signals.updateFindControlState;- const [, setSearchLocationPending] = pdf.state.signals.searchLocationPending;+ const pdfViewer = usePdfViewer();+ const rootRuntime = pdfViewer.root;+ const rootViewer = rootRuntime.instance;+ const findControllerStateEventSignal = rootRuntime.findControlState;const go = async (location: PdfLocation): Promise<void> => {const viewer = rootViewer();@@ -545,7 +488,6 @@ function useGoToPdfLocation() {});return;case 'search':- // Go to the page of the matchawait viewer.scrollTo({pageNumber: location.pageIndex,yPos: 0,@@ -586,7 +528,6 @@ function useGoToPdfLocation() {return;}- // Break early if we can't find the matchif (findControllerStateEvent.state === FindState.NOT_FOUND) {console.warn('unable to find match', { location });// TODO: fallback to raw query@@ -623,7 +564,6 @@ function useGoToPdfLocation() {findController._highlightMatches = false;findController._updatePage(pageIdx);- // Apply custom highlights based on macro_em tagsawait applyCustomHighlights(viewer,currentScrollTop,@@ -651,9 +591,12 @@ function useGoToPdfLocation() {return async (location: PdfLocation) => {if (location.type === 'search') {- setSearchLocationPending(true);- await go(location);- setSearchLocationPending(false);+ pdfViewer.beginSearchNavigation();+ try {+ await go(location);+ } finally {+ pdfViewer.endSearchNavigation();+ }return;}@@ -663,22 +606,23 @@ function useGoToPdfLocation() {const useGoToPreviousLocation = () => {const pdf = usePdfDocument();- const [viewer] = pdf.state.signals.rootViewer;- const [viewLocation] = pdf.state.signals.viewLocation;+ const viewer = usePdfViewer().root.instance;const isViewerReady = useIsViewerReadyForScroll();return async () => {const rootViewer = viewer();- await waitForSignal(viewLocation, (location) => !!location, 300).then(- (prevLocationHash) => {- waitForSignal(isViewerReady).then(() => {- if (rootViewer && prevLocationHash) {- rootViewer.goToLocationHash(prevLocationHash);- }- });- }- );+ await waitForSignal(+ pdf.persistedViewLocation,+ (location) => !!location,+ 300+ ).then((prevLocationHash) => {+ waitForSignal(isViewerReady).then(() => {+ if (rootViewer && prevLocationHash) {+ rootViewer.goToLocationHash(prevLocationHash);+ }+ });+ });};};diff --git a/apps/web/src/features/block-pdf/signal/pdfViewer.tsx b/apps/web/src/features/block-pdf/signal/pdfViewer.tsxindex 8c97336c8f..9d3761fb0e 100644--- a/apps/web/src/features/block-pdf/signal/pdfViewer.tsx+++ b/apps/web/src/features/block-pdf/signal/pdfViewer.tsx@@ -1,5 +1,5 @@import { createContext, type ParentComponent, useContext } from 'solid-js';-import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import { PDFViewer } from '../PdfViewer';type PageViewportWithScale = {@@ -30,13 +30,11 @@ export const initializePdfViewer = (popupViewer?: PDFViewer) => {};export const useGetRootViewer = () => {- const [viewer] = usePdfDocument().state.signals.rootViewer;- return () => viewer();+ return usePdfViewer().root.instance;};export const useGetPopupViewer = () => {- const [viewer] = usePdfDocument().state.signals.popupViewer;- return () => viewer();+ return usePdfViewer().popup.instance;};export const useGetPopupContextViewer = () => {@@ -48,13 +46,10 @@ export const useGetPopupContextViewer = () => {// NOTE: this fires off on every change because the isEqual function is not workingexport const useVisiblePages = () => {- const { visiblePagesChanged, visiblePagesChangedPopup } =- usePdfDocument().state.signals;+ const viewer = usePdfViewer();const isPopup = useIsPopup();- const [visiblePages] = isPopup- ? visiblePagesChangedPopup- : visiblePagesChanged;- return () => visiblePages()?.visiblePages;+ const viewArea = isPopup ? viewer.popup.viewArea : viewer.root.viewArea;+ return () => viewArea()?.visiblePages;};const PopupContext = createContext<boolean>();@@ -75,39 +70,38 @@ export function useIsPopup() {}export const useOverlayViewsChanged = () => {- const { overlayViewsChanged, overlayViewsChangedPopup } =- usePdfDocument().state.signals;+ const viewer = usePdfViewer();const isPopup = useIsPopup();- return () =>- isPopup ? overlayViewsChangedPopup[0]() : overlayViewsChanged[0]();+ return isPopup ? viewer.popup.overlayViews : viewer.root.overlayViews;};export const useCurrentPageNumber = () => {- const currentPageNumber = usePdfDocument().state.derived.currentPageNumber;- return () => currentPageNumber() ?? 1;+ return usePdfViewer().root.currentPageNumber;};// /** reactive values based on current page dimensions */export const useCurrentPageViewport = () => {- const pdf = usePdfDocument();+ const viewerRuntime = usePdfViewer();const isPopup = useIsPopup();const getViewer = useGetPopupContextViewer();- const { currentPageNumber, popupCurrentPageNumber, viewerReady } =- pdf.state.derived;+ const currentPageNumber = isPopup+ ? viewerRuntime.popup.currentPageNumber+ : viewerRuntime.root.currentPageNumber;return () => {- const curPage = isPopup ? popupCurrentPageNumber() : currentPageNumber();+ const curPage = currentPageNumber();const viewer = getViewer();- if (!viewerReady() || !viewer || curPage == null || curPage < 1)+ if (!viewerRuntime.root.isReady() || !viewer || curPage < 1)return PAGE_VIEWPORT_DEFAULT;return viewer.pageViewport(curPage - 1) ?? PAGE_VIEWPORT_DEFAULT;};};export const useCurrentScale = () => {- const { currentScale, popupCurrentScale } = usePdfDocument().state.derived;+ const viewer = usePdfViewer();const isPopup = useIsPopup();- return () => {- return (isPopup ? popupCurrentScale() : currentScale()) ?? 1;- };+ const currentScale = isPopup+ ? viewer.popup.currentScale+ : viewer.root.currentScale;+ return () => currentScale() ?? 1;};diff --git a/apps/web/src/features/block-pdf/signal/permissions.ts b/apps/web/src/features/block-pdf/signal/permissions.tsindex b24369ee0c..a193044bf8 100644--- a/apps/web/src/features/block-pdf/signal/permissions.ts+++ b/apps/web/src/features/block-pdf/signal/permissions.ts@@ -3,12 +3,9 @@ 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) {@@ -16,14 +13,15 @@ export const useOwnedCommentPlaceableSelector = () => {return [];}+ const anchors = pdf.annotations.anchors();const owned =- anchors()+ anchors?.filter((anchor) =>anchor.anchorType === 'placeable' && anchor.owner === currentUserId).map((anchor) => anchor.uuid) ?? [];- const newComment = newPlaceable();+ const newComment = pdf.markup.draft();if (newComment &&isThreadPlaceable(newComment) &&@@ -40,33 +38,11 @@ export const useOwnedCommentPlaceableSelector = () => {return ownedCommentSelector;};-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)- );- return ownedCommentSelector;-};-export const useOwnedHighlightSelector = () => {const pdf = usePdfDocument();const userId = useUserId();- const highlightsUuidMap = pdf.state.derived.highlightsUuidMap;const ownedHighlightSelector = createSelector(- highlightsUuidMap,+ pdf.annotations.highlightsByUuid,(uuid: string, owned) => {if (!owned) return false;const highlight = owned[uuid];diff --git a/apps/web/src/features/block-pdf/signal/save.ts b/apps/web/src/features/block-pdf/signal/save.tsindex 95d5a9229b..1810388455 100644--- a/apps/web/src/features/block-pdf/signal/save.ts+++ b/apps/web/src/features/block-pdf/signal/save.ts@@ -4,6 +4,7 @@ import { refetchHistory } from '@queries/history/history';import { storageServiceClient } from '@service-storage/client';import { createMemo } from 'solid-js';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import {getSaveModificationData,hashModificationData,@@ -11,58 +12,23 @@ import {} from '../util/buildModificationData';export function useDoEdit() {- const [, setNumOperations] = usePdfDocument().state.signals.numOperations;- return () => setNumOperations((prev) => prev + 1);+ return usePdfDocument().model.commands.recordEdit;}-const useSaveWrapper = () => {- const { isSaving, savingCount } = usePdfDocument().state.signals;- const [, setIsSaving] = isSaving;- const [getSavingCount, setSavingCount] = savingCount;-- return (save: () => Promise<void>, shouldSave: () => boolean) => {- return async () => {- let saving = false;- try {- if (!shouldSave()) return;- saving = true;- setIsSaving(true);- setSavingCount((prev) => prev + 1);- await save();- } catch (e) {- console.error('Error saving PDF', e);- } finally {- if (saving) {- const count = getSavingCount() - 1;- setSavingCount(count);- if (count === 0) {- setIsSaving(false);- }- }- }- };- };-};-export function useHasModificationData() {- const { highlights, modificationData } = usePdfDocument().state.stores;- const [highlightStoreValue] = highlights;- const [pdfModificationValue] = modificationData;+ const pdf = usePdfDocument();return () =>- Object.keys(highlightStoreValue).length > 0 ||- pdfModificationValue.placeables.length > 0;+ pdf.annotations.hasHighlights() ||+ pdf.model.modificationData.placeables.length > 0;}export function useSaveModificationData() {const pdf = usePdfDocument();- const saveWrapper = useSaveWrapper();- const [pdfModificationValue] = pdf.state.stores.modificationData;- const [tableOfContents] = pdf.state.stores.tableOfContents;- const [serverModificationData] = pdf.state.signals.serverModificationData;+ const pdfModificationValue = pdf.model.modificationData;const serverModificationDataHash = createMemo(() => {- const modificationData_ = serverModificationData();+ const modificationData_ = pdf.model.serverSnapshot();if (!modificationData_) return '';const hash = hashModificationDataSync(modificationData_);return hash;@@ -73,7 +39,6 @@ export function useSaveModificationData() {const placeables = pdfModificationValue.placeables ?? [];const { modificationData } = getSaveModificationData({placeables,- TOCItems: tableOfContents.items,pinnedTerms: [],});const sha = hashModificationDataSync(modificationData);@@ -84,7 +49,6 @@ export function useSaveModificationData() {const placeables = pdfModificationValue.placeables ?? [];const { modificationData } = getSaveModificationData({placeables,- TOCItems: tableOfContents.items,pinnedTerms: [],});@@ -103,17 +67,13 @@ export function useSaveModificationData() {await Promise.all(serverSaves);};- const wrapped = saveWrapper(save, shouldSave);-- return wrapped;+ return () => pdf.persistence.runSave(save, shouldSave);}export function usePdfSaveLocation() {const pdf = usePdfDocument();- const saveWrapper = useSaveWrapper();- const [viewer] = pdf.state.signals.rootViewer;- const [prevLocationHash, setPrevLocationHash] =- pdf.state.signals.viewLocation;+ const viewer = usePdfViewer().root.instance;+ const prevLocationHash = pdf.persistedViewLocation;const userId = useUserId();const shouldSave = () => {@@ -126,7 +86,7 @@ export function usePdfSaveLocation() {const save = async () => {const location = viewer()?.getLocationHash();- setPrevLocationHash(location);+ pdf.setPersistedViewLocation(location);if (location == null) {await storageServiceClient.deleteDocumentViewLocation({documentId: pdf.documentId(),@@ -139,9 +99,7 @@ export function usePdfSaveLocation() {}};- const wrapped = saveWrapper(save, shouldSave);-- return wrapped;+ return () => pdf.persistence.runSave(save, shouldSave);}export const usePdfSave = () => {diff --git a/apps/web/src/features/block-pdf/signal/search.ts b/apps/web/src/features/block-pdf/signal/search.tsindex 99d213365a..ec7ecdca47 100644--- a/apps/web/src/features/block-pdf/signal/search.ts+++ b/apps/web/src/features/block-pdf/signal/search.ts@@ -1,16 +1,11 @@import type { PDFViewer } from '@block-pdf/PdfViewer';-import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import {FindState,type IMatchesCount,type IUpdateFindControlStateEvent,} from '../PdfViewer/EventBus';import type { FindController } from '../PdfViewer/FindController';-import {- type TPageToSectionMap,- useGetPageToSectionMap,-} from '../store/tableOfContents';-import TocUtils from '../util/TocUtils';import { generatePhrases } from '../util/wordSearchUtils';enum SearchMatchType {@@ -41,12 +36,11 @@ type WordMatch = BaseMatch & {type Match = EntityMatch | WordMatch;function useMergedEventSignal() {- const { updateFindControlState, updateFindMatchesCount } =- usePdfDocument().state.signals;+ const { findControlState, findMatchesCount } = usePdfViewer().root;return (): IUpdateFindControlStateEvent | null => {- const controlStateEvent = updateFindControlState[0]();- const matchesCount = updateFindMatchesCount[0]();+ const controlStateEvent = findControlState();+ const matchesCount = findMatchesCount();if (!controlStateEvent) return null;@@ -103,10 +97,7 @@ function useMergedEventSignal() {};}-function getWordMatches(- pageToSectionMap: TPageToSectionMap,- findController: FindController-): WordMatch[] {+function getWordMatches(findController: FindController): WordMatch[] {if (!findController._pageMatches ||findController._pageMatches.length === 0 ||@@ -153,12 +144,6 @@ function getWordMatches(endPos,page: pageContent,});- const section =- TocUtils.getNearestSection({- page: pageIndex,- yPos: startPos,- pageToSectionMap,- })?.title ?? '';matches.push({startPos,endPos,@@ -166,7 +151,7 @@ function getWordMatches(prePhrase,postPhrase,matchPhrase,- section,+ section: '',matchNumber,type: SearchMatchType.Word,});@@ -177,7 +162,7 @@ function getWordMatches(}export function useSearchStart() {- const [rootViewer] = usePdfDocument().state.signals.rootViewer;+ const rootViewer = usePdfViewer().root.instance;return (args: Parameters<PDFViewer['search']>[0]) => {rootViewer()?.search(args);};@@ -185,7 +170,6 @@ export function useSearchStart() {export function useSearchResults() {const mergedEvent = useMergedEventSignal();- const pageToSectionMap = useGetPageToSectionMap();return (): {query: string;@@ -206,7 +190,7 @@ export function useSearchResults() {};const findController = results.source;- const matches = getWordMatches(pageToSectionMap(), findController);+ const matches = getWordMatches(findController);if (matches.length === 0) {return null;}@@ -222,7 +206,7 @@ export function useSearchResults() {}export function useJumpToResult() {- const [rootViewer] = usePdfDocument().state.signals.rootViewer;+ const rootViewer = usePdfViewer().root.instance;const mergedEvent = useMergedEventSignal();return (match: Match) => {@@ -241,7 +225,7 @@ export function useJumpToResult() {}export function useSearchClose() {- const [rootViewer] = usePdfDocument().state.signals.rootViewer;+ const rootViewer = usePdfViewer().root.instance;return () => {rootViewer()?.findBarClose();};diff --git a/apps/web/src/features/block-pdf/signal/tab.test.tsx b/apps/web/src/features/block-pdf/signal/tab.test.tsxnew file mode 100644index 0000000000..edf23189e6--- /dev/null+++ b/apps/web/src/features/block-pdf/signal/tab.test.tsx@@ -0,0 +1,140 @@+import { cleanup, render } from '@solidjs/testing-library';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ type PdfDocumentContextValue,+ PdfDocumentProvider,+ usePdfDocument,+} from '../context/pdf-document-context';+import {+ type PdfViewerContextValue,+ PdfViewerProvider,+ usePdfViewer,+} from '../context/pdf-viewer-context';+import type { PDFViewer } from '../PdfViewer';+import { createEventBus, type TEvents } from '../PdfViewer/EventBus';+import { useCreateTab, useNavigateToTab } from './tab';++vi.mock('../queries/annotations', () => ({+ getPdfAnchors: vi.fn(async () => []),+ getPdfComments: vi.fn(async () => []),+}));++afterEach(cleanup);++type TabTestApi = {+ context: PdfDocumentContextValue;+ viewer: PdfViewerContextValue;+ createTab: ReturnType<typeof useCreateTab>;+ navigateToTab: ReturnType<typeof useNavigateToTab>;+};++function Probe(props: { capture: (api: TabTestApi) => void }) {+ props.capture({+ context: usePdfDocument(),+ viewer: usePdfViewer(),+ createTab: useCreateTab(),+ navigateToTab: useNavigateToTab(),+ });+ return null;+}++function setup(isNested = false): TabTestApi {+ let api!: TabTestApi;+ render(() => (+ <PdfDocumentProvider+ documentId="document-1"+ documentName="document-1.pdf"+ isNested={isNested}+ permissions={{+ canComment: true,+ canEdit: true,+ isOwner: true,+ }}+ >+ <PdfViewerProvider>+ <Probe capture={(value) => (api = value)} />+ </PdfViewerProvider>+ </PdfDocumentProvider>+ ));+ return api;+}++function createViewer(overrides: Partial<PDFViewer> = {}) {+ return {+ event: createEventBus(),+ ...overrides,+ } as PDFViewer;+}++function setCurrentPage(viewer: PDFViewer, pageNumber: number) {+ viewer.event.dispatch('pagechanging', {+ source: {},+ pageNumber,+ previous: pageNumber - 1,+ pageLabel: null,+ } satisfies TEvents['pagechanging']);+}++describe('PDF tab hooks', () => {+ it('does not create tabs without a viewer or for nested documents', () => {+ const withoutViewer = setup();+ withoutViewer.createTab();++ const nested = setup(true);+ nested.viewer.installPair({+ root: createViewer(),+ popup: createViewer(),+ });+ nested.createTab();++ expect({+ withoutViewerCount: withoutViewer.context.tabs.count(),+ withoutViewerVisible: withoutViewer.context.tabs.isVisible(),+ nestedCount: nested.context.tabs.count(),+ nestedVisible: nested.context.tabs.isVisible(),+ }).toEqual({+ withoutViewerCount: 1,+ withoutViewerVisible: false,+ nestedCount: 1,+ nestedVisible: false,+ });+ });++ it('creates and navigates tabs through viewer state', () => {+ const { context, viewer, createTab, navigateToTab } = setup();+ const getLocationHash = vi.fn(() => '#page=3');+ const goToLocationHash = vi.fn();+ const rootViewer = createViewer({+ getLocationHash,+ goToLocationHash,+ });+ viewer.installPair({+ root: rootViewer,+ popup: createViewer(),+ });+ setCurrentPage(rootViewer, 3);++ createTab();+ createTab({ label: 'Saved location', locationHash: '#page=8' });++ expect(context.tabs.items).toEqual([+ { id: 0, label: 'Page 3', locationHash: '#page=3' },+ { id: 1, label: 'Page 3', locationHash: '#page=3' },+ { id: 2, label: 'Saved location', locationHash: '#page=8' },+ ]);+ expect(context.tabs.activeId()).toBe(2);+ expect(goToLocationHash.mock.calls).toEqual([['#page=3'], ['#page=8']]);++ getLocationHash.mockReturnValue('#page=4');+ setCurrentPage(rootViewer, 4);+ navigateToTab(0);++ expect(context.tabs.items[2]).toEqual({+ id: 2,+ label: 'Page 4',+ locationHash: '#page=4',+ });+ expect(context.tabs.activeId()).toBe(0);+ expect(goToLocationHash).toHaveBeenLastCalledWith('#page=3');+ });+});diff --git a/apps/web/src/features/block-pdf/signal/tab.ts b/apps/web/src/features/block-pdf/signal/tab.tsindex 3aa2d35f6b..eb7ea550ac 100644--- a/apps/web/src/features/block-pdf/signal/tab.ts+++ b/apps/web/src/features/block-pdf/signal/tab.ts@@ -1,20 +1,14 @@import { ENABLE_PDF_TABS } from '@core/constant/featureFlags';import { createCallback } from '@solid-primitives/rootless';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';const TOP_PADDING = 0.2;-// TODO (seamus) : Max tabs is not an ideal solution. Revisit when makingexport const MAX_TAB_COUNT = 8;-export type TabInfo = {- label: string;- locationHash?: string;- id: number;-};-export function useGoToLocationHash() {- const [rootViewer] = usePdfDocument().state.signals.rootViewer;+ const rootViewer = usePdfViewer().root.instance;const createTab = useCreateTab();const tabCount = useTabCount();@@ -30,7 +24,7 @@ export function useGoToLocationHash() {}export function useGoToLocation() {- const [rootViewer] = usePdfDocument().state.signals.rootViewer;+ const rootViewer = usePdfViewer().root.instance;const createTab = useCreateTab();const tabCount = useTabCount();return createCallback(@@ -49,7 +43,6 @@ export function useGoToLocation() {viewer.hidePopup();const pageNumber = loc.pageIndex + 1;- // perform the scrollviewer.scrollTo({pageNumber,yPos: Math.floor(loc.yPos),@@ -65,79 +58,48 @@ export function useGoToLocation() {);}-// The default tab info for a newly opened pdf.-const defaultTabData = (id: number) => ({- label: 'Page 1',- locationHash: '#page=1',- id,-});--function tabById(tabs: readonly TabInfo[], id: number): TabInfo | undefined {- return tabs.find((tab) => tab.id === id);-}--/**- * Create a block-scoped function to navigate to a tab by id. Also sets the- * selected tab id, and pushes it to the tab history.- */export function useNavigateToTab() {const pdf = usePdfDocument();+ const pdfViewer = usePdfViewer();const updateCurrentTab = useUpdateCurrentTab();- const [tabs] = pdf.state.stores.tabData;- const [, setActiveTabId] = pdf.state.signals.activeTabId;- const [, setTabHistory] = pdf.state.signals.tabHistory;- const [rootViewer] = pdf.state.signals.rootViewer;+ const rootViewer = pdfViewer.root.instance;return createCallback((id: number) => {const viewer = rootViewer();if (!viewer) return;- // Store the current location in the current tab.updateCurrentTab();- const tab = tabById(tabs, id);+ const tab = pdf.tabs.items.find((tab) => tab.id === id);if (tab === undefined) {return;}tab.locationHash && viewer.goToLocationHash(tab.locationHash);- setActiveTabId(id);- setTabHistory((p) => [...p, id]);+ pdf.tabs.commands.activate(id);});}-/**- * Create a block-scoped function that stores the current location hash of the- * pdf viewer in the currently active tab.- */export function useUpdateCurrentTab() {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;+ const pdfViewer = usePdfViewer();+ const rootViewer = pdfViewer.root.instance;+ const currentPageNumber = pdfViewer.root.currentPageNumber;return createCallback(() => {const viewer = rootViewer();if (!viewer) return;- 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);+ pdf.tabs.commands.updateCurrent({+ label: `Page ${currentPageNumber()}`,+ locationHash: viewer.getLocationHash() ?? undefined,+ });});}-/**- * Create a block-scoped function that creates a new tab.- */export function useCreateTab() {const pdf = usePdfDocument();+ const pdfViewer = usePdfViewer();const navigateToTab = useNavigateToTab();- 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;+ const rootViewer = pdfViewer.root.instance;+ const currentPageNumber = pdfViewer.root.currentPageNumber;return createCallback((info?: { label: string; locationHash: string }) => {if (pdf.isNested()) return;@@ -145,64 +107,24 @@ export function useCreateTab() {const viewer = rootViewer();if (!viewer) return;- setTabId((previous) => previous + 1);- const newId = tabId();- setTabs([- ...tabs,- {- locationHash: info?.locationHash ?? viewer.getLocationHash() ?? '',- label: info?.label ?? `Page ${currentPageNumber()}`,- id: newId,- },- ]);- setShowTabBar(true);+ const newId = pdf.tabs.commands.create({+ locationHash: info?.locationHash ?? viewer.getLocationHash() ?? '',+ label: info?.label ?? `Page ${currentPageNumber()}`,+ });navigateToTab(newId);- setActiveTabId(newId);});}-/**- * Create a block-scoped function that resets tab state.- */-export function useClearTabs() {- 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);- setTabHistory([0]);- setTabData([defaultTabData(0)]);- };-}--/**- * Create a block-scoped function deletes a tab by id.- */export function useDeleteTab() {const pdf = usePdfDocument();- const [tabs, setTabs] = pdf.state.stores.tabData;- const [tabHistory, setTabHistory] = pdf.state.signals.tabHistory;const navigateToTab = useNavigateToTab();return createCallback((id: number) => {- setTabs([...tabs.filter((tab) => tab.id !== id)]);- let history = tabHistory().filter((tabId) => tabId !== id);-- // If history is empty after filtering, use the first available tab- if (history.length === 0 && tabs.length > 0) {- history = [tabs[0].id];- }-- setTabHistory(history);- const nextId = history.at(-1) ?? tabs[0].id ?? 0;+ const nextId = pdf.tabs.commands.remove(id);navigateToTab(nextId);});}export function useTabCount() {- const [tabs] = usePdfDocument().state.stores.tabData;- return createCallback(() => tabs.length);+ return usePdfDocument().tabs.count;}diff --git a/apps/web/src/features/block-pdf/store/annotations.ts b/apps/web/src/features/block-pdf/store/annotations.tsindex c7a58a0f46..78bb848c28 100644--- a/apps/web/src/features/block-pdf/store/annotations.ts+++ b/apps/web/src/features/block-pdf/store/annotations.ts@@ -1,74 +1,28 @@-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 { untrack } from 'solid-js';import { usePdfDocument } from '../context/pdf-document-context';import { annotationsToPlaceables } from './placeables';export const useLoadAnnotations = () => {- const pdfDocument = usePdfDocument();- const [, setModificationData] = pdfDocument.state.stores.modificationData;- const [serverModificationData] =- pdfDocument.state.signals.serverModificationData;- const hasServerModificationData = () => serverModificationData() != null;+ const model = usePdfDocument().model;- // const getPageHighlightMap = (highlights: IHighlight[]): HighlightUuidMap => {- // const pageIndex = highlights.at(0)?.pageNum;- // if (pageIndex === undefined) return {};- // if (!highlights.every((h) => h.pageNum === pageIndex)) return {};- //- // // NOTE: deduplicates highlights by uuid, preferring the last highlight in the array- // const hmap = highlights.reduce<HighlightUuidMap>(- // (acc, h) => ({ ...acc, [h.uuid]: h }),- // {}- // );- //- // return hmap;- // };-- return async (- documentProxy: PDFDocumentProxy,- modificationData: IModificationData- ) => {- // clearHighlightStore();-- if (hasServerModificationData()) {- batch(() => {- // setHighlightStore(reconcile(modificationData.highlights));- setModificationData(- 'placeables',- reconcile(untrack(() => modificationData.placeables))- );- });+ return async (documentProxy: PDFDocumentProxy) => {+ if (model.hasServerSnapshot()) {+ model.commands.replacePlaceables(+ untrack(() => model.modificationData.placeables)+ );return;}- setModificationData('placeables', reconcile([]));- // const allHighlights: [number, HighlightUuidMap][] = [];+ model.commands.replacePlaceables([]);const allPlaceables: IPlaceable[] = [];for (let pageIndex = 0; pageIndex < documentProxy.numPages; pageIndex++) {try {const page = await documentProxy.getPage(pageIndex + 1);const pageViewport = page.getViewport({ scale: 1 });- const [annotations, _textContent] = await Promise.all([- page.getAnnotations(),- new Promise((resolve) => resolve(null)),- // page.getTextContent(),- ]);-- // const highlightArray = highlightsFromPDFjs({- // pageIndex,- // pageViewport,- // textContent,- // annotations,- // }).map(Highlight.toObject);- //- // if (highlightArray.length > 0) {- // const highlightsOnPage = getPageHighlightMap(highlightArray);- // allHighlights.push([pageIndex, highlightsOnPage]);- // }+ const annotations = await page.getAnnotations();const pagePlaceables = annotationsToPlaceables({pageIndex,@@ -82,11 +36,6 @@ export const useLoadAnnotations = () => {}}- batch(() => {- // for (const [pageIndex, highlightsOnPage] of allHighlights) {- // setHighlightStore(pageIndex, highlightsOnPage);- // }- setModificationData('placeables', reconcile(allPlaceables));- });+ model.commands.replacePlaceables(allPlaceables);};};diff --git a/apps/web/src/features/block-pdf/store/comments/commentEffect.ts b/apps/web/src/features/block-pdf/store/comments/commentEffect.tsindex c624210dec..5acdbe59ad 100644--- a/apps/web/src/features/block-pdf/store/comments/commentEffect.ts+++ b/apps/web/src/features/block-pdf/store/comments/commentEffect.ts@@ -1,48 +1,44 @@-import { usePdfDocument } from '@block-pdf/context/pdf-document-context';import { usePdfCommentRealtimeBehavior } from '@block-pdf/store/commentsResource';+import { isPdfDraftThreadId } from '@block-pdf/type/comments';import { createEffect, createMemo } from 'solid-js';-import { useCommentLayoutBehavior } from './commentLayout';+import { usePdfComments } from '../../context/pdf-comments-context';import {useDeleteNewComments,useScrollToCommentThread,} from './commentOperations';-import { useCommentStoreBehavior } from './commentStore';-// remove the new temporary comment when it is no longer activeconst useDeleteNewCommentEffect = () => {const deleteNewComments = useDeleteNewComments();- const [activeCommentThread] =- usePdfDocument().state.signals.activeCommentThread;+ const activeCommentThreadId = usePdfComments().activeThreadId;createEffect(() => {- const activeThreadId = activeCommentThread();- if (!activeThreadId || activeThreadId !== -1) {+ const activeThreadId = activeCommentThreadId();+ if (!isPdfDraftThreadId(activeThreadId)) {deleteNewComments();}});};-// scroll to the active comment threadconst useScrollToActiveThreadEffect = () => {const scrollToCommentThread = useScrollToCommentThread();- const { signals, stores } = usePdfDocument().state;- const [comments] = stores.comments;- const [activeCommentThread] = signals.activeCommentThread;- const [noScrollToActiveCommentThread] = signals.noScrollToActiveCommentThread;- const noScroll = createMemo(() => {- return noScrollToActiveCommentThread();- });- const hasMatch = createMemo(() => {- return comments.find((c) => c.threadId === activeCommentThread()) != null;+ const commentsContext = usePdfComments();+ const comments = commentsContext.all;+ const activeCommentThreadId = commentsContext.activeThreadId;+ const activeThreadScrollingSuppressed = commentsContext.scrollingSuppressed;+ const hasActiveThread = createMemo(() => {+ const activeThreadId = activeCommentThreadId();+ return (+ activeThreadId != null &&+ comments().some((comment) => comment.threadId === activeThreadId)+ );});createEffect(() => {- if (noScroll()) return;+ if (activeThreadScrollingSuppressed()) return;- const activeThreadId = activeCommentThread();+ const activeThreadId = activeCommentThreadId();if (activeThreadId == null) return;-- if (!hasMatch()) return;+ if (!hasActiveThread()) return;if (typeof activeThreadId === 'number')scrollToCommentThread(activeThreadId);@@ -50,8 +46,6 @@ const useScrollToActiveThreadEffect = () => {};export const usePdfCommentEffects = () => {- useCommentStoreBehavior();- useCommentLayoutBehavior();usePdfCommentRealtimeBehavior();useDeleteNewCommentEffect();useScrollToActiveThreadEffect();diff --git a/apps/web/src/features/block-pdf/store/comments/commentLayout.test.ts b/apps/web/src/features/block-pdf/store/comments/commentLayout.test.tsnew file mode 100644index 0000000000..559dcec7c7--- /dev/null+++ b/apps/web/src/features/block-pdf/store/comments/commentLayout.test.ts@@ -0,0 +1,180 @@+import type { Root } from '@core/comments/commentType';+import { describe, expect, it, vi } from 'vitest';+import type { CommentLayout, PdfRootLayout } from '../../type/comments';+import { computePageCommentLayout } from './commentLayout';++vi.mock('../../context/pdf-document-context', () => ({+ usePdfDocument: vi.fn(),+}));++function thread(threadId: number, originalYPosition: number): PdfRootLayout {+ return {+ threadId,+ layout: {+ pageIndex: 0,+ originalYPosition,+ },+ } as PdfRootLayout;+}++function positions(layouts: CommentLayout<Root>[]) {+ return layouts.map(({ threadId, layout }) => ({+ threadId,+ ...layout,+ }));+}++describe('computePageCommentLayout', () => {+ it('returns no layout without page bounds or root comments', () => {+ expect(+ computePageCommentLayout({+ comments: [thread(1, 100)],+ activeThreadId: null,+ pageHeight: undefined,+ threadHeights: { 1: 40 },+ })+ ).toEqual([]);+ expect(+ computePageCommentLayout({+ comments: [],+ activeThreadId: null,+ pageHeight: 800,+ threadHeights: {},+ })+ ).toEqual([]);+ });++ it('sorts by original position and anchors the first thread by default', () => {+ const result = computePageCommentLayout({+ comments: [thread(3, 300), thread(1, 100), thread(2, 200)],+ activeThreadId: null,+ pageHeight: 1000,+ threadHeights: { 1: 30, 2: 20, 3: 40 },+ });++ expect(positions(result)).toEqual([+ {+ threadId: 1,+ height: 30,+ calculatedYPos: 100,+ overflow: null,+ },+ {+ threadId: 2,+ height: 20,+ calculatedYPos: 200,+ overflow: null,+ },+ {+ threadId: 3,+ height: 40,+ calculatedYPos: 300,+ overflow: null,+ },+ ]);+ });++ it('uses the active thread as the page anchor', () => {+ const result = computePageCommentLayout({+ comments: [thread(1, 190), thread(2, 200), thread(3, 205)],+ activeThreadId: 2,+ pageHeight: 1000,+ threadHeights: { 1: 30, 2: 20, 3: 20 },+ });++ expect(positions(result)).toEqual([+ {+ threadId: 1,+ height: 30,+ calculatedYPos: 154,+ overflow: null,+ },+ {+ threadId: 2,+ height: 20,+ calculatedYPos: 200,+ overflow: null,+ },+ {+ threadId: 3,+ height: 20,+ calculatedYPos: 236,+ overflow: null,+ },+ ]);+ });++ it('preserves gaps, overflow, padding, and oversized anchor handling', () => {+ const result = computePageCommentLayout({+ comments: [thread(1, 10), thread(2, 170), thread(3, 210), thread(4, 220)],+ activeThreadId: 3,+ pageHeight: 300,+ threadHeights: { 1: 60, 2: 30, 3: 40, 4: 50 },+ });++ expect(positions(result)).toEqual([+ {+ threadId: 1,+ height: 60,+ calculatedYPos: 10,+ overflow: 'top',+ },+ {+ threadId: 2,+ height: 30,+ calculatedYPos: 134,+ overflow: null,+ },+ {+ threadId: 3,+ height: 40,+ calculatedYPos: 180,+ overflow: null,+ },+ {+ threadId: 4,+ height: 50,+ calculatedYPos: 236,+ overflow: 'bottom',+ },+ ]);++ expect(+ positions(+ computePageCommentLayout({+ comments: [thread(5, 100)],+ activeThreadId: 5,+ pageHeight: 300,+ threadHeights: { 5: 400 },+ })+ )+ ).toEqual([+ {+ threadId: 5,+ height: 400,+ calculatedYPos: 0,+ overflow: null,+ },+ ]);+ });++ it('repositions neighbors when measured heights change', () => {+ const comments = [thread(1, 100), thread(2, 105)];++ const shortAnchor = computePageCommentLayout({+ comments,+ activeThreadId: 1,+ pageHeight: 1000,+ threadHeights: { 1: 20, 2: 30 },+ });+ const tallAnchor = computePageCommentLayout({+ comments,+ activeThreadId: 1,+ pageHeight: 1000,+ threadHeights: { 1: 80, 2: 30 },+ });++ expect(shortAnchor[1].layout.calculatedYPos).toBe(136);+ expect(tallAnchor[1].layout.calculatedYPos).toBe(196);+ });+});diff --git a/apps/web/src/features/block-pdf/store/comments/commentLayout.ts b/apps/web/src/features/block-pdf/store/comments/commentLayout.tsindex f7db38b50a..1ec21b7ff4 100644--- a/apps/web/src/features/block-pdf/store/comments/commentLayout.ts+++ b/apps/web/src/features/block-pdf/store/comments/commentLayout.ts@@ -8,20 +8,15 @@ import type {} from '@block-pdf/type/comments';import type { ThreadId } from '@core/comments/commentType';import { isRoot, type Root } from '@core/comments/commentType';-import { createMemo, createRenderEffect } from 'solid-js';-import { reconcile } from 'solid-js/store';-import { usePdfDocument } from '../../context/pdf-document-context';+import { type Accessor, createMemo } from 'solid-js';+import { createStore } from 'solid-js/store';+import { usePdfComments } from '../../context/pdf-comments-context';+import { usePdfViewer } from '../../context/pdf-viewer-context';// how much to pad the container for the "show more" buttonsconst CONTAINER_PADDING = 80;-/** Maps thread id to height of its measure container */-export type ThreadHeights = Record<ThreadId, number>;--/** Maps page index to comment layout on that page */-export type ThreadPositionsOnPage = Partial<- Record<number, CommentLayout<Root>[]>->;+type ThreadHeights = Record<ThreadId, number>;const isPdfRootLayout = (comment: CommentStore[number]@@ -77,133 +72,110 @@ function computeLayout<T>({}return out;}-// todo: scroll to highlight or comment-// 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-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;+export function computePageCommentLayout({+ comments,+ activeThreadId,+ pageHeight,+ threadHeights,+}: {+ comments: readonly PdfRootLayout[];+ activeThreadId: ThreadId | null;+ pageHeight: number | undefined;+ threadHeights: Partial<ThreadHeights>;+}): CommentLayout<Root>[] {+ if (!pageHeight || comments.length === 0) return [];++ const sortedThreadsByOriginalPosition = [...comments]+ .sort((a, b) => a.layout.originalYPosition - b.layout.originalYPosition)+ .map((thread) => ({+ ...thread,+ height: threadHeights[thread.threadId] ?? 0,+ }));++ const activeThreadIndex = sortedThreadsByOriginalPosition.findIndex(+ (thread) => thread.threadId === activeThreadId+ );+ const anchorIndex = activeThreadIndex === -1 ? 0 : activeThreadIndex;+ const anchorElement = sortedThreadsByOriginalPosition[anchorIndex];+ const anchorHeight = threadHeights[anchorElement.threadId] ?? 0;+ const sliceAboveAnchor = sortedThreadsByOriginalPosition.slice(+ 0,+ anchorIndex+ );+ const sliceBelowAnchor = sortedThreadsByOriginalPosition.slice(+ anchorIndex + 1+ );++ const paddedHeight = pageHeight - CONTAINER_PADDING;+ let anchorTop = anchorElement.layout.originalYPosition;+ const anchorOverflow = anchorTop + anchorHeight - paddedHeight;+ if (anchorOverflow > 0) {+ anchorTop -= anchorOverflow;+ }+ if (anchorTop < 0) {+ anchorTop = 0;+ }+ const 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,});- 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,- });-- 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,- },- },- ...layoutBelowAnchor,- ];-- groupedThreadLayoutsByPage[pageIndex] = out;- }+ return [+ ...layoutAboveAnchor,+ {+ ...anchorElement,+ layout: {+ height: anchorHeight,+ calculatedYPos: anchorTop,+ overflow: null,+ },+ },+ ...layoutBelowAnchor,+ ];+}- setThreadPositions(reconcile(groupedThreadLayoutsByPage));+export function usePageCommentLayout(pageIndex: Accessor<number>) {+ const pdfViewer = usePdfViewer();+ const commentsContext = usePdfComments();+ const activeCommentThreadId = commentsContext.activeThreadId;+ const comments = commentsContext.all;+ const pageHeights = pdfViewer.root.pageHeights;+ const [threadHeights, setThreadHeights] = createStore<Partial<ThreadHeights>>(+ {}+ );++ const threads = createMemo(() => {+ const currentPageIndex = pageIndex();+ return computePageCommentLayout({+ comments: comments().filter(+ (comment): comment is PdfRootLayout =>+ isPdfRootLayout(comment) &&+ comment.layout.pageIndex === currentPageIndex+ ),+ activeThreadId: activeCommentThreadId(),+ pageHeight: pageHeights[currentPageIndex],+ threadHeights,+ });});++ return {+ threads,+ setThreadHeight: (threadId: ThreadId, height: number) => {+ if (threadHeights[threadId] === height) return;+ setThreadHeights(threadId, height);+ },+ };}diff --git a/apps/web/src/features/block-pdf/store/comments/commentOperations.ts b/apps/web/src/features/block-pdf/store/comments/commentOperations.tsindex 59a73df357..36177774e6 100644--- a/apps/web/src/features/block-pdf/store/comments/commentOperations.ts+++ b/apps/web/src/features/block-pdf/store/comments/commentOperations.ts@@ -1,6 +1,9 @@import { useAnalytics } from '@app/lib/analytics/analytics-context';import { usePdfDocument } from '@block-pdf/context/pdf-document-context';-import type { PdfRootLayout } from '@block-pdf/type/comments';+import {+ isPdfDraftThreadId,+ type PdfRootLayout,+} from '@block-pdf/type/comments';import {type CommentId,type DeleteCommentInfo,@@ -14,6 +17,8 @@ import type {} from '@service-storage/generated/schemas';import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';import { createCallback } from '@solid-primitives/rootless';+import { usePdfComments } from '../../context/pdf-comments-context';+import { usePdfViewer } from '../../context/pdf-viewer-context';import {useAttachHighlightCommentResource,useCreateFreeCommentResource,@@ -27,8 +32,8 @@ import { useDeleteNewHighlightComment } from './highlightComments';export function useCreateComment() {const analytics = useAnalytics();- const { stores, derived } = usePdfDocument().state;- const [comments] = stores.comments;+ const annotations = usePdfDocument().annotations;+ const comments = usePdfComments().all;const deleteNewComments = useDeleteNewComments();const createFreeComment = useCreateFreeCommentResource();@@ -44,9 +49,8 @@ export function useCreateComment() {analytics.track('comment_create', { blockType: 'pdf' });const { threadId, text, mentions } = info;- // new thread + anchor- if (threadId === -1) {- const comment = comments.find((c) => c.threadId === threadId);+ if (isPdfDraftThreadId(threadId)) {+ const comment = comments().find((c) => c.threadId === threadId);if (!comment) {console.error('Unable to comment');return null;@@ -55,7 +59,7 @@ export function useCreateComment() {let response: CreateCommentResponse | null = null;switch (comment.type) {case 'highlight':- const highlight = derived.highlightsUuidMap()?.[comment.anchorId];+ const highlight = annotations.highlightsByUuid()[comment.anchorId];if (!highlight) {console.error('Unable to find highlight');return response;@@ -136,7 +140,7 @@ export function useDeleteComment() {return createCallback(async (info: DeleteCommentInfo) => {const commentId = info.commentId;- if (commentId === -1) {+ if (isPdfDraftThreadId(commentId)) {deleteNewComments();return false;}@@ -164,9 +168,12 @@ export function useDeleteNewComments() {}export function useScrollToCommentThread() {- const { documentId, rootElement, state } = usePdfDocument();- const [viewer] = state.signals.rootViewer;- const [comments] = state.stores.comments;+ const pdf = usePdfDocument();+ const pdfViewer = usePdfViewer();+ const { documentId } = pdf;+ const rootElement = pdfViewer.rootElement;+ const viewer = pdfViewer.root.instance;+ const comments = usePdfComments().all;const scrollIntoView = (el: HTMLElement) => {el.scrollIntoView({@@ -211,8 +218,6 @@ export function useScrollToCommentThread() {}});- // If the element is already in the DOM, start observing it immediately- // otherwise, listen for it to be added to the DOMif (measureContainer) {intersectionObserver.observe(measureContainer);scrollIntoView(measureContainer);@@ -228,12 +233,11 @@ export function useScrollToCommentThread() {const viewer_ = viewer();if (!viewer_) return;- const rootComment = comments+ const rootComment = comments().filter(isRoot).find((c) => c.threadId === threadId) as PdfRootLayout | undefined;if (!rootComment) return;- // if the comment is already in the viewport, we don't need to scrollif (measureContainer) return;mutationObserver.disconnect();@@ -256,7 +260,6 @@ export function useScrollToCommentThread() {}, 250);}- // automatically clean up after a timeout periodsetTimeout(() => {intersectionObserver.disconnect();mutationObserver.disconnect();diff --git a/apps/web/src/features/block-pdf/store/comments/commentStore.ts b/apps/web/src/features/block-pdf/store/comments/commentStore.tsindex 11a125bce7..3dd9cdf923 100644--- a/apps/web/src/features/block-pdf/store/comments/commentStore.ts+++ b/apps/web/src/features/block-pdf/store/comments/commentStore.ts@@ -1,15 +1,12 @@-import { usePdfDocument } from '@block-pdf/context/pdf-document-context';import type { ThreadId } from '@core/comments/commentType';-import { createEffect, createMemo, createSelector } from 'solid-js';-import { reconcile } from 'solid-js/store';+import { createMemo, createSelector } from 'solid-js';+import { usePdfComments } from '../../context/pdf-comments-context';import { useFreeComments } from './freeComments';import { useHighlightComments } from './highlightComments';export const useIsActiveThreadSelector = () => {- const [activeCommentThread] =- usePdfDocument().state.signals.activeCommentThread;const isSelected = createSelector(- activeCommentThread,+ usePdfComments().activeThreadId,(id: ThreadId | null, activeId) => {if (id == null) return false;return id === activeId;@@ -18,27 +15,13 @@ export const useIsActiveThreadSelector = () => {return isSelected;};-export const useGetCommentById = () => {- const { commentMap } = usePdfDocument().state.derived;- return (id: number) => commentMap().get(id);-};--// 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 = () => {+export function usePdfCommentProjection() {const highlightComments = useHighlightComments();const freeComments = useFreeComments();- return createMemo(() => {- return [...highlightComments(), ...freeComments()].length > 0;- });-};--export function useCommentStoreBehavior() {- const highlightComments = useHighlightComments();- const freeComments = useFreeComments();- const [, setComments] = usePdfDocument().state.stores.comments;-- createEffect(() => {- setComments(reconcile([...highlightComments(), ...freeComments()]));- });+ return createMemo(() => [...highlightComments(), ...freeComments()]);}++export const useHasComments = () => {+ const comments = usePdfComments().all;+ return () => comments().length > 0;+};diff --git a/apps/web/src/features/block-pdf/store/comments/freeComments.ts b/apps/web/src/features/block-pdf/store/comments/freeComments.tsindex fd4a86f6ad..d67e867e56 100644--- a/apps/web/src/features/block-pdf/store/comments/freeComments.ts+++ b/apps/web/src/features/block-pdf/store/comments/freeComments.ts@@ -1,8 +1,9 @@-import type {- PdfComment,- PdfReply,- PdfRoot,- ViewerCommentType,+import {+ createPdfDraftThreadId,+ type PdfComment,+ type PdfReply,+ type PdfRoot,+ type ViewerCommentType,} from '@block-pdf/type/comments';import {type IThreadPlaceable,@@ -11,6 +12,7 @@ import {import { useUserId } from '@core/context/user';import { createMemo } from 'solid-js';import { usePdfDocument } from '../../context/pdf-document-context';+import { usePdfViewer } from '../../context/pdf-viewer-context';import { sortComments } from '../commentsResource';export { isThreadPlaceable };@@ -67,15 +69,13 @@ const getFreeCommentThread = (};const useServerCommentPlaceables = () => {- const { resources } = usePdfDocument().state;- const [anchors] = resources.anchors;- const [commentThreads] = resources.commentThreads;+ const annotations = usePdfDocument().annotations;return createMemo<IThreadPlaceable[]>(() => {- const anchorsData = anchors();+ const anchorsData = annotations.anchors();if (!anchorsData || anchorsData.length === 0) return [];- const commentThreadsData = commentThreads();+ const commentThreadsData = annotations.commentThreads();if (!commentThreadsData || commentThreadsData.length === 0) return [];const freeCommentAnchors = anchorsData.filter(@@ -127,9 +127,9 @@ const useServerCommentPlaceables = () => {};export const useNewThreadPlaceable = () => {- const [newPlaceable] = usePdfDocument().state.signals.newPlaceable;+ const draft = usePdfDocument().markup.draft;return createMemo<IThreadPlaceable | undefined>(() => {- const value = newPlaceable();+ const value = draft();if (!value || !isThreadPlaceable(value)) return undefined;return value;});@@ -141,21 +141,21 @@ export const useCommentPlaceables = () => {return createMemo<IThreadPlaceable[]>(() => {const serverArr = serverCommentPlaceables();- const newPlaceable = newThreadPlaceable();- if (!newPlaceable) return serverArr;+ const draft = newThreadPlaceable();+ if (!draft) return serverArr;- return [newPlaceable, ...serverArr];+ return [draft, ...serverArr];});};export const useFreeComments = () => {const userId = useUserId();- const { stores, derived } = usePdfDocument().state;- const [pageHeights] = stores.pageHeight;+ const pdfViewer = usePdfViewer();+ const pageHeights = pdfViewer.root.pageHeights;const commentPlaceables = useCommentPlaceables();return createMemo(() => {- if (!derived.viewerReady()) return [];+ if (!pdfViewer.root.isReady()) return [];const out: PdfComment[] = [];for (const commentPlaceable of commentPlaceables()) {@@ -176,9 +176,13 @@ export const useFreeComments = () => {console.error('User ID not found');continue;}+ const draftThreadId = createPdfDraftThreadId(+ 'free',+ commentPlaceable.internalId+ );const rootComment: PdfRoot = {- id: -1,- rootId: -1,+ id: draftThreadId,+ rootId: draftThreadId,type: 'free',text: '',owner: currentUserId,@@ -186,7 +190,7 @@ export const useFreeComments = () => {createdAt: new Date(),isNew: true,children: [],- threadId: -1,+ threadId: draftThreadId,anchorId: commentPlaceable.internalId,};out.push({ ...rootComment, layout });@@ -206,10 +210,10 @@ export const useFreeComments = () => {};export const useDeleteNewFreeComment = () => {- const { activePlaceableId, newPlaceable } = usePdfDocument().state.signals;+ const markup = usePdfDocument().markup;return () => {- newPlaceable[1](undefined);- activePlaceableId[1](undefined);+ markup.commands.clearDraft();+ markup.commands.clearActive();};};diff --git a/apps/web/src/features/block-pdf/store/comments/highlightComments.ts b/apps/web/src/features/block-pdf/store/comments/highlightComments.tsindex acde526e30..6789b82a34 100644--- a/apps/web/src/features/block-pdf/store/comments/highlightComments.ts+++ b/apps/web/src/features/block-pdf/store/comments/highlightComments.ts@@ -1,17 +1,19 @@import { useHighlightSelection } from '@block-pdf/component/UserHighlight';import { useCurrentPageViewport } from '@block-pdf/signal/pdfViewer';-import type {- PdfComment,- PdfReply,- PdfRoot,- ViewerCommentType,+import {+ createPdfDraftThreadId,+ type PdfComment,+ type PdfReply,+ type PdfRoot,+ type ViewerCommentType,} from '@block-pdf/type/comments';import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';import { useUserId } from '@core/context/user';import { createCallback } from '@solid-primitives/rootless';import { batch, createMemo } from 'solid-js';-import { produce } from 'solid-js/store';+import { usePdfComments } from '../../context/pdf-comments-context';import { usePdfDocument } from '../../context/pdf-document-context';+import { usePdfViewer } from '../../context/pdf-viewer-context';import {Highlight,HighlightType,@@ -19,12 +21,9 @@ import {} from '../../model/Highlight';import { sortComments } from '../commentsResource';import { useDeleteNewComments } from './commentOperations';-import { useGetCommentById } from './commentStore';const getHighlightPos = (highlight: IHighlight, viewportHeight: number) => {try {- // NOTE: got a weird bug where the rects were undefined for some reason- // going to add this try/catch for now since unable to reproduceconst top = highlight.rects.at(0)?.top;if (top === undefined) return null;return top * viewportHeight;@@ -82,12 +81,13 @@ const getHighlightThread = (export const useHighlightComments = () => {const userId = useUserId();- const { stores, derived } = usePdfDocument().state;- const [pageHeights] = stores.pageHeight;- const [highlights] = stores.highlights;+ const pdf = usePdfDocument();+ const pdfViewer = usePdfViewer();+ const pageHeights = pdfViewer.root.pageHeights;+ const highlights = pdf.annotations.highlightsByPage;return createMemo(() => {- if (!derived.viewerReady()) return [];+ if (!pdfViewer.root.isReady()) return [];const out: PdfComment[] = [];for (const [pageIndexStr, pageHighlights] of Object.entries(highlights)) {@@ -106,16 +106,19 @@ export const useHighlightComments = () => {originalYPosition,};- // new highlight threadif (highlight.hasTempThread) {const currentUserId = userId();if (!currentUserId) {console.error('User ID not found');continue;}+ const draftThreadId = createPdfDraftThreadId(+ 'highlight',+ highlight.uuid+ );const rootComment: PdfRoot = {- id: -1,- rootId: -1,+ id: draftThreadId,+ rootId: draftThreadId,type: 'highlight',text: '',owner: currentUserId,@@ -123,7 +126,7 @@ export const useHighlightComments = () => {createdAt: new Date(),isNew: true,children: [],- threadId: -1,+ threadId: draftThreadId,anchorId: highlight.uuid,};out.push({ ...rootComment, layout });@@ -142,100 +145,57 @@ export const useHighlightComments = () => {});};-const useGetHighlightIdFromCommentId = () => {- const getCommentById = useGetCommentById();- return (commentId: number) => {- const comment = getCommentById(commentId);- if (!comment) {- return;- }-- return comment.anchorId;- };-};-export const useDeleteNewHighlightComment = () => {const handleHighlightSelection = useHighlightSelection();- const { signals, stores, derived } = usePdfDocument().state;- const [convertedHighlightThreadId, setConvertedHighlightThreadId] =- signals.convertedHighlightThreadId;- const [, setHighlights] = stores.highlights;- const getHighlightIdFromCommentId = useGetHighlightIdFromCommentId();+ const pdf = usePdfDocument();+ const annotations = pdf.annotations;return () => {- const commentId = -1;- const highlightUuid = getHighlightIdFromCommentId(commentId);- if (!highlightUuid) return;- const highlight = derived.highlightsUuidMap()?.[highlightUuid];- if (!highlight) return;- const pageIndex = highlight.pageNum;-- setHighlights(- pageIndex,- produce((draft) => {- if (!draft) return;-- const highlight = draft[highlightUuid];- if (!highlight) return;-- const isTemporaryHighlight = highlight.hasTempThread;- if (!isTemporaryHighlight) {- console.error(- 'This method should only be used for temporary highlights'- );- return;- }-- // Revert back to a regular highlight if the user cancels the comment operation- if (highlight.uuid === convertedHighlightThreadId()) {- highlight.thread = null;- highlight.hasTempThread = false;- setConvertedHighlightThreadId(null);- setTimeout(() => handleHighlightSelection(highlight.uuid));- return;- }-- // Delete the whole highlight- delete draft[highlightUuid];- })- );+ for (const highlight of Object.values(annotations.highlightsByUuid())) {+ if (!highlight?.hasTempThread) continue;++ const restoredExistingHighlight =+ annotations.commands.cancelTemporaryHighlightCommentDraft(+ highlight.uuid+ );+ if (restoredExistingHighlight) {+ setTimeout(() => handleHighlightSelection(highlight.uuid));+ }+ }};};export function useCreateHighlightCommentAtSelection() {- const { signals, stores } = usePdfDocument().state;- const [selection] = stores.selection;- const [, setHighlights] = stores.highlights;+ const pdf = usePdfDocument();+ const pdfViewer = usePdfViewer();+ const comments = usePdfComments();+ const annotationSelection = pdf.annotationSelection;const currentPageViewport = useCurrentPageViewport();const deleteNewComments = useDeleteNewComments();return createCallback((_e: MouseEvent) => {- signals.disablePageViewClick[1](true);- try {+ pdfViewer.runWithPageClicksDisabled(() => {deleteNewComments();+ pdf.closeSelectionMenu();- // TODO: make the general popup location reactive to the active highlight/term state instead of requiring a manual reset- signals.generalPopupLocation[1](null);-- // create comment from existing highlight- const highlightUnderSelection = selection.highlightsUnderSelection.at(0);+ const highlightUnderSelection =+ annotationSelection().selectedHighlights.at(0);if (highlightUnderSelection) {+ const draftThreadId = createPdfDraftThreadId(+ 'highlight',+ highlightUnderSelection.uuid+ );batch(() => {- signals.convertedHighlightThreadId[1](highlightUnderSelection.uuid);- signals.activeCommentThread[1](-1);-- // NOTE: the new comment is reactively determined in the highlight comments memo- setHighlights(- highlightUnderSelection.pageNum,- highlightUnderSelection.uuid,- (prev) => ({ ...prev, hasTempThread: true })+ comments.activateThread(draftThreadId);+ pdf.annotations.commands.beginExistingHighlightCommentDraft(+ highlightUnderSelection);});return;}- const selectedRange = selection.selection;+ const selectedRange = annotationSelection().nativeSelection;if (!selectedRange) return;const selectionHighlights = getHighlightsFromSelection(@@ -250,47 +210,22 @@ export function useCreateHighlightCommentAtSelection() {});- // create ID to make highlight accessible later- let highlights: IHighlight[] = [];+ const highlights: IHighlight[] = [];for (const highlight of [...selectionHighlights.values()].map(Highlight.toObject)) {- highlights.push({ ...highlight, hasTempThread: true });+ highlights.push(highlight);}- 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 {- signals.disablePageViewClick[1](false);- }+ const activeHighlight = highlights.at(0);+ if (!activeHighlight) return;++ batch(() => {+ pdf.annotations.commands.beginNewHighlightCommentDrafts(highlights);+ comments.activateThread(+ createPdfDraftThreadId('highlight', activeHighlight.uuid)+ );+ });+ });});}--// // NOTE: also works for regular highlights-// export const useGoToHighlightComment = () => {-// const goToHighlight = useGoToHighlight();-// const getHighlightIdFromCommentId = useGetHighlightIdFromCommentId();-// const getHighlightByUuid = useGetHighlightByUuid();-//-// return async (id: string) => {-// let highlightUuid: string | undefined = id;-// if (getHighlightByUuid(id) == null) {-// highlightUuid = getHighlightIdFromCommentId(id);-// }-//-// if (!highlightUuid) return;-// return goToHighlight(highlightUuid);-// };-// };diff --git a/apps/web/src/features/block-pdf/store/commentsResource.ts b/apps/web/src/features/block-pdf/store/commentsResource.tsindex 24683ccdf5..8c8d63835e 100644--- a/apps/web/src/features/block-pdf/store/commentsResource.ts+++ b/apps/web/src/features/block-pdf/store/commentsResource.ts@@ -7,22 +7,14 @@ 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';-import type { CommentThread } from '@service-storage/generated/schemas/commentThread';import type { CreateCommentRequest } from '@service-storage/generated/schemas/createCommentRequest';import type { CreateCommentRequestAnchor } from '@service-storage/generated/schemas/createCommentRequestAnchor';import type { CreateCommentRequestMentions } from '@service-storage/generated/schemas/createCommentRequestMentions';-import type { CreateCommentResponse } from '@service-storage/generated/schemas/createCommentResponse';import type { CreateUnthreadedAnchorRequest } from '@service-storage/generated/schemas/createUnthreadedAnchorRequest';-import type { CreateUnthreadedAnchorResponse } from '@service-storage/generated/schemas/createUnthreadedAnchorResponse';import type { DeleteCommentRequest } from '@service-storage/generated/schemas/deleteCommentRequest';-import type { DeleteCommentResponse } from '@service-storage/generated/schemas/deleteCommentResponse';import type { DeleteUnthreadedAnchorRequest } from '@service-storage/generated/schemas/deleteUnthreadedAnchorRequest';-import type { DeleteUnthreadedAnchorResponse } from '@service-storage/generated/schemas/deleteUnthreadedAnchorResponse';import type { EditAnchorRequest } from '@service-storage/generated/schemas/editAnchorRequest';-import type { EditAnchorResponse } from '@service-storage/generated/schemas/editAnchorResponse';import type { EditCommentRequest } from '@service-storage/generated/schemas/editCommentRequest';-import type { EditCommentResponse } from '@service-storage/generated/schemas/editCommentResponse';-import { batch } from 'solid-js';import { usePdfDocument } from '../context/pdf-document-context';export const sortComments = (a: Comment, b: Comment) => {@@ -36,18 +28,8 @@ export const sortComments = (a: Comment, b: Comment) => {return compareDateAsc(a.createdAt, b.createdAt);};-function useHandleCreateUnthreadedAnchor() {- const [, { mutate: mutateAnchors }] =- usePdfDocument().state.resources.anchors;-- return async (response: CreateUnthreadedAnchorResponse) => {- mutateAnchors((prev) => [...(prev ?? []), response]);- };-}-function useCreateUnthreadedAnchor() {- const { documentId } = usePdfDocument();- const handleCreateUnthreadedAnchor = useHandleCreateUnthreadedAnchor();+ const { annotations, documentId } = usePdfDocument();return async (body: CreateUnthreadedAnchorRequest) => {const result = await storageServiceClient.annotations.createAnchor({@@ -61,32 +43,14 @@ function useCreateUnthreadedAnchor() {}const response = result.value;-- handleCreateUnthreadedAnchor(response);+ annotations.commands.applyCreatedAnchor(response);return true;};}-function useHandleDeleteUnthreadedAnchor() {- 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)- );- if (response.threadId != null) {- mutateCommentThreads((prev) =>- (prev ?? []).filter((t) => t.thread.threadId !== response.threadId)- );- }- };-}-function useDeleteUnthreadedAnchor() {- const handleDeleteUnthreadedAnchor = useHandleDeleteUnthreadedAnchor();+ const annotations = usePdfDocument().annotations;return async (body: DeleteUnthreadedAnchorRequest) => {const result = await storageServiceClient.annotations.deleteAnchor({@@ -99,27 +63,14 @@ function useDeleteUnthreadedAnchor() {}const response = result.value;-- handleDeleteUnthreadedAnchor(response);+ annotations.commands.applyDeletedAnchor(response);return true;};}-function useHandleEditAnchor() {- const [, { mutate: mutateAnchors }] =- usePdfDocument().state.resources.anchors;-- return async (response: EditAnchorResponse) => {- mutateAnchors((prev) => [- ...(prev ?? []).filter((a) => a.uuid !== response.uuid),- response,- ]);- };-}-function useEditAnchor() {- const handleEditAnchor = useHandleEditAnchor();+ const annotations = usePdfDocument().annotations;return async (body: EditAnchorRequest) => {const result = await storageServiceClient.annotations.editAnchor({@@ -132,52 +83,14 @@ function useEditAnchor() {}const response = result.value;-- handleEditAnchor(response);+ annotations.commands.applyEditedAnchor(response);return true;};}-function useHandleCreateComment() {- const { anchors, commentThreads } = usePdfDocument().state.resources;- const [, { mutate: mutateCommentThreads }] = commentThreads;- const [, { mutate: mutateAnchors }] = anchors;-- return async (response: CreateCommentResponse) => {- const commentThread: CommentThread = {- thread: response.thread,- comments: response.comments,- };- const retAnchor = response.anchor;- batch(() => {- if (retAnchor) {- mutateAnchors((prev) => [...(prev ?? []), retAnchor]);- }-- let mutatedExistingThread = false;- mutateCommentThreads((prev) => {- let out: CommentThread[] = [];- for (const thread of prev ?? []) {- if (thread.thread.threadId === commentThread.thread.threadId) {- mutatedExistingThread = true;- out.push(commentThread);- } else {- out.push(thread);- }- }- if (!mutatedExistingThread) {- out.push(commentThread);- }- return out;- });- });- };-}-function useCreateComment() {- const { documentId } = usePdfDocument();- const handleCreateComment = useHandleCreateComment();+ const { annotations, documentId } = usePdfDocument();return async (body: CreateCommentRequest) => {if (body.threadId == null && body.anchor == null) {@@ -196,44 +109,14 @@ function useCreateComment() {}const response = result.value;-- handleCreateComment(response);+ annotations.commands.applyCreatedComment(response);return response;};}-function useHandleEditComment() {- const [, { mutate: mutateCommentThreads }] =- usePdfDocument().state.resources.commentThreads;-- return async (response: EditCommentResponse) => {- mutateCommentThreads((prev) => {- let out: CommentThread[] = [];- for (const thread of prev ?? []) {- if (thread.thread.threadId === response.threadId) {- const commentThread = {- thread: thread.thread,- comments: thread.comments.map((comment) => {- if (comment.commentId === response.commentId) {- const editedComment: Comment = response;- return editedComment;- }- return comment;- }),- };- out.push(commentThread);- } else {- out.push(thread);- }- }- return out;- });- };-}-export function useEditCommentResource() {- const handleEditComment = useHandleEditComment();+ const annotations = usePdfDocument().annotations;return async (commentId: number, body: EditCommentRequest) => {const result = await storageServiceClient.annotations.editComment({@@ -247,58 +130,14 @@ export function useEditCommentResource() {}const response = result.value;-- handleEditComment(response);+ annotations.commands.applyEditedComment(response);return true;};}-function useHandleDeleteComment() {- 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- )- );- } else {- mutateCommentThreads((prev) => {- let out: CommentThread[] = [];- for (const commentThread of prev ?? []) {- if (commentThread.thread.threadId === response.thread.threadId) {- const comments = commentThread.comments.filter(- (c) => c.commentId !== response.commentId- );- out.push({ thread: commentThread.thread, comments });- } else {- out.push(commentThread);- }- }- return out;- });- }-- const deletedAnchor = response.anchor;- if (!deletedAnchor) return;-- if (deletedAnchor.deleted) {- mutateAnchors((prev) =>- (prev ?? []).filter((a) => a.uuid !== deletedAnchor.uuid)- );- }- });- };-}-export function useDeleteCommentResource() {- const handleDeleteComment = useHandleDeleteComment();+ const annotations = usePdfDocument().annotations;return async (commentId: number, body: DeleteCommentRequest) => {const result = await storageServiceClient.annotations.deleteComment({@@ -312,8 +151,7 @@ export function useDeleteCommentResource() {}const response = result.value;-- handleDeleteComment(response);+ annotations.commands.applyDeletedComment(response);return true;};@@ -338,7 +176,6 @@ export function useCreateFreeCommentResource() {page,fileType: 'pdf',anchorType: 'free-comment',- // position infoxPct: placeable.position.xPct,yPct: placeable.position.yPct,widthPct: placeable.position.widthPct,@@ -515,13 +352,7 @@ export function useEditPdfFreeCommentAnchor() {export function usePdfCommentRealtimeBehavior() {const currentUserId = useUserId();- const { documentId } = usePdfDocument();- const handleCommentUpdate = useHandleCreateComment();- const handleCreateUnthreadedAnchor = useHandleCreateUnthreadedAnchor();- const handleEditComment = useHandleEditComment();- const handleEditAnchor = useHandleEditAnchor();- const handleDeleteComment = useHandleDeleteComment();- const handleDeleteUnthreadedAnchor = useHandleDeleteUnthreadedAnchor();+ const { annotations, documentId } = usePdfDocument();createConnectionWebsocketEffect((msg) => {if (msg.type === 'comment') {@@ -541,22 +372,34 @@ export function usePdfCommentRealtimeBehavior() {switch (incrementalUpdate.updateType) {case 'create-comment':- handleCommentUpdate(incrementalUpdate.payload.response);+ annotations.commands.applyCreatedComment(+ incrementalUpdate.payload.response+ );break;case 'create-anchor':- handleCreateUnthreadedAnchor(incrementalUpdate.payload.response);+ annotations.commands.applyCreatedAnchor(+ incrementalUpdate.payload.response+ );break;case 'edit-comment':- handleEditComment(incrementalUpdate.payload.response);+ annotations.commands.applyEditedComment(+ incrementalUpdate.payload.response+ );break;case 'edit-anchor':- handleEditAnchor(incrementalUpdate.payload.response);+ annotations.commands.applyEditedAnchor(+ incrementalUpdate.payload.response+ );break;case 'delete-comment':- handleDeleteComment(incrementalUpdate.payload.response);+ annotations.commands.applyDeletedComment(+ incrementalUpdate.payload.response+ );break;case 'delete-anchor':- handleDeleteUnthreadedAnchor(incrementalUpdate.payload.response);+ annotations.commands.applyDeletedAnchor(+ incrementalUpdate.payload.response+ );break;default:console.error('unknown comment update type', msg);diff --git a/apps/web/src/features/block-pdf/store/definitionPopup.ts b/apps/web/src/features/block-pdf/store/definitionPopup.tsdeleted file mode 100644index e1bf54b4fc..0000000000--- a/apps/web/src/features/block-pdf/store/definitionPopup.ts+++ /dev/null@@ -1,247 +0,0 @@-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';--/* --------------------------------------------------------------------------- *- * Helper functions- * --------------------------------------------------------------------------- */--const MIN_SIDE_PADDING = 20;-const WIDTH_PADDING = 50;--function calculateSizing(- term: Readonly<Term>,- draft: Partial<ISectionPopupContext>-): {- width: number;- truncated: boolean;-} {- const text = Array.from(term.definition.childNodes)- .filter((n) => n.nodeName.includes('span'))- .map((el) => decodeString(el as Element))- .join('');-- const { pageWidth } = draft;-- const rowWidth = pageWidth ?? 0;-- let width = 0;- let truncated = false;-- const maxWidth = rowWidth - WIDTH_PADDING - 2 * MIN_SIDE_PADDING;- const minWidth = Math.min(550, maxWidth);- const targetWidth = Math.min(550, maxWidth);-- const singleLineWidth = estimateTextWidth(text);- if (singleLineWidth < targetWidth) {- width = Math.max(minWidth, singleLineWidth + WIDTH_PADDING);- } else {- let targetLines = 3;- let numLinesWithTargetWidth = Math.ceil(singleLineWidth / targetWidth);- if (numLinesWithTargetWidth <= targetLines) {- width = targetWidth;- } else {- // If too many lines are needed to fit the target width, increase the width until- // either the number of lines is below the target or the max width is reached- if (numLinesWithTargetWidth > 5) {- targetLines += Math.ceil((numLinesWithTargetWidth - 5) / 2);- }- width = Math.min(- maxWidth,- (targetWidth * numLinesWithTargetWidth) / targetLines- );- }-- const estimatedLines = Math.ceil(singleLineWidth / width);- width = width + WIDTH_PADDING;- if (estimatedLines > MAX_LINES) {- truncated = true;- }- }-- return {- width,- truncated,- };-}--function updateTermIDs(draft: Partial<ISectionPopupContext>): void {- draft.termIDs = [...new Set(draft.terms?.map((term) => term.id))];-}--function updateTermIDToSizingMap(draft: Partial<ISectionPopupContext>): void {- draft.termIDToSizingMap = Object.fromEntries(- draft.terms?.map((term) => [term.id, calculateSizing(term, draft)]) ?? []- );-}--/* --------------------------------------------------------------------------- *- * Context- * --------------------------------------------------------------------------- */--// TODO terms that are actually the same definition have different IDs-// As a result, you can open several of the same definition-export interface ISectionPopupContext {- terms: Term[];- termIDs: Array<string>;- termIDToSizingMap: Partial<- Record<- string,- {- width: number;- truncated: boolean;- }- >- >;-- pageWidth: number | null;- element: Element | null;-}--type SetRectsAction = {- type: 'SET_RECTS';- pageWidth: number;- // element: Element;-};--type SetTermAction = {- type: 'SET_TERM';- term: Term;-};--type SetTermFromElementAction = {- type: 'SET_TERM_FROM_ELEMENT';- term: Term;- pageWidth: number;- element: Element;-};--type AddNextTermAction = {- type: 'ADD_NEXT_TERM';- term: Term;-};--// Remove all terms after the specified index-type RemoveNextTermsAction = {- type: 'REMOVE_NEXT_TERMS';- index: number;-};--type RemovePopupsAction = {- type: 'REMOVE_POPUPS';-};--type ISectionPopupAction =- | SetTermAction- | RemovePopupsAction- | AddNextTermAction- | RemoveNextTermsAction- | SetTermFromElementAction- | SetRectsAction;--const handler = (- draft: Partial<ISectionPopupContext>,- action: ISectionPopupAction-) => {- switch (action.type) {- case 'SET_RECTS':- draft.pageWidth = action.pageWidth;- // draft.element = action.element as unknown as Draft<Element>;-- updateTermIDToSizingMap(draft);-- break;- case 'SET_TERM_FROM_ELEMENT':- draft.pageWidth = action.pageWidth;- draft.element = action.element;- draft.terms = [action.term];- updateTermIDs(draft);- updateTermIDToSizingMap(draft);-- break;- case 'SET_TERM':- draft.terms = [action.term];- updateTermIDs(draft);- updateTermIDToSizingMap(draft);-- break;- case 'ADD_NEXT_TERM':- if (draft.terms?.length === 0) {- console.error(- 'Invalid state, cannot add term if there is not already a term'- );- return;- }-- if (draft.termIDs?.includes(action.term.id)) {- return; // Do nothing- }-- draft.terms?.push(action.term);- updateTermIDs(draft);- updateTermIDToSizingMap(draft);-- break;- case 'REMOVE_NEXT_TERMS':- const { index } = action;-- if (!draft.terms) {- return;- }-- if (index === draft.terms.length - 1) {- // There are no next terms -> nothing to remove- return;- }-- if (index < 0 || index >= draft.terms.length) {- console.error('Invalid term index provided');- }-- draft.terms = draft.terms.slice(0, index + 1);- updateTermIDs(draft);- updateTermIDToSizingMap(draft);-- break;- case 'REMOVE_POPUPS':- draft.terms = [];-- // Clear rectangles- draft.pageWidth = null;- draft.element = null;-- updateTermIDs(draft);- updateTermIDToSizingMap(draft);- break;- default:- throw new InvalidActionError(action);- }-};--export function usePopupContextUpdate(isPopup: boolean) {- const { rootDefinition, popupDefinition } = usePdfDocument().state.stores;- const setStore = isPopup ? popupDefinition[1] : rootDefinition[1];-- return (action: ISectionPopupAction) => {- setStore(produce<ISectionPopupContext>((state) => handler(state, action)));- };-}--export function usePopupStore(isPopup: boolean) {- const { rootDefinition, popupDefinition } = usePdfDocument().state.stores;- const store = isPopup ? popupDefinition[0] : rootDefinition[0];-- return {- terms: () => store.terms,- element: () => store.element,- termIDToSizingMap: () => store.termIDToSizingMap,- pageWidth: () => store.pageWidth,- };-}diff --git a/apps/web/src/features/block-pdf/store/highlight.ts b/apps/web/src/features/block-pdf/store/highlight.tsindex adb37cf4bd..cdc0084a94 100644--- a/apps/web/src/features/block-pdf/store/highlight.ts+++ b/apps/web/src/features/block-pdf/store/highlight.ts@@ -1,7 +1,5 @@import { getHighlightsFromSelection } from '@block-pdf/util/pdfjsUtils';-import { createCallback } from '@solid-primitives/rootless';-import { batch, createEffect } from 'solid-js';-import { produce, reconcile } from 'solid-js/store';+import { batch } from 'solid-js';import { usePdfDocument } from '../context/pdf-document-context';import { Highlight, type IHighlight } from '../model/Highlight';import {@@ -9,126 +7,23 @@ import {useDeleteUnthreadedHighlightResource,} from './commentsResource';-/** Map of highlight uuid to highlights */-export type HighlightUuidMap = Partial<Record<string, IHighlight>>;-/** Map of highlight page index to highlights uuid map on that page. */-export type HighlightPageMap = Partial<Record<number, HighlightUuidMap>>;--/**- * Keeps the document-scoped highlight store synchronized with annotation- * resources. Invoke once inside the PDF document provider.- */-export function useSyncHighlightStore() {- const pdf = usePdfDocument();- const [, setHighlightStore] = pdf.state.stores.highlights;- const [anchorsData] = pdf.state.resources.anchors;- const [commentThreadsData] = pdf.state.resources.commentThreads;-- createEffect(() => {- setHighlightStore(reconcile({}));-- const anchors = anchorsData();- if (!anchors || anchors.length === 0) return;-- const commentThreads = commentThreadsData() ?? [];- const highlightAnchors = anchors.filter(- (anchor) => anchor.anchorType === '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) {- setHighlightStore(highlight.pageNum, (previous) => ({- ...previous,- [highlight.uuid]: highlight,- }));- }- });- });-}--export const useClearHighlightStore = () => {- const [, setHighlightStore] = usePdfDocument().state.stores.highlights;- return () => {- setHighlightStore(reconcile({}));- };-};--export const useClearSelectionHighlights = () => {- const [, setSelectionStore] = usePdfDocument().state.stores.selection;- return () => {- setSelectionStore(- reconcile({- highlightsUnderSelection: [],- selection: null,- selectionString: '',- })- );- };-};-export const useSetSelectionHighlights = () => {- const { highlights, selection } = usePdfDocument().state.stores;- const [highlightStore] = highlights;- const [, setSelectionStore] = selection;+ const pdf = usePdfDocument();+ const highlightsByPage = pdf.annotations.highlightsByPage;return (selection: Selection) => {if (selection.isCollapsed) return;- setSelectionStore({- highlightsUnderSelection: [],- selection,- selectionString: selection.toString(),- });+ pdf.setNativeSelection(selection);batch(() => {+ const selectedHighlights: IHighlight[] = [];const selectionHighlights = getHighlightsFromSelection(selection);for (let [pageIndex,selectionHighlight,] of selectionHighlights.entries()) {- const existingHighlights = highlightStore[pageIndex];+ const existingHighlights = highlightsByPage[pageIndex];if (!existingHighlights) continue;const overlappingHighlights = Object.values(existingHighlights).filter(@@ -136,41 +31,13 @@ export const useSetSelectionHighlights = () => {!!existingHighlight &&Highlight.overlaps(selectionHighlight, existingHighlight));-- setSelectionStore(- produce((state) => {- if (!state.highlightsUnderSelection)- state.highlightsUnderSelection = [];-- state.highlightsUnderSelection.push(...overlappingHighlights);- })- );+ selectedHighlights.push(...overlappingHighlights);}+ pdf.replaceSelectedHighlights(selectedHighlights);});};};-export const useAddNewHighlightComments = () => {- const [, setHighlightStore] = usePdfDocument().state.stores.highlights;- return (highlights: IHighlight[]) =>- setHighlightStore(- produce((state) => {- for (const highlight of highlights) {- const pageNum = highlight.pageNum;- const uuid = highlight.uuid;-- if (state[pageNum]) {- // Update the existing page highlights- state[pageNum][uuid] = highlight;- } else {- // Create a new entry for the page if it doesn't exist- state[pageNum] = { [uuid]: highlight };- }- }- })- );-};-export const useAddNewHighlights = () => {const addHighlight = useCreateUnthreadedHighlightResource();@@ -183,26 +50,10 @@ export const useAddNewHighlights = () => {export function useRemoveHighlight() {const deleteHighlight = useDeleteUnthreadedHighlightResource();- const [, setGeneralPopupLocation] =- usePdfDocument().state.signals.generalPopupLocation;+ const pdf = usePdfDocument();return (uuid: string) => {- setGeneralPopupLocation(null);+ pdf.closeSelectionMenu();deleteHighlight(uuid);};}--export const useGetHighlightByUuid = () => {- const highlightsUuidMap = usePdfDocument().state.derived.highlightsUuidMap;- return createCallback((uuid: string) => {- return highlightsUuidMap()?.[uuid];- });-};--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.test.tsx b/apps/web/src/features/block-pdf/store/placeables.test.tsxnew file mode 100644index 0000000000..17e4debeef--- /dev/null+++ b/apps/web/src/features/block-pdf/store/placeables.test.tsx@@ -0,0 +1,147 @@+import { cleanup, render } from '@solidjs/testing-library';+import { afterEach, describe, expect, it, vi } from 'vitest';+import {+ type PdfDocumentContextValue,+ PdfDocumentProvider,+ usePdfDocument,+} from '../context/pdf-document-context';+import { PdfViewerProvider } from '../context/pdf-viewer-context';+import {+ type IPlaceable,+ PayloadMode,+ type PayloadType,+} from '../type/placeables';+import { useModifyPlaceable } from './placeables';++vi.mock('../queries/annotations', () => ({+ getPdfAnchors: vi.fn(async () => []),+ getPdfComments: vi.fn(async () => []),+}));++vi.mock('@core/context/user', () => ({+ useUserId: () => () => 'user-1',+}));++vi.mock('../signal/pdfViewer', () => ({+ useIsPopup: () => false,+}));++vi.mock('./comments/commentOperations', () => ({+ useDeleteComment: () => vi.fn(),+ useDeleteNewComments: () => vi.fn(),+}));++vi.mock('./comments/freeComments', () => ({+ isThreadPlaceable: () => false,+ useCommentPlaceables: () => () => [],+}));++vi.mock('./commentsResource', () => ({+ useEditPdfFreeCommentAnchor: () => vi.fn(),+}));++afterEach(cleanup);++function textPlaceable(text: string): IPlaceable {+ return {+ internalId: 'placeable-1',+ allowableEdits: {+ allowResize: true,+ allowTranslate: true,+ allowRotate: true,+ allowDelete: true,+ lockAspectRatio: false,+ },+ wasEdited: false,+ wasDeleted: false,+ pageRange: new Set([0]),+ position: {+ xPct: 0.1,+ yPct: 0.2,+ widthPct: 0.3,+ heightPct: 0.4,+ rotation: 0,+ },+ payload: {+ color: { red: 0, green: 0, blue: 0, alpha: 1 },+ fontSize: 10,+ bold: false,+ fontFamily: 'Times New Roman',+ text,+ italic: false,+ underlined: false,+ textType: 'pdf-text',+ },+ payloadType: PayloadMode.FreeTextAnnotation,+ shouldLockOnSave: false,+ originalPage: 0,+ originalIndex: -1,+ };+}++type PlaceableTestApi = {+ context: PdfDocumentContextValue;+ modifyPlaceable: ReturnType<typeof useModifyPlaceable>;+};++function Probe(props: { capture: (api: PlaceableTestApi) => void }) {+ props.capture({+ context: usePdfDocument(),+ modifyPlaceable: useModifyPlaceable(),+ });+ return null;+}++function setup(): PlaceableTestApi {+ let api!: PlaceableTestApi;+ render(() => (+ <PdfDocumentProvider+ documentId="document-1"+ documentName="document-1.pdf"+ permissions={{+ canComment: true,+ canEdit: true,+ isOwner: true,+ }}+ >+ <PdfViewerProvider>+ <Probe capture={(value) => (api = value)} />+ </PdfViewerProvider>+ </PdfDocumentProvider>+ ));+ return api;+}++describe('useModifyPlaceable', () => {+ it('updates a matching placeable and records one edit', () => {+ const { context, modifyPlaceable } = setup();+ const original = textPlaceable('before');+ context.model.commands.replacePlaceables([original]);++ const updated = textPlaceable('after');++ expect(modifyPlaceable(0, updated)).toBe(true);+ expect(context.model.modificationData.placeables[0]).toEqual({+ ...updated,+ wasEdited: true,+ });+ expect(context.model.revision()).toBe(1);+ });++ it('rejects missing or mismatched placeables without recording an edit', () => {+ const { context, modifyPlaceable } = setup();+ const original = textPlaceable('before');+ context.model.commands.replacePlaceables([original]);++ const mismatched = {+ ...textPlaceable('after'),+ payloadType: PayloadMode.Signature as PayloadType,+ } as IPlaceable;++ expect(modifyPlaceable(-1, original)).toBe(false);+ expect(modifyPlaceable(1, original)).toBe(false);+ expect(modifyPlaceable(0, mismatched)).toBe(false);+ expect(context.model.modificationData.placeables).toEqual([original]);+ expect(context.model.revision()).toBe(0);+ });+});diff --git a/apps/web/src/features/block-pdf/store/placeables.ts b/apps/web/src/features/block-pdf/store/placeables.tsindex 2d9470e607..af08709e68 100644--- a/apps/web/src/features/block-pdf/store/placeables.ts+++ b/apps/web/src/features/block-pdf/store/placeables.ts@@ -5,11 +5,8 @@ import {useDeleteComment,useDeleteNewComments,} from '@block-pdf/store/comments/commentOperations';-import type {- Annotation,- // AnnotationFlag,- ShapeType,-} from '@block-pdf/type/pdfJs';+import { createPdfDraftThreadId } from '@block-pdf/type/comments';+import type { Annotation, ShapeType } from '@block-pdf/type/pdfJs';import {type IPlaceable,type IPlaceablePayload,@@ -20,7 +17,6 @@ import {PayloadMode,type PayloadType,} from '@block-pdf/type/placeables';-// 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 { useUserId } from '@core/context/user';@@ -28,7 +24,9 @@ import { createCallback } from '@solid-primitives/rootless';import type { PageViewport } from 'pdfjs-dist';import { batch, createEffect, createMemo } from 'solid-js';import { v7 as uuid7 } from 'uuid';+import { usePdfComments } from '../context/pdf-comments-context';import { usePdfDocument } from '../context/pdf-document-context';+import { usePdfViewer } from '../context/pdf-viewer-context';import {isThreadPlaceable,useCommentPlaceables,@@ -52,7 +50,7 @@ const DEFAULT_APPEARANCE_PAYLOAD: AppearancePayload = {};export function usePlaceableIdMap() {- const [modificationData] = usePdfDocument().state.stores.modificationData;+ const modificationData = usePdfDocument().model.modificationData;const commentPlaceables = useCommentPlaceables();return createMemo(() => {@@ -65,61 +63,21 @@ export function usePlaceableIdMap() {function useCurrentScale() {const isPopup = useIsPopup();- const { currentScale, popupCurrentScale } = usePdfDocument().state.derived;+ const viewer = usePdfViewer();+ const currentScale = isPopup+ ? viewer.popup.currentScale+ : viewer.root.currentScale;- return () => (isPopup ? popupCurrentScale() : currentScale()) ?? 1;+ return () => currentScale() ?? 1;}function useGetPopupContextViewer() {const isPopup = useIsPopup();- const { rootViewer, popupViewer } = usePdfDocument().state.signals;+ const viewer = usePdfViewer();- return () => (isPopup ? popupViewer[0]() : rootViewer[0]());+ return (isPopup ? viewer.popup : viewer.root).instance;}-function useDoEdit() {- const [, setNumOperations] = usePdfDocument().state.signals.numOperations;-- return () => setNumOperations((previous) => previous + 1);-}--// function convertTextAnnotationToThread(-// annotation: Annotation,-// pageIndex: number-// ): IThread {-// let editDate: Date = reformatPdfjsDate(-// annotation.modificationDate,-// annotation.creationDate-// );-// const comment: IComment = {-// content: annotation.contentsObj!.str,-// sender: annotation.titleObj?.str ?? '',-// editDate: editDate,-// id: annotation.id,-// };-// const newThread: IThread = {-// headID: annotation.id,-// page: pageIndex,-// comments: [comment],-// isResolved: annotation.annotationFlags === AnnotationFlag.HIDDEN,-// };-// return newThread;-// }--// function convertTextAnnotationToComment(annotation: Annotation) {-// let editDate: Date = reformatPdfjsDate(-// annotation.modificationDate,-// annotation.creationDate-// );-// const comment: IComment = {-// content: annotation.contentsObj!.str,-// sender: annotation.titleObj?.str ?? '',-// editDate: editDate,-// id: annotation.id,-// };-// return comment;-// }-function convertRawRGBToColor(r: string | number,g: string | number,@@ -183,7 +141,6 @@ function parseDefaultAppearance(appearance: string): AppearancePayload {};}-// Helper function to convert internal id (uuid) to array index.function internalIdToIndex(placeables: IPlaceable[], id: string) {return placeables.findIndex((p) => p.internalId === id);}@@ -274,7 +231,6 @@ function convertShapeAnnotationToPlaceable({const borderColor =c && borderWidth ? convertRawRGBToColor(c[0], c[1], c[2]) : DEFAULT_COLOR;const ic = annotation.rawInteriorColor;- // If interior color wasn't set, make sure alpha gets set to 0const fillColor = ic? convertRawRGBToColor(ic[0], ic[1], ic[2]): DEFAULT_COLOR;@@ -317,7 +273,6 @@ export function annotationsToPlaceables({pageViewport: PageViewport;}): IPlaceable[] {let placeables: IPlaceable[] = [];- // let threads = new Array<IThread>();// We will increment this when we come across annotation placeables// The list that increments it needs to match the pdfserver as they@@ -338,23 +293,6 @@ export function annotationsToPlaceables({validAnnotationPlaceableIndex += 1;}- // TODO: fully deprecate- // Handle plain text annotations for comments & threads- // if (annotation.subtype === 'Text' && !!annotation.contentsObj?.str) {- // if (annotation.inReplyTo == null) {- // threads.push(convertTextAnnotationToThread(annotation, pageIndex));- // }- // if (annotation.inReplyTo != null) {- // // eslint-disable-next-line no-loop-func- // const replyTo = threads.find((t) => t.headID === annotation.inReplyTo);- // if (replyTo) {- // const comment = convertTextAnnotationToComment(annotation);- // replyTo.comments.push(comment);- // }- // }- // }-- // Handle free text annotations that convert to activateable placeablesif (annotation.subtype === 'FreeText') {placeables.push(convertFreeTextToPlaceable({@@ -366,7 +304,6 @@ export function annotationsToPlaceables({);}- // Handle shape annotations that convert to activateable placeablesif (['Circle', 'Square', 'Polygon'].includes(annotation.subtype)) {placeables.push(convertShapeAnnotationToPlaceable({@@ -379,34 +316,6 @@ export function annotationsToPlaceables({}}- // Zip threads and replies back together- // const finalThreads = threads.map((thread) => {- // const payload: IThread = thread;- // let headAnnot = annotations.find((a) => a.id === thread.headID);- // const position = getPlaceablePosition(headAnnot?.rect, pageViewport);- // const threadPlaceable: IPlaceable = {- // allowableEdits: {- // allowResize: false,- // allowTranslate: true,- // allowRotate: false,- // allowDelete: true,- // lockAspectRatio: true,- // },- // pageRange: new Set<number>([pageIndex]),- // position,- // shouldLockOnSave: false,- // originalPage: pageIndex,- // originalIndex: -1,- // payload,- // payloadType: 'thread',- // wasEdited: false,- // wasDeleted: false,- // };- // return threadPlaceable;- // });-- // Return all placeables together- // return [finalThreads, placeables].flat(1);return placeables;}@@ -481,15 +390,7 @@ function useMakeThread() {function useMakeSignature() {const getViewer = useGetPopupContextViewer();const currentScale = useCurrentScale();- // previously created signatures- // const selectedSavedSignature = useSignatureValue();const defaultSignature: ISignature | undefined = undefined;- // const defaultSignature = useMemo(- // () => selectedSavedSignature.options.at(0),- // [selectedSavedSignature.options]- // );-- // const prompt = usePrompt();return (e: MouseEvent, pageRef: HTMLElement, index: number): IPlaceable => {const curViewer = getViewer();@@ -497,13 +398,6 @@ function useMakeSignature() {let payload: ISignature | undefined = defaultSignature;if (!payload) {- // // prompt the user for their initial signature- // const res = await prompt<typeof EditSignatureDialog>((args) => (- // <EditSignatureDialog {...args} />- // ));- // // short circuit if user declined, we wont create a signature- // if (res.isErr()) return null;- // payload = res.value;payload = {base64: null,dateTime: Date.now(),@@ -573,7 +467,6 @@ const textAnnotationProperties = {function useMakeTextAnnotation() {const getViewer = useGetPopupContextViewer();- const [fontPreference] = usePdfDocument().state.signals.fontPreference;const currentScale = useCurrentScale();return (@@ -584,13 +477,10 @@ function useMakeTextAnnotation() {): ITextBoxPlaceable => {const curViewer = getViewer();const curScale = currentScale();- const fontFamily = fontPreference();+ const fontFamily = DEFAULT_APPEARANCE_PAYLOAD.family;let position: IPlaceablePosition;if (e) {- // At default zoom and font size, 250px can hold ~15-20 characters horizontally- // We want to vertically position so that the center of our textbox is at the center- // of the text cursor caret.const cursorOffsetY = 14;const cursorOffsetX = 14;@@ -615,7 +505,6 @@ function useMakeTextAnnotation() {rotation: 0,};} else {- // Create a new text box at the top left of the page (e.g. on copy/paste with no MouseEvent)const { width, height } = pageRef.getBoundingClientRect();position = {xPct: 0.01,@@ -665,16 +554,16 @@ function useMakeTextAnnotation() {*/export function useSyncActivePlaceableWithCommentThread() {const placeableIdMap = usePlaceableIdMap();- const {- activePlaceableId: [activePlaceableId, setActivePlaceableId],- activeCommentThread: [activeCommentThread],- } = usePdfDocument().state.signals;+ const pdf = usePdfDocument();+ const comments = usePdfComments();+ const activeId = pdf.markup.activeId;+ const activeCommentThreadId = comments.activeThreadId;createEffect(() => {- const activeThreadId = activeCommentThread();- const activePlaceableIdValue = activePlaceableId();- const activePlaceable = activePlaceableIdValue- ? placeableIdMap()[activePlaceableIdValue]+ const activeThreadId = activeCommentThreadId();+ const activeIdValue = activeId();+ const activePlaceable = activeIdValue+ ? placeableIdMap()[activeIdValue]: null;if (@@ -682,7 +571,7 @@ export function useSyncActivePlaceableWithCommentThread() {activePlaceable &&isThreadPlaceable(activePlaceable)) {- setActivePlaceableId(undefined);+ pdf.markup.commands.clearActive();}if (activeThreadId == null) return;@@ -693,7 +582,7 @@ export function useSyncActivePlaceableWithCommentThread() {);if (matchingFreeCommentPlaceable) {- setActivePlaceableId(matchingFreeCommentPlaceable.internalId);+ pdf.markup.commands.activate(matchingFreeCommentPlaceable.internalId);}});}@@ -703,11 +592,7 @@ export function useCreatePlaceable() {const makeTextAnnotation = useMakeTextAnnotation();const makeSignature = useMakeSignature();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;+ const comments = usePdfComments();return async (e: MouseEvent) => {let placeable: IPlaceable | null;@@ -718,7 +603,7 @@ export function useCreatePlaceable() {}const index = PageModel.getPageIndex(pageRef)!;- switch (mode()) {+ switch (pdf.markup.mode()) {case PayloadMode.Thread:placeable = makeThread(e, pageRef, index);break;@@ -734,15 +619,17 @@ export function useCreatePlaceable() {batch(() => {if (!isThreadPlaceable(placeable)) {- setPdfModificationData('placeables', (prev) => [...prev, placeable]);+ pdf.model.commands.appendPlaceable(placeable);} else {- setActiveCommentThread(-1);+ comments.activateThread(+ createPdfDraftThreadId('free', placeable.internalId)+ );}- setActivePlaceableId(placeable.internalId);- setNewPlaceable(placeable);+ pdf.markup.commands.activate(placeable.internalId);+ pdf.markup.commands.setDraft(placeable);});- setMode(PayloadMode.NoMode);+ pdf.markup.commands.cancelPlacement();e.stopPropagation();e.preventDefault();@@ -750,34 +637,16 @@ export function useCreatePlaceable() {}export function useModifyPlaceable() {- const [modificationData, setModificationData] =- usePdfDocument().state.stores.modificationData;- const doEdit = useDoEdit();-- return (index: number, newPlaceable: IPlaceable) => {- if (index < 0) return false;-- const placeables = modificationData.placeables;-- const currPlaceable = placeables.at(index);- if (!currPlaceable) return false;+ const model = usePdfDocument().model;- if (newPlaceable.payloadType !== currPlaceable.payloadType) return false;-- setModificationData('placeables', index, {- ...newPlaceable,- wasEdited: true,- });-- doEdit();-- return true;+ return (index: number, updatedPlaceable: IPlaceable) => {+ return model.commands.updatePlaceable(index, updatedPlaceable);};}export function useModifyPayload() {const modifyPlaceable = useModifyPlaceable();- const [modificationData] = usePdfDocument().state.stores.modificationData;+ const modificationData = usePdfDocument().model.modificationData;return <T extends PayloadType>(id: string,@@ -793,7 +662,7 @@ export function useModifyPayload() {if (!existingPlaceable) return false;if (payloadType !== existingPlaceable.payloadType) return false;- const newPlaceable = {+ const updatedPlaceable = {...existingPlaceable,payload: {...existingPlaceable.payload,@@ -801,32 +670,16 @@ export function useModifyPayload() {},} as IPlaceable;- return modifyPlaceable(index, newPlaceable);+ return modifyPlaceable(index, updatedPlaceable);};}export function useDeletePlaceable() {const pdf = usePdfDocument();- const [modificationData, setModificationData] =- pdf.state.stores.modificationData;- const [, setActivePlaceable] = pdf.state.signals.activePlaceableId;+ const modificationData = pdf.model.modificationData;const placeableIdMap = usePlaceableIdMap();- const doEdit = useDoEdit();const deleteComment = useDeleteComment();- const arrayDelete = (index: number) => {- if (index < 0 || index >= modificationData.placeables.length) return false;-- setModificationData('placeables', (prev) => [- ...prev.slice(0, index),- ...prev.slice(index + 1),- ]);-- doEdit();-- return true;- };-return createCallback((uuid: string) => {const placeable = placeableIdMap()[uuid];if (!placeable) {@@ -846,9 +699,9 @@ export function useDeletePlaceable() {const index = internalIdToIndex(modificationData.placeables, uuid);- let deleted = arrayDelete(index);+ const deleted = pdf.model.commands.removePlaceable(index);if (deleted) {- setActivePlaceable((prev) => (prev === uuid ? undefined : prev));+ pdf.markup.commands.clearActiveIf(uuid);}return deleted;});@@ -858,8 +711,7 @@ export function useUpdatePlaceablePosition() {const modifyPlaceable = useModifyPlaceable();const editPdfFreeCommentAnchor = useEditPdfFreeCommentAnchor();const pdf = usePdfDocument();- const [, setNewPlaceable] = pdf.state.signals.newPlaceable;- const [modificationData] = pdf.state.stores.modificationData;+ const modificationData = pdf.model.modificationData;const placeableIdMap = usePlaceableIdMap();return createCallback(@@ -911,57 +763,57 @@ export function useUpdatePlaceablePosition() {widthPct,heightPct,};- let newPlaceable = {+ let updatedPlaceable = {...placeable,position: newPosition,};if (!samePage) {- newPlaceable = {- ...newPlaceable,+ updatedPlaceable = {+ ...updatedPlaceable,pageRange: new Set([pageNum]),originalPage: pageNum,};- if (isThreadPlaceable(newPlaceable)) {- if ((newPlaceable as IThreadPlaceable).isNew) {- setNewPlaceable(newPlaceable);+ if (isThreadPlaceable(updatedPlaceable)) {+ if ((updatedPlaceable as IThreadPlaceable).isNew) {+ pdf.markup.commands.setDraft(updatedPlaceable);return;} else {return editPdfFreeCommentAnchor(uuid, {- xPct: newPlaceable.position.xPct,- yPct: newPlaceable.position.yPct,- widthPct: newPlaceable.position.widthPct,- heightPct: newPlaceable.position.heightPct,+ xPct: updatedPlaceable.position.xPct,+ yPct: updatedPlaceable.position.yPct,+ widthPct: updatedPlaceable.position.widthPct,+ heightPct: updatedPlaceable.position.heightPct,page: pageNum,});}}- switch (newPlaceable.payloadType) {+ switch (updatedPlaceable.payloadType) {case PayloadMode.FreeTextAnnotation:case PayloadMode.Signature:break;default:- console.error('Unhandled payload type', newPlaceable.payload);+ console.error('Unhandled payload type', updatedPlaceable.payload);return false;}}- if (isThreadPlaceable(newPlaceable)) {- if (newPlaceable.isNew) {- setNewPlaceable(newPlaceable);+ if (isThreadPlaceable(updatedPlaceable)) {+ if (updatedPlaceable.isNew) {+ pdf.markup.commands.setDraft(updatedPlaceable);return;} else {return editPdfFreeCommentAnchor(uuid, {- xPct: newPlaceable.position.xPct,- yPct: newPlaceable.position.yPct,- widthPct: newPlaceable.position.widthPct,- heightPct: newPlaceable.position.heightPct,+ xPct: updatedPlaceable.position.xPct,+ yPct: updatedPlaceable.position.yPct,+ widthPct: updatedPlaceable.position.widthPct,+ heightPct: updatedPlaceable.position.heightPct,});}}const index = internalIdToIndex(modificationData.placeables, uuid);- return modifyPlaceable(index, newPlaceable);+ return modifyPlaceable(index, updatedPlaceable);});}diff --git a/apps/web/src/features/block-pdf/store/tableOfContents.ts b/apps/web/src/features/block-pdf/store/tableOfContents.tsdeleted file mode 100644index 8eecb3698f..0000000000--- a/apps/web/src/features/block-pdf/store/tableOfContents.ts+++ /dev/null@@ -1,1336 +0,0 @@-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';-import type { ICoParse } from '../type/coParse';-import * as ArrayUtils from '../util/arrayUtils';-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';-export type TPageToSectionMap = Partial<{ [yPos: number]: Section }>[];-export interface ITableOfContentsContext {- // original copies of each TOC mode; allows for quickly swapping between the two- original: {- aiToc: TocItem[] | null;- pdfBookmarks: TocItem[] | null;- };- currentMode: 'ai-toc' | 'bookmarks';- width: number;-- sectionToRenameID: number | null;- renameFormValue: string;- sectionToDeleteID: number | null;-- unsavedBookmarks: boolean;- coparse: ICoParse | null;-- // this is the current table of contents that is displayed, will be swapped out- // with either object in `original` when swapping between bookmarks and AI TOC- items: TocItem[];- openItems: Partial<Record<number, boolean>>;- isLoaded: boolean;- pageToSectionMap: TPageToSectionMap;- idToSectionMap: Partial<{ [sectionId: number]: Section }>;- idToPathMap: Partial<Record<number, number[]>>;- idToNearestTitleMap: Partial<{ [sectionId: number]: string | null }>;- // use this instead of `idToSectionMap` when `currentMode` is `bookmarks`,- // used for clicking on section references within the document- aiTocIdToSectionMap: Partial<{ [sectionId: number]: Section }>;-}-/* -------------------------------------------------------------------------- *- * Types- * -------------------------------------------------------------------------- */--type LoadAiTocAction = {- type: 'LOAD_AI_TOC';- coparse: ICoParse;-};--type LoadPdfBookmarksAction = {- type: 'LOAD_PDF_BOOKMARKS';- bookmarks: TocItem[];-};--type SwitchTypeAction = {- type: 'SWITCH_CURRENT_MODE';-};--type SetTableOfContentsWidth = {- type: 'SET_TABLE_OF_CONTENTS_WIDTH';- width: number;-};--type ToggleBookmarkAction = {- type: 'TOGGLE_BOOKMARK';- secID: number;-};--type AddBookmarkAction = {- type: 'ADD_BOOKMARK';- yPos: number;- pageNum: number;- initialEmpty?: boolean; // for placeable bookmarks, start out without title and immediately prompt user to input a title- titleForPlaceable?: string; // for moving placeable bookmarks (delete then add a new one), create a bookmark with a passed-in title, not based on window selection- uuid?: string;-};--type DeleteBookmarkAction = {- type: 'DELETE_BOOKMARK';- secID: number;-};--type RenameBookmarkAction = {- type: 'RENAME_BOOKMARK';- secID: number;- value: string;-};--type HideRenameBookmarkAction = {- type: 'HIDE_RENAME_BOOKMARK';-};--type LeftIndentSectionAction = {- type: 'LEFT_INDENT_SECTION';- secID: number;-};--type RightIndentSectionAction = {- type: 'RIGHT_INDENT_SECTION';- secID: number;-};--type ResetOpenItemsAction = {- type: 'RESET_OPEN_ITEMS';-};--/**- * Union type for all actions- */--type ITableOfContentsAction =- | RenameBookmarkAction- | HideRenameBookmarkAction- | DeleteBookmarkAction- | ToggleBookmarkAction- | LoadAiTocAction- | LoadPdfBookmarksAction- | SwitchTypeAction- | LeftIndentSectionAction- | RightIndentSectionAction- | AddBookmarkAction- | SetTableOfContentsWidth- | ResetOpenItemsAction;--/* -------------------------------------------------------------------------- *- * Helper functions- * -------------------------------------------------------------------------- */--class Builder {- // Store pointer to the draft so any calls to functions update mutable state- private draft: ITableOfContentsContext;-- public constructor(draft: ITableOfContentsContext) {- this.draft = draft;- }-- public getSection(id: number): Section | null {- const section = this.draft.idToSectionMap[id];- return section?.clone() ?? null;- }-- public getTocItemBySectionID(id: number) {- const path = this.draft.idToPathMap[id];- if (!path) {- console.error('Section not found');- return;- }- return TocUtils.getTocItemFromPath({ items: this.draft.items, path });- }-- public deleteSection(secID: number): void {- const path = this.draft.idToPathMap[secID];-- if (!path) {- console.error('Section not found');- return;- }-- if (path.length > 1) {- this.removeSectionFromParent({- path,- secID,- });- } else {- // If there are no ancestors, then the section is at the root- this.draft.items = this.draft.items.filter(- (item) => item.section.id !== secID- );- }-- // Many paths could have changed as a result- this.computeIDToPathMap();- this.computePageToSectionMap();- this.computeIDToSectionMap();- this.computeIDToNearestTitleMap();-- if (!this.draft.coparse) {- throw new Error(- 'Coparse datastructure is not defined in table of contents context'- );- }-- // TODO: Delete the section and propagate throughout the application (green- // link in document AND definitions, search results, tab location, etc.)- // this.idToSection.delete(id)- Helpers.updateCoParseSectionXML({- id: secID,- type: 'DELETE',- coparse: this.draft.coparse,- });- }-- public removeSectionFromParent({- path,- secID,- }: {- path: number[];- secID: number;- }) {- // If we are removing the node from the root- if (path.length === 1) {- this.draft.items = this.draft.items.filter(- (item) => item.section.id !== secID- );- return;- }-- const parent = TocUtils.getTocItemParentFromPath({- items: this.draft.items,- path,- });-- // Remove section from its former parent- parent.children = parent.children.filter(- (child) => child.section.id !== secID- );- }-- /**- * Rename section with ID `id` to have name (title) `name`- *- */- public renameSection(id: number, name: string): this {- const section = this.getSection(id);- if (!section) {- console.error('Section not found');- return this;- }-- section.bookmarkTitle = name;- this.draft.idToSectionMap[id] = section;-- const tocItem = this.getTocItemBySectionID(id);- if (!tocItem) {- throw Error(`Failed to find TOC item for section id "${id}"`);- }-- if (!this.draft.coparse) {- throw Error(`No coparse data structure in TOC context`);- }-- tocItem.section = section;- Helpers.updateCoParseSectionXML({- id,- type: 'RENAME',- bookmarkTitle: name,- coparse: this.draft.coparse,- });-- this.computeIDToNearestTitleMap();- this.computePageToSectionMap();- this.computeIDToSectionMap();- this.computeIDToPathMap();-- return this;- }-- /**- * Add reference to next and prev section for each section- */- addLinksBetweenSections(): this {- let prevItem: TocItem | null = null;-- function handle(items: TocItem[]) {- items.forEach((item) => {- const { section } = item;- if (prevItem) {- const prevSection = prevItem.section;- prevSection.nextSection = section;- section.prevSection = section;- }- prevItem = item;- if (item.children.length) {- handle(item.children);- }- });- }-- handle(this.draft.items);-- return this;- }-- /**- * Creates mapping from section ID's to Section objects- *- * Stores it to the draft- */- public computeIDToSectionMap(settingOriginalAiToc?: boolean): this {- const mapping = Helpers.computeIDToSectionMapRecursive(- {},- this.draft.items- );- this.draft.idToSectionMap = mapping;- if (settingOriginalAiToc) {- const aiTocMapping = Helpers.computeIDToSectionMapRecursive(- {},- this.draft.original.aiToc || []- );- this.draft.aiTocIdToSectionMap = aiTocMapping;- }- return this;- }-- /**- * Create mapping from section IDs to paths to reach the section- *- * A path is the indices one needs to traverse in the tree to reach a node- *- * For example, if we have the tree:- *- * ```- * > A- * > B- * > C- * > D- * > E- * ```- *- * The path to section D is `[1, 0, 0]` to go from B -> C -> D- */- public computeIDToPathMap(): this {- this.draft.idToPathMap = Helpers.computeIDToPathMapRecursive(- {},- this.draft.items,- []- );- return this;- }-- public computeIDToNearestTitleMap(): this {- this.draft.idToNearestTitleMap =- Helpers.computeIDToNearestTitleMapRecursive({}, this.draft.items, null);- return this;- }-- // If we have one top level section, expand that by default- public setDefaultOpenState(): this {- if (this.draft.items.length === 1) {- const open: Record<number, boolean> = {};- open[this.draft.items[0].section.id] = true;- this.draft.openItems = open;- }- return this;- }-- /**- * Page number -> section ID -> section object- *- * TODO could add segment from prev page at yPos 0 for the next page as an- * optimizations- */- computePageToSectionMap(): this {- this.draft.pageToSectionMap = Helpers.getPageToSectionMapRecursive(- this.draft.items,- []- );- return this;- }-}--class Helpers {- /**- * Parse out node ID (a number) from an Element- *- * Returns null if fails to parse a number- */- static getNodeID(node: Element): number | null {- const nodeIDRaw = node.getAttribute('id');- if (typeof nodeIDRaw === 'number') {- return nodeIDRaw;- }- if (nodeIDRaw == null) {- return null;- }- const nodeID = parseInt(nodeIDRaw, 10);- if (isNaN(nodeID)) {- return null;- }-- return nodeID;- }-- /**- * TODO this is inefficient- */- static findNodeByID(secID: number, node: Element): Element | null {- if (this.getNodeID(node) === secID) {- return node;- }-- // Cast to an array so we can use array functions like `filter`- const children = Array.from(node.children).filter(- (child) => child.tagName === 'section'- );-- for (const childNode of children) {- // Recursive call- const match = Helpers.findNodeByID(secID, childNode);-- if (match) {- return match;- }- }-- return null;- }-- /**- * Convert section to node element- *- * Example HTML/XML:- * <section- * title='Permitted Encumbrances '- * literal='1.04'- * page='15'- * y='70.994865'- * id='14'- * qualified='1.04'- * show='true'- * type='SECTION'- * ></section>- */- static sectionToNodeElement(section: Section): HTMLElement {- const sectionNode = document.createElement('section');- sectionNode.setAttribute('title', section.title);- sectionNode.setAttribute('literal', section.literal ?? '');- sectionNode.setAttribute('page', section.page + '');- sectionNode.setAttribute('y', section.y + '');- sectionNode.setAttribute('id', section.id + '');- sectionNode.setAttribute('qualified', section.qualified);- sectionNode.setAttribute('show', section.showBookmark + '');- sectionNode.setAttribute('type', section.type ?? '');-- return sectionNode;- }-- static updateCoParseSectionXML(- props: { coparse: ICoParse } & (- | {- type: 'RENAME';- id: number;- bookmarkTitle: string;- }- | {- type: 'DELETE';- id: number;- }- | {- type: 'RIGHT_INDENT';- id: number;- parentID: number;- }- | {- type: 'LEFT_INDENT';- id: number;- parentID: number | null;- newChildrenIDs: number[];- }- | {- type: 'INSERT';- parentSectionID: number | null;- insertAtIndex: number | null;- section: Section;- }- )- ): ICoParse {- const coparse = Object.assign({}, props.coparse);- const sectionXML = coparse.toc ?? '';- const htmlDom = XMLUtils.parse(sectionXML);- const { firstChild } = htmlDom;- if (!firstChild) {- console.error('Missing firstChild in HTML DOM for Table of Contents');- return coparse;- }- const elt = firstChild as Element;-- if (props.type === 'INSERT') {- const { section, parentSectionID, insertAtIndex } = props;-- const sectionNode = this.sectionToNodeElement(section);- const parentNode = parentSectionID- ? Helpers.findNodeByID(parentSectionID, elt)- : elt;-- if (!parentNode) {- console.error('Failed to find parent node for new bookmark');- return coparse;- }-- // Second parameter here is the `referenceNode` (which node to insert- // before). If this is null, this inserts as the last child.- // https://developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore#syntax- const refChild: Element | null =- (insertAtIndex != null && parentNode.children[insertAtIndex]) || null;- parentNode?.insertBefore(sectionNode, refChild);- } else {- const { id } = props;- const targetNode = Helpers.findNodeByID(id, elt);- if (!targetNode) {- console.error('Failed to find target node');- return coparse;- }-- if (props.type === 'RIGHT_INDENT') {- /**- * This is a simple case compared to left indent, since there is no need- * for surgery on the children. We just need to find the target node and- * move it to be a child of its new parent (the ToC item immediately- * before it in the PDF)- */- const parentNode = Helpers.findNodeByID(props.parentID, elt);- if (!parentNode) {- console.error('Failed to find parent node');- return coparse;- }-- // Move target node to be a child of the new parent- parentNode.appendChild(targetNode);- } else if (props.type === 'LEFT_INDENT') {- /**- * If no parentID is supplied, that means we are moving the node to be a- * root ToC item. It's parent is thus elt itself.- *- * 1. Move the target node to be a child of the parent- *- * 2. Update list of children to have the target node as their new parent- * these are the children which used to be siblings of the target node,- * but now are children since the target node has shifted left.- *- * For example, say we want to left indent C:- *- * ```- * | Before: | After: |- * |---------|---------|- * | > A | > A |- * | > B | > B |- * | > C | > C |- * | > D | > D |- * | > E | > E |- * ```- *- * D and E have moved from being children of A to being children of C.- */- const { parentID, newChildrenIDs } = props;- const parentNode = parentID ? Helpers.findNodeByID(parentID, elt) : elt;-- if (!parentNode) {- console.error('Failed to find parent node');- return coparse;- }-- parentNode.appendChild(targetNode);-- newChildrenIDs.forEach((childID) => {- const childNode = Helpers.findNodeByID(childID, parentNode);-- if (!childNode) {- console.error('Failed to find child node');- return;- }-- targetNode.appendChild(childNode);- });- } else if (props.type === 'DELETE') {- // NOTE we must set value to a string (even though it's really a boolean)- targetNode.setAttribute('show', 'false');- } else if (props.type === 'RENAME') {- targetNode.setAttribute('bookmark', props.bookmarkTitle);- }- }-- coparse.toc = new XMLSerializer().serializeToString(htmlDom);- return coparse;- }-- static computeIDToNearestTitleMapRecursive(- mapping: Partial<Record<number, string>>,- items: TocItem[],- nearestParentTitle: string | null- ): Partial<Record<number, string>> {- items.forEach((item) => {- const { id, bookmarkTitle } = item.section;-- // Use `||` insetad of `??` so the empty string counts as no title- // Use bookmarkTitle here because that's the value that gets edited when renaming- const nearestTitle = bookmarkTitle || nearestParentTitle || null;- if (nearestTitle) {- mapping[id] = nearestTitle;- }- return Helpers.computeIDToNearestTitleMapRecursive(- mapping,- item.children,- nearestTitle- );- });-- return mapping;- }-- static computeIDToSectionMapRecursive(- mapping: Partial<Record<number, Section>>,- items: TocItem[]- ): Partial<Record<number, Section>> {- items.forEach((item) => {- const section = item.section;- mapping[section.id] = section;- const children = item.children;-- if (children.length) {- Helpers.computeIDToSectionMapRecursive(mapping, children);- }- });-- return mapping;- }-- static computeIDToPathMapRecursive(- mapping: Partial<Record<number, number[]>>,- items: TocItem[],- path: number[]- ): Partial<Record<number, number[]>> {- items.forEach((item, idx) => {- const newPath = [...path, idx];- const id = item.section.id;- mapping[id] = newPath;- const children = item.children;-- Helpers.computeIDToPathMapRecursive(mapping, children, newPath);- });-- return mapping;- }-- public static parseItem(- node: Element,- bookmark?: IBookmark,- sections?: Element[]- ): TocItem {- const id = node.getAttribute('id') || '';- const title = node.getAttribute('title') || '';- const literal = node.getAttribute('literal');- const page = parseInt(node.getAttribute('page') || '');- const y = parseFloat(node.getAttribute('y') || '');- const qualified = node.getAttribute('qualified') || '';- const numRefs = node.getElementsByTagName('reference').length;- const type = Section.parseSegmentType(node.getAttribute('type'));- const fullTitle = Section.getFullTitle(node);-- // If sections is defined and bookmark is not, then bookmarks exist and the- // selected bookmark was manually removed- const showBookmark =- bookmark === undefined && sections !== undefined- ? false- : // Either it is not set, in which case we default to showing, or the value is- // literally set to "true"- !node.getAttribute('show') || node.getAttribute('show') === 'true';- const bookmarkTitle = bookmark- ? bookmark.title- : node.getAttribute('bookmark');-- const idNum = parseInt(id, 10);-- if (isNaN(idNum)) {- console.error('Invalid section ID');- }-- const section = new Section({- id: idNum,- title,- literal,- page,- y,- qualified,- type,- fullTitle,- numRefs,- showBookmark,- bookmarkTitle,- });-- let children: TocItem[] = [];-- if (bookmark === undefined) {- const childElems = [...(node?.children ?? [])];- children = childElems- .filter((child) => child.tagName === 'section')- .map((node) => Helpers.parseItem(node));- } else {- bookmark.children.forEach((b) => {- const existingSection = sections?.find(- (node) => parseInt(node.id) === b.id- );- if (existingSection)- children.push(Helpers.parseItem(existingSection, b, sections));- });- }-- return new TocItem(section, children);- }-- static getPageToSectionMapRecursive(- items: TocItem[],- pageToSec: TPageToSectionMap- ): TPageToSectionMap {- for (let item of items) {- const section = item.section;- const page = section.page;- const pageMap = pageToSec[page] || {};- const y = section.y;-- if (typeof y === 'number') {- pageMap[y] = section;- } else {- console.error('Section has invalid y value');- }-- pageToSec[page] = pageMap;- Helpers.getPageToSectionMapRecursive(item.children, pageToSec);- }-- return pageToSec;- }-- static recursiveFindUuid(uuid: string, tocItem: TocItem) {- if (tocItem.section.uuid === uuid) {- return [tocItem.section.id];- }-- let ancestorIds: number[] = [];- tocItem.children.forEach((childItem) => {- const foundChildrenIds = this.recursiveFindUuid(uuid, childItem);- if (foundChildrenIds.length > 0) {- ancestorIds = [- ...ancestorIds,- ...foundChildrenIds,- childItem.section.id,- ];- }- });-- return ancestorIds;- }-- /**- * Find a given section based on UUID, then return all of its ancestors (including itself)- */- static findAllAncestors(uuid: string, tocItems: TocItem[]) {- let ancestorIds: number[] = [];-- tocItems.forEach((item) => {- const foundChildrenIds = this.recursiveFindUuid(uuid, item);- if (foundChildrenIds.length > 0) {- ancestorIds = [...ancestorIds, ...foundChildrenIds, item.section.id];- }- });-- return ancestorIds;- }-- static flattenAllSections(tocItem: TocItem): Section[] {- let sections: Section[] = [tocItem.section];-- if (tocItem.children.length > 0) {- tocItem.children.forEach((childItem) => {- sections = [...sections, ...this.flattenAllSections(childItem)];- });- } else {- sections.push(tocItem.section);- }-- return sections;- }-- static sectionToNodeElementRecursive(tocItem: TocItem): string {- // HTMLElement -> string (in XML format)- const currentSectionXml = new XMLSerializer().serializeToString(- this.sectionToNodeElement(tocItem.section)- );- let xmlElements: string[] = [- // remove end tag so that all child elements can be nested- // within, then re-add end tag afterwards- currentSectionXml.split('</section>')[0],- ];-- tocItem.children.forEach((childItem) => {- const childElements = this.sectionToNodeElementRecursive(childItem);- xmlElements = [...xmlElements, ...childElements];- });-- return xmlElements.join('') + '</section>';- }-- static tocItemsToXml(tocItems: TocItem[]): string {- let xmlElements: string[] = [];- tocItems.forEach((tocItem) => {- xmlElements = [- ...xmlElements,- this.sectionToNodeElementRecursive(tocItem),- ];- });-- return `<xml>${xmlElements.join('')}</xml>`;- }-- static addItemToSectionChildren({- parentSectionId,- insertItem,- existingItem,- }: {- parentSectionId: number;- insertItem: TocItem;- existingItem: TocItem;- }) {- let children: TocItem[] = [];-- if (existingItem.section.id === parentSectionId) {- children =- existingItem.children.length === 0- ? [insertItem]- : [insertItem, ...existingItem.children];- } else {- existingItem.children.forEach((childItem) => {- children.push(- this.addItemToSectionChildren({- parentSectionId,- insertItem,- existingItem: childItem,- })- );- });- }-- existingItem.children = children;- return existingItem;- }-- static insertSectionIntoItems({- section,- parentSectionId,- items,- }: {- section: Section;- parentSectionId: number | null;- items: TocItem[];- }): TocItem[] {- let updatedItems: TocItem[] = [];- const tocItem = new TocItem(section, []);-- if (parentSectionId === null) {- updatedItems = [tocItem, ...items];- } else {- items.forEach((item) => {- const updatedItem = this.addItemToSectionChildren({- parentSectionId,- insertItem: tocItem,- existingItem: item,- });- updatedItems = [...updatedItems, updatedItem];- });- }-- return updatedItems;- }-- static recursiveCloneTocItem(tocItem: TocItem): TocItem {- return tocItem.clone(- tocItem.children.map((childItem) => this.recursiveCloneTocItem(childItem))- );- }-- static cloneTocTree(tree: TocItem[]): TocItem[] {- return tree.map((treeItem) => this.recursiveCloneTocItem(treeItem));- }-}--/* -------------------------------------------------------------------------- *- * Reducer- * -------------------------------------------------------------------------- */--const producer = (- draft: ITableOfContentsContext,- action: ITableOfContentsAction-) => {- switch (action.type) {- case 'LOAD_AI_TOC': {- const firstChild = XMLUtils.parse(action.coparse.toc || '').firstChild as- | Element- | undefined;- const children: TocItem[] = [...(firstChild?.children ?? [])]- .filter((child) => child.tagName === 'section')- .map((node) => Helpers.parseItem(node, undefined));-- // In case `window` was undefined when we created the default state- draft.width = getDefaultWidth();- draft.pageToSectionMap = [];- draft.original.aiToc = [...children];-- // include everything from action.coparse except for toc because PDF- // bookmarks on page load, so LOAD_PDF_BOOKMARKS sets the value for toc- const existingCoParseToc = draft.coparse?.toc;- draft.coparse = action.coparse;- draft.coparse.toc = existingCoParseToc;-- new Builder(draft)- .computePageToSectionMap()- .computeIDToSectionMap(true)- .computeIDToPathMap()- .addLinksBetweenSections()- .computeIDToNearestTitleMap(); // TODO call this in more places-- draft.isLoaded = !!draft.original.aiToc && !!draft.original.pdfBookmarks;- break;- }- case 'LOAD_PDF_BOOKMARKS': {- draft.original.pdfBookmarks = action.bookmarks;- draft.items = Helpers.cloneTocTree(action.bookmarks);- draft.isLoaded = !!draft.original.aiToc && !!draft.original.pdfBookmarks;-- const coparse = Object.assign({}, draft.coparse);- coparse.toc = Helpers.tocItemsToXml(action.bookmarks);- draft.coparse = coparse;-- new Builder(draft)- .computePageToSectionMap()- .computeIDToSectionMap()- .computeIDToPathMap()- .addLinksBetweenSections()- .computeIDToNearestTitleMap()- .setDefaultOpenState();-- break;- }- case 'SWITCH_CURRENT_MODE': {- const { currentMode, original } = draft;- const originalBookmarks = original.pdfBookmarks;- const originalToc = original.aiToc;-- if (originalBookmarks === null || originalToc === null) {- break;- }-- if (currentMode === 'ai-toc') {- draft.currentMode = 'bookmarks';- draft.items = Helpers.cloneTocTree(originalBookmarks);- const coparse = Object.assign({}, draft.coparse);- coparse.toc = Helpers.tocItemsToXml(originalBookmarks);- draft.coparse = coparse;- draft.openItems =- originalBookmarks.length === 1- ? { [originalBookmarks[0].section.id]: true }- : {};- } else if (currentMode === 'bookmarks') {- draft.currentMode = 'ai-toc';- draft.items = Helpers.cloneTocTree(originalToc);- const coparse = Object.assign({}, draft.coparse);- coparse.toc = Helpers.tocItemsToXml(originalToc);- draft.coparse = coparse;- draft.openItems =- originalToc.length === 1 ? { [originalToc[0].section.id]: true } : {};- }-- new Builder(draft)- .computePageToSectionMap()- .computeIDToSectionMap()- .computeIDToPathMap()- .addLinksBetweenSections()- .computeIDToNearestTitleMap();-- break;- }- case 'SET_TABLE_OF_CONTENTS_WIDTH': {- if (action.width <= 0) {- console.error('Table of contents width must be positive');- return;- }-- if (action.width > window.innerWidth) {- console.error('Table of contents cannot be wider than the window');- return;- }-- draft.width = action.width;- break;- }- case 'TOGGLE_BOOKMARK': {- const { secID } = action;- draft.openItems[secID] = !draft.openItems[secID];- break;- }- case 'DELETE_BOOKMARK': {- const { secID } = action;-- if (secID === null) {- console.error('Invalid state to delete bookmark');- return;- }-- new Builder(draft).deleteSection(secID);-- draft.unsavedBookmarks = true;-- // draft.items = newItems;- draft.sectionToDeleteID = null;- break;- }- case 'LEFT_INDENT_SECTION': {- const { secID } = action;- const path = draft.idToPathMap[secID];- if (!path) {- console.error('Section not found');- return;- }-- if (!TocUtils.canLeftIndent({ path })) {- console.error('Cannot left indent the section provided');- return;- }-- const parent = TocUtils.getTocItemParentFromPath({- items: draft.items,- path,- });-- const siblings = parent.children;- const idx = path[path.length - 1];- const item = siblings[idx];-- if (!item) {- console.error('Failed to find item ');- return;- }-- // Update parent children- parent.children = siblings.slice(0, idx);- const newChildren = siblings.slice(idx + 1);-- // If not this, then there are no changes to the node's children- if (newChildren.length) {- item.children = [...item.children, ...newChildren];- }-- const newIndex = path[path.length - 2] + 1;-- let newParent: TocItem | null = null;-- if (path.length < 3) {- // Item will now be at root of tree- // Inserted right after its parent- draft.items = ArrayUtils.withItemAtIndex(draft.items, item, newIndex);- } else {- newParent = TocUtils.getTocItemFromPath({- items: draft.items,- path: path.slice(0, path.length - 2),- });- newParent.children = ArrayUtils.withItemAtIndex(- newParent.children,- item,- newIndex- );- }-- // Expand the relocated item if it is not already expanded- draft.openItems[secID] = true;-- new Builder(draft).computeIDToPathMap().computeIDToNearestTitleMap();-- if (!draft.coparse) {- throw new Error(- 'CoParse data structure is not defined when trying to update section html'- );- }-- Helpers.updateCoParseSectionXML({- type: 'LEFT_INDENT',- id: secID,- // TODO or could give parent path for more efficient access- parentID: newParent?.section.id ?? null,- newChildrenIDs: newChildren.map((child) => child.section.id),- coparse: draft.coparse,- });- draft.unsavedBookmarks = true;-- break;- }- case 'RIGHT_INDENT_SECTION': {- const { secID } = action;- const path = draft.idToPathMap[secID];-- if (!path) {- console.error('Section not found');- return;- }- if (!TocUtils.canRightIndent({ path })) {- console.error('Cannot right indent the section provided');- return;- }-- // Append the child to the new parent- // It comes last in the list of children (top to bottom order maintained)- const item = TocUtils.getTocItemFromPath({ items: draft.items, path });-- new Builder(draft).removeSectionFromParent({- path,- secID,- });-- // New parent is the sibling directly above it- const newParentPath = (() => {- const newPath = path.slice(0, path.length - 1);- newPath.push(path[path.length - 1] - 1);- return newPath;- })();- const newParent = TocUtils.getTocItemFromPath({- items: draft.items,- path: newParentPath,- });- newParent.children.push(item);-- // Expand the new parent to show where the node went- draft.openItems[newParent.section.id] = true;-- if (!draft.coparse) {- throw new Error('CoParse data structure is not defined');- }-- Helpers.updateCoParseSectionXML({- type: 'RIGHT_INDENT',- id: secID,- // TODO or could give parent path for more efficient access- parentID: newParent.section.id,- coparse: draft.coparse,- });-- draft.unsavedBookmarks = true;-- new Builder(draft).computeIDToPathMap().computeIDToNearestTitleMap();-- break;- }- case 'RENAME_BOOKMARK': {- const { secID, value } = action;-- if (!value) {- console.error('Missing value');- return;- }-- new Builder(draft).renameSection(secID, value);-- draft.unsavedBookmarks = true;-- draft.renameFormValue = '';- draft.sectionToRenameID = null;- break;- }- case 'ADD_BOOKMARK': {- const { yPos, pageNum, initialEmpty, titleForPlaceable, uuid } = action;- const selection = window.getSelection();- const text =- titleForPlaceable || (selection ? selection.toString().trim() : null);-- if (!text && !initialEmpty) {- console.error('You must select text to add a bookmark');- return;- }-- if (pageNum < 0) {- console.error('Invalid page for bookmark');- return;- }-- if (yPos < 0) {- console.error('Invalid Y position for bookmark');- return;- }-- const title = text || '';-- const section = new Section({- id: Math.floor(Math.random() * 10 ** 10), // TODO replace this with uuid when section IDs are no longer numbers- title,- page: pageNum,- y: yPos,- showBookmark: true,- fullTitle: title,- literal: null,- qualified: '',- numRefs: 0,- bookmarkTitle: title,- type: 'SECTION',- uuid, // pass in UUID if recreating an existing bookmark, otherwise section constructor will generate a UUID- });-- // flattened list of all bookmark sections in document- let allSections: Section[] = [];- draft.items.forEach((sectionItem) => {- allSections = [- ...allSections,- ...Helpers.flattenAllSections(sectionItem),- ];- });-- // find the closest section before the new bookmark's position- let nearestSection: Section | null = null;- allSections.forEach((sectionItem: Section) => {- if (- sectionItem.page < section.page ||- (sectionItem.page === section.page && sectionItem.y <= section.y)- ) {- nearestSection = sectionItem;- }- });- nearestSection = nearestSection as Section | null;-- if (!draft.coparse) {- throw new Error('CoParse data structure is not defined');- }-- // add new section to items- draft.items = Helpers.insertSectionIntoItems({- section,- parentSectionId: nearestSection?.id ?? null,- items: draft.items,- });-- // add new section to XML- draft.coparse = Helpers.updateCoParseSectionXML({- section,- type: 'INSERT',- parentSectionID: nearestSection?.id ?? null,- insertAtIndex: 0,- coparse: draft.coparse,- });-- // open all ancestors of new section in outline- const ancestors = Helpers.findAllAncestors(section.uuid, draft.items);- if (ancestors.length > 0) {- [...ancestors, ...(nearestSection ? [nearestSection.id] : [])].forEach(- (sectionId) => {- draft.openItems[sectionId] = true;- }- );- } else {- console.error(- 'Error: Newly created outline section could not be found in tree'- );- }-- new Builder(draft)- .computeIDToNearestTitleMap()- .computePageToSectionMap()- .computeIDToSectionMap()- .computeIDToPathMap();-- break;- }- case 'RESET_OPEN_ITEMS': {- draft.openItems = {};- break;- }- default:- throw new InvalidActionError(action);- }-};--function recursiveFindByUuid(uuid: string, tocItem: TocItem): Section | null {- if (tocItem.section.uuid === uuid || tocItem.uuid === uuid) {- return tocItem.section;- }-- let foundSection: Section | null = null;- tocItem.children.forEach((childItem) => {- const childrenResults = recursiveFindByUuid(uuid, childItem);- if (childrenResults) {- foundSection = childrenResults;- }- });-- return foundSection;-}--export function findSectionByUuid(- uuid: string,- items: TocItem[]-): Section | null {- let foundSection: Section | null = null;- items.forEach((childItem) => {- const childrenResults = recursiveFindByUuid(uuid, childItem);- if (childrenResults) {- foundSection = childrenResults;- }- });-- return foundSection;-}--export function useTableOfContentsValue() {- const [tocStore] = usePdfDocument().state.stores.tableOfContents;- return () => tocStore;-}--export function useTableOfContentsUpdate() {- const [, setTocStore] = usePdfDocument().state.stores.tableOfContents;- return (action: ITableOfContentsAction) => {- setTocStore(- produce<ITableOfContentsContext>((state) => producer(state, action))- );- };-}--export function useGetIdToSectionMap() {- const [tocStore] = usePdfDocument().state.stores.tableOfContents;- return () =>- tocStore.currentMode === 'bookmarks'- ? tocStore.aiTocIdToSectionMap- : tocStore.idToSectionMap;-}--export function useGetPageToSectionMap() {- const [tocStore] = usePdfDocument().state.stores.tableOfContents;- return () => tocStore.pageToSectionMap;-}diff --git a/apps/web/src/features/block-pdf/type/comments.ts b/apps/web/src/features/block-pdf/type/comments.tsindex 72ad2c6e98..7fbb6934ee 100644--- a/apps/web/src/features/block-pdf/type/comments.ts+++ b/apps/web/src/features/block-pdf/type/comments.ts@@ -1,4 +1,9 @@-import type { Reply, Root } from '@core/comments/commentType';+import type {+ CommentId,+ Reply,+ Root,+ ThreadId,+} from '@core/comments/commentType';import type { Comment } from '@service-storage/generated/schemas/comment';export type ThreadPayload = {@@ -12,6 +17,24 @@ export type ThreadPayload = {export type ViewerCommentType = 'free' | 'highlight';+const PDF_DRAFT_THREAD_PREFIX = 'pdf-draft:';++export type PdfDraftThreadId =+ `${typeof PDF_DRAFT_THREAD_PREFIX}${ViewerCommentType}:${string}`;++export function createPdfDraftThreadId(+ type: ViewerCommentType,+ anchorId: string+): PdfDraftThreadId {+ return `${PDF_DRAFT_THREAD_PREFIX}${type}:${anchorId}`;+}++export function isPdfDraftThreadId(+ id: CommentId | ThreadId | null | undefined+): id is PdfDraftThreadId {+ return typeof id === 'string' && id.startsWith(PDF_DRAFT_THREAD_PREFIX);+}+export type Overflow = null | 'top' | 'bottom';type Layout = { calculatedYPos: number; overflow: Overflow; height: number };diff --git a/apps/web/src/features/block-pdf/util/TocUtils.ts b/apps/web/src/features/block-pdf/util/TocUtils.tsindex 12c583e165..e610056e9d 100644--- a/apps/web/src/features/block-pdf/util/TocUtils.ts+++ b/apps/web/src/features/block-pdf/util/TocUtils.ts@@ -1,248 +1,45 @@-import Section, { type StringifyableSection } from '../model/Section';-import type TocItem from '../model/TocItem';-import { cleanQuery } from './StringUtils';--// import type { TPageToSectionMap } from '../context/DefaultTableOfContentsState';-type TPageToSectionMap = Partial<{ [yPos: number]: Section }>[];--/**- * Types- */--interface IDProps {- id: number;-}--interface PathProps {- path: number[];-}--interface ItemsProps {- items: TocItem[];-}--/**- * Util functions- */+import type Section from '../model/Section';class TocUtils {public static getSection({id,idToSectionMap,- }: IDProps & {+ }: {+ id: number;idToSectionMap: Partial<Record<number, Section>>;}): Section {const section = idToSectionMap[id];if (!section) {- // TODO determine if this error is necessary- // what is fallback Section value?throw new Error('Failed to find section with ID ' + id);}return section.clone();}- /**- * Get the nearest Section to the provided page/yPost location- */public static getNearestSection({page,yPos,- pageToSectionMap,+ idToSectionMap,}: {page: number;yPos: number;- pageToSectionMap: TPageToSectionMap;+ idToSectionMap: Partial<Record<number, Section>>;}): Section | null {- if (!pageToSectionMap) {- console.error('Missing pageToSectionMap');+ let nearestSection: Section | null = null;++ for (const section of Object.values(idToSectionMap)) {+ if (!section) continue;+ const appearsBefore =+ section.page < page || (section.page === page && section.y < yPos);+ if (!appearsBefore) continue;++ const appearsAfterNearest =+ nearestSection == null ||+ section.page > nearestSection.page ||+ (section.page === nearestSection.page && section.y > nearestSection.y);+ if (appearsAfterNearest) nearestSection = section;}- const mappingForThisPage = pageToSectionMap?.[page];- if (mappingForThisPage) {- // If there are sections on this page- let last: Section | null = null;- for (const section of Object.values(mappingForThisPage)) {- // TODO this code relies on this being sorted by key- // This is not the best assumption...- if (section?.shouldDisplay({ page, yPos })) {- last = section;- }- }-- if (last) {- return last;- }- }-- let otherPage = page - 1;-- /**- * TODO: efficiency: could create a "CDF" i.e. store best section at "0" so- * we don't have to examine previous pages- */- while (otherPage > 0) {- const mapping = pageToSectionMap[otherPage];- const numSectionsOnOtherPage: number = mapping- ? Object.keys(mapping).length- : 0;- if (numSectionsOnOtherPage) {- // TODO this assumes order of Object.values, which ~ assumes order of IDs- const sectionToReturn =- Object.values(mapping)[numSectionsOnOtherPage - 1]!;-- return sectionToReturn;- }- otherPage = otherPage - 1;- }-- return null;- }-- /**- * 1. Filter sections that do not contain the query in the full descriptor- * NOTE: Query must be found at the start of a token in the descriptor- * The only prefixes that are allowed are 'in', 'un', and 're'- *- * 2. Filter out sections with the exact same full title. Keep the first one- * that appears in the document.- * - the effect is the removal of subsections with the same full title- * - the first one that appears in the document will be the parent section- *- * 3. Sort by the following criteria:- * 1) The search query is an exact match on one of the tokens- * 2) The number of times the section is referenced in the document- */- public static searchSections(- query: string,- sections: StringifyableSection[]- ): number[] {- const escapedQuery = cleanQuery(query);- let includeRE = new RegExp(`(^| | in| un| re| co|-)${escapedQuery}`);- let sortRE = new RegExp(`(^| )${escapedQuery}( |$|:)`);- let arr = sections.filter((section) => {- return includeRE.test(section.lowerCaseFullDescriptor);- });-- const isExactMatchSomewhere: Record<number, boolean> = {};- const sectionsWithTitle: { [title: string]: StringifyableSection } = {};- arr.forEach((section) => {- let currentSection = sectionsWithTitle[section.fullTitle];- if (currentSection) {- if (Section.appearsBefore(section, currentSection)) {- sectionsWithTitle[section.fullTitle] = section;- }- } else {- sectionsWithTitle[section.fullTitle] = section;- }- isExactMatchSomewhere[section.id] = sortRE.test(- section.lowerCaseFullDescriptor- );- });-- return Object.values(sectionsWithTitle)- .sort((s1, s2) => {- const s1IsExactMatchSomewhere = isExactMatchSomewhere[s1.id];- const s2IsExactMatchSomewhere = isExactMatchSomewhere[s2.id];- if (s1IsExactMatchSomewhere === s2IsExactMatchSomewhere) {- return s2.numRefs - s1.numRefs;- } else {- return (- Number(s2IsExactMatchSomewhere) - Number(s1IsExactMatchSomewhere)- );- }- })- .map((s) => s.id);- }-- private static getPathToTocItemRecursive({- items,- id,- path,- }: ItemsProps & IDProps & PathProps): number[] | null {- for (let i = 0; i < items.length; i++) {- const tocItem = items[i];- if (tocItem.section.id === id) {- // This is a match- return [...path, i];- }-- // Recursive call on children- const children = tocItem.children;- const childTocItem = this.getPathToTocItemRecursive({- items: children,- id,- path: [...path, i],- });- if (childTocItem) {- // If we found the child, return early- return childTocItem;- }-- // Else, keep looking- }-- return null;- }-- /**- * TODO this is inefficient...can we cache this?- *- * Probably would want to cache upstream (where this is called)- */- public static getPathToTocItem(props: ItemsProps & IDProps): number[] | null {- return TocUtils.getPathToTocItemRecursive({- ...props,- path: [],- });- }-- public static getTocItemFromPath({- items,- path,- }: ItemsProps & PathProps): TocItem {- if (!path.length) console.error('Path must be at least of length 1');-- const item = items[path[0]];- if (!item) {- console.error('Invalid path');- }-- if (path.length === 1) {- return item;- }-- return this.getTocItemFromPath({- items: item.children,- path: path.slice(1),- });- }-- public static getTocItemParentFromPath({- items,- path,- }: ItemsProps & PathProps) {- // Parent path is child path without the last element- const parentPath = path.slice(0, path.length - 1);- return this.getTocItemFromPath({ path: parentPath, items });- }-- /**- * Returns if the ToC item at the specified path can be left indented- *- * You cannot left indent an item that is already at the root of the tree- */- public static canLeftIndent(props: PathProps): boolean {- return props.path.length > 1;- }-- /**- * Returns if the ToC item at the specified path can be right indented- *- * You cannot right indent an item that is the first of its siblings- */- public static canRightIndent({ path }: PathProps): boolean {- const idx = path[path.length - 1];- return idx !== 0;+ return nearestSection?.clone() ?? null;}}diff --git a/apps/web/src/features/block-pdf/util/buildModificationData.ts b/apps/web/src/features/block-pdf/util/buildModificationData.tsindex b090afb5da..d42899ff25 100644--- a/apps/web/src/features/block-pdf/util/buildModificationData.ts+++ b/apps/web/src/features/block-pdf/util/buildModificationData.ts@@ -1,7 +1,5 @@import { modificationDataReplacer } from '@coparse/document-processing-types';import type Term from '../model/Term';-import type TocItem from '../model/TocItem';-import type { IBookmark } from '../type/Bookmark';import {type IModificationData,type IModificationDataOnServer,@@ -12,18 +10,6 @@ import { hashString, hashStringSync } from './hash';export { modificationDataReplacer };-export function getBookmarks(items: TocItem[]): IBookmark[] {- return items.map(- ({ section, children }): IBookmark => ({- title: section.bookmarkTitle,- pageNum: section.page,- top: section.y,- children: getBookmarks(children),- id: section.id,- })- );-}-/*** Filter for excluding certain placeables from being saved as modification data* @returns false if the placeable should be excluded@@ -39,16 +25,14 @@ const savePlaceablesFilter = (p: IPlaceable) => {export function getSaveModificationData({pinnedTerms,- TOCItems,placeables,}: {placeables: IPlaceable[];- TOCItems: TocItem[];pinnedTerms: Term[];}): { modificationData: IModificationDataOnServer } {const pins = pinnedTerms.map((term) => term.name);const modificationData: IModificationData = {- bookmarks: getBookmarks(TOCItems),+ bookmarks: [],placeables: placeables.filter(savePlaceablesFilter),pinnedTermsNames: pins,};diff --git a/apps/web/src/features/block-pdf/util/definitionText.ts b/apps/web/src/features/block-pdf/util/definitionText.tsnew file mode 100644index 0000000000..d4509a23da--- /dev/null+++ b/apps/web/src/features/block-pdf/util/definitionText.ts@@ -0,0 +1,8 @@+export function decodeDefinitionText(element: Element): string {+ const lineBreaks = /<br\/>/g;+ const endBreak = /(?<=.)(<br\/>)$/g;+ if (!element.innerHTML) return '';+ return element.innerHTML+ .replaceAll(endBreak, '')+ .replaceAll(lineBreaks, '\r\n\n');+}diff --git a/apps/web/src/features/block-pdf/util/selectionUtils.ts b/apps/web/src/features/block-pdf/util/selectionUtils.tsindex 69772d4a6c..7ffcf05656 100644--- a/apps/web/src/features/block-pdf/util/selectionUtils.ts+++ b/apps/web/src/features/block-pdf/util/selectionUtils.ts@@ -63,19 +63,10 @@ function nodeToString(node: Node): string {}export function useResetSelection() {- const { signals, stores } = usePdfDocument().state;- const setActiveHighlight = signals.activeHighlight[1];- const setGeneralPopupLocation = signals.generalPopupLocation[1];- const setSelection = stores.selection[1];+ const pdf = usePdfDocument();return (selection?: Selection) => {selection?.removeAllRanges();- setGeneralPopupLocation(null);- setSelection({- highlightsUnderSelection: [],- selection: null,- selectionString: '',- });- setActiveHighlight(null);+ pdf.resetSelection();};}diff --git a/apps/web/src/features/drive-view/views/PdfDetail.tsx b/apps/web/src/features/drive-view/views/PdfDetail.tsxindex 31e347dbdd..62b48630bc 100644--- a/apps/web/src/features/drive-view/views/PdfDetail.tsx+++ b/apps/web/src/features/drive-view/views/PdfDetail.tsx@@ -12,7 +12,6 @@ import {type LocationSearchParams,URL_PARAMS,} from '@block-pdf/signal/location';-import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import {getPermissions,hasPermissions,@@ -34,12 +33,10 @@ export type PdfDetailContext = {function PdfDetailContent() {const pdf = usePdfDocument();- const [documentProxy] = pdf.state.signals.documentProxy;- const [showTabBar] = pdf.state.signals.showTabBar;return (<>- <Show when={documentProxy()}>+ <Show when={pdf.documentProxy()}><div class="flex min-h-11 shrink-0 items-center gap-2 border-edge-muted border-b px-2"><PdfToolbarControls /><div class="ml-auto">@@ -48,7 +45,7 @@ function PdfDetailContent() {</div></Show><div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">- <Show when={showTabBar()}>+ <Show when={pdf.tabs.isVisible()}><div class="flex min-h-11 items-center justify-between gap-2 px-2"><div class="customScrollbar w-0 grow overflow-x-auto overflow-y-hidden"><Tabs />@@ -68,7 +65,6 @@ export function PdfDetailDocument(children?: (context: PdfDetailContext) => JSX.Element;}) {- const panel = useSplitPanelOrThrow();const [searchParams] = useSearchParams();const permissions = () => getPermissions(props.data.userAccessLevel);@@ -91,7 +87,6 @@ export function PdfDetailDocument(documentProxy={props.data.documentProxy}viewLocation={props.data.viewLocation}modificationData={props.data.documentMetadata.modificationData}- hotkeyScope={panel.splitHotkeyScope}portalScope="split"permissions={{canComment: hasPermissions(permissions(), Permissions.CAN_COMMENT),diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex 234663ad66..5e1b64b250 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -469,7 +469,7 @@ body.tauri-ios {Bands:0- 99 in-page — viewer internals (0-19), app chrome (20-30),- floating widgets (90)+ cross-panel content (31), floating widgets (90)100-199 modal stack, drag previews, menus200-299 always on top — tooltips, toasts@@ -483,7 +483,6 @@ body.tauri-ios {local ordering. *//* ---- 0-99: in-page --------------------------------------------------- */- --z-index-main-view-layout: 0;--z-index-user-highlight: 1;--z-index-annotation-layer: 2;/* Split-view header title strip. Local to the header's own stacking@@ -513,6 +512,9 @@ body.tauri-ios {/* Split panel header/side-panel chrome: above the panel's content and therest of the in-page chrome, below floating widgets. */--z-index-split-panel-chrome: 30;+ /* PDF margin comments cross the document panel boundary and must remain+ interactive when they overlap side-panel chrome. */+ --z-index-pdf-comments: 31;/* App-level floating widgets (`z-float`: draggable call controls, incomingcalls). Above all other in-page content, below the modal stack. */diff --git a/apps/web/src/lib/core/util/threeColumnLayout.ts b/apps/web/src/lib/core/util/threeColumnLayout.tsdeleted file mode 100644index 5b69560ca0..0000000000--- a/apps/web/src/lib/core/util/threeColumnLayout.ts+++ /dev/null@@ -1,67 +0,0 @@-export interface ThreeColumnLayout {- isInitialized: boolean;- leftWidth: number;- rightWidth: number;- rightMargin: number;- centerWidth: number | undefined;- windowWidth: number | undefined;- marginWidth: number;-}--interface ThreeColumnConfig {- gutterPx: number;- minLeftColumnWidth: number;- minRightColumnWidth: number;- maxLeftHandWidth: number;- rightHandWidth: number;-}--const _resizeColumns = (- centerWidth: number | undefined,- windowWidth: number | undefined,- oldColumns: ThreeColumnLayout,- config: ThreeColumnConfig-): ThreeColumnLayout => {- const lastMiddleWidth = oldColumns.centerWidth;- const lastWindowWidth = oldColumns.windowWidth;-- if (- !centerWidth ||- !windowWidth ||- (lastMiddleWidth === centerWidth && lastWindowWidth === windowWidth)- ) {- return oldColumns;- }-- let rightMargin = config.gutterPx;- let leftWidth = config.maxLeftHandWidth - config.gutterPx * 3;- let rightWidth = config.rightHandWidth;- const totalWidth = windowWidth - config.gutterPx * 2;-- const intendedWidth =- centerWidth + leftWidth + rightWidth + config.gutterPx * 4;- const marginWidth = Math.round((totalWidth - centerWidth) / 2);- if (intendedWidth <= totalWidth) {- rightMargin = marginWidth - rightWidth;- } else {- leftWidth = Math.min(- marginWidth + config.gutterPx,- config.maxLeftHandWidth - config.gutterPx * 3- );- rightWidth = Math.min(config.rightHandWidth, marginWidth);- rightMargin = marginWidth - rightWidth + config.gutterPx;- }-- rightWidth = Math.max(rightWidth, config.minRightColumnWidth);- leftWidth = Math.max(leftWidth, config.minLeftColumnWidth);-- return {- isInitialized: true,- leftWidth,- rightWidth,- rightMargin,- centerWidth,- windowWidth,- marginWidth,- };-};