Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#119 Tempered TextAnnotatorPopup positioning #120

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 50 additions & 66 deletions packages/text-annotator-react/src/TextAnnotatorPopup.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
import { ReactNode, useEffect, useState } from 'react';
import { useSelection } from '@annotorious/react';
import type { TextAnnotation, TextSelector } from '@recogito/text-annotator';
import { getClosestRect, toClientRects } from './utils';
import { ReactNode, useCallback, useEffect, useState, PointerEvent } from 'react';
import { useAnnotator, useSelection } from '@annotorious/react';
import { type TextAnnotation, type TextAnnotator } from '@recogito/text-annotator';
import {
autoPlacement,
autoUpdate,
inline,
offset,
shift,
useFloating
useDismiss,
useFloating,
useInteractions,
useRole
} from '@floating-ui/react';

interface TextAnnotationPopupProps {
Expand All @@ -24,89 +25,72 @@ export interface TextAnnotatorPopupProps {
}

export const TextAnnotatorPopup = (props: TextAnnotationPopupProps) => {
const r = useAnnotator<TextAnnotator>();

const { selected, pointerEvent } = useSelection<TextAnnotation>();

const [mousePos, setMousePos] = useState<{ x: number, y: number } | undefined>();
const annotation = selected[0]?.annotation;

const [isOpen, setIsOpen] = useState(selected?.length > 0);
const [isOpen, setOpen] = useState(selected?.length > 0);

const { refs, floatingStyles, update } = useFloating({
const { refs, floatingStyles, context } = useFloating({
placement: 'top',
open: isOpen,
onOpenChange: setIsOpen,
onOpenChange: (open, _event, reason) => {
setOpen(open);
if (!open && reason === 'escape-key') {
r?.cancelSelected();
}
},
middleware: [
autoPlacement({ crossAxis: true, padding: 5 }),
inline(),
offset(5),
shift({ crossAxis: true, padding: 5 })
offset(10),
inline(),
shift({ mainAxis: false, crossAxis: true, padding: 10 })
],
whileElementsMounted: autoUpdate
});

useEffect(() => {
// Ignore all selection changes except those
// accompanied by a pointer event.
if (pointerEvent) {
if (selected.length > 0 && pointerEvent.type === 'pointerup') {
setIsOpen(true);
} else {
setIsOpen(false);
}
}
}, [pointerEvent, selected.map(a => a.annotation.id).join('-')]);
const dismiss = useDismiss(context);
const role = useRole(context, { role: 'tooltip' });
const { getFloatingProps } = useInteractions([dismiss, role]);

const selectedKey = selected.map(a => a.annotation.id).join('-');
useEffect(() => {
if (selected?.length > 0) {
const selector = selected[0].annotation.target.selector as (TextSelector | TextSelector[]);
const range = Array.isArray(selector) ? selector[0].range : selector.range;

if (range && !range.collapsed) {
refs.setReference({
getBoundingClientRect: () => {
return range.getBoundingClientRect();
},
getClientRects: () => {
const rect = mousePos
? getClosestRect(range.getClientRects(), mousePos)
: range.getClientRects()[0];

return toClientRects(rect);
}
});
}
// Ignore all selection changes except those accompanied by a pointer event.
if (pointerEvent) {
setOpen(selected.length > 0 && pointerEvent.type === 'pointerup');
}
}, [open, selected, mousePos]);
}, [pointerEvent?.type, selectedKey]);

useEffect(() => {
const onPointerUp = (event: PointerEvent) => {
const { clientX, clientY } = event;
setMousePos({ x: clientX, y: clientY });
}

const config: MutationObserverInit = { attributes: true, childList: true, subtree: true };
if (!isOpen || !annotation) return;

const mutationObserver = new MutationObserver(() =>
update());

mutationObserver.observe(document.body, config);
const {
target: {
selector: [{ range }]
}
} = annotation;

window.document.addEventListener('scroll', update, true);
window.document.addEventListener('pointerup', onPointerUp);
refs.setPositionReference({
getBoundingClientRect: range.getBoundingClientRect.bind(range),
getClientRects: range.getClientRects.bind(range)
});
}, [isOpen, annotation, refs]);

return () => {
mutationObserver.disconnect();
window.document.removeEventListener('scroll', update, true);
window.document.removeEventListener('pointerup', onPointerUp);
}
}, [update]);
// Prevent text-annotator from handling the irrelevant events triggered from the popup
const getStopEventsPropagationProps = useCallback(
() => ({ onPointerUp: (event: PointerEvent<HTMLDivElement>) => event.stopPropagation() }),
[]
);

return (isOpen && selected.length > 0) && (
return isOpen && selected.length > 0 ? (
<div
className="annotation-popup text-annotation-popup not-annotatable"
ref={refs.setFloating}
style={floatingStyles}>
style={floatingStyles}
{...getFloatingProps()}
{...getStopEventsPropagationProps()}>
{props.popup({ selected })}
</div>
)
) : null;

}
38 changes: 0 additions & 38 deletions packages/text-annotator-react/src/utils.ts

This file was deleted.