@soomo/react-text-annotator 3.0.0-staging.7 → 3.0.0-staging.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/TextAnnotatorPopup.d.ts +5 -4
  2. package/dist/TextAnnotatorPopup.d.ts.map +1 -1
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/react-text-annotator.es10.js +565 -34
  6. package/dist/react-text-annotator.es10.js.map +1 -1
  7. package/dist/react-text-annotator.es11.js +460 -856
  8. package/dist/react-text-annotator.es11.js.map +1 -1
  9. package/dist/react-text-annotator.es12.js +2 -2
  10. package/dist/react-text-annotator.es13.js +35 -2
  11. package/dist/react-text-annotator.es13.js.map +1 -1
  12. package/dist/react-text-annotator.es14.js +894 -109
  13. package/dist/react-text-annotator.es14.js.map +1 -1
  14. package/dist/react-text-annotator.es15.js +208 -289
  15. package/dist/react-text-annotator.es15.js.map +1 -1
  16. package/dist/react-text-annotator.es16.js +127 -49
  17. package/dist/react-text-annotator.es16.js.map +1 -1
  18. package/dist/react-text-annotator.es17.js +113 -19
  19. package/dist/react-text-annotator.es17.js.map +1 -1
  20. package/dist/react-text-annotator.es18.js +312 -0
  21. package/dist/react-text-annotator.es18.js.map +1 -0
  22. package/dist/react-text-annotator.es19.js +61 -0
  23. package/dist/react-text-annotator.es19.js.map +1 -0
  24. package/dist/react-text-annotator.es2.js +1 -1
  25. package/dist/react-text-annotator.es20.js +23 -0
  26. package/dist/react-text-annotator.es20.js.map +1 -0
  27. package/dist/react-text-annotator.es21.js +5 -0
  28. package/dist/react-text-annotator.es21.js.map +1 -0
  29. package/dist/react-text-annotator.es22.js +5 -0
  30. package/dist/react-text-annotator.es22.js.map +1 -0
  31. package/dist/react-text-annotator.es23.js +124 -0
  32. package/dist/react-text-annotator.es23.js.map +1 -0
  33. package/dist/react-text-annotator.es24.js +555 -0
  34. package/dist/react-text-annotator.es24.js.map +1 -0
  35. package/dist/react-text-annotator.es4.js.map +1 -1
  36. package/dist/react-text-annotator.es5.js +60 -36
  37. package/dist/react-text-annotator.es5.js.map +1 -1
  38. package/dist/react-text-annotator.es6.js +3 -3
  39. package/dist/react-text-annotator.es8.js +24 -488
  40. package/dist/react-text-annotator.es8.js.map +1 -1
  41. package/dist/react-text-annotator.es9.js +196 -2
  42. package/dist/react-text-annotator.es9.js.map +1 -1
  43. package/dist/utils.d.ts +14 -0
  44. package/dist/utils.d.ts.map +1 -0
  45. package/package.json +4 -3
@@ -1,51 +1,75 @@
1
1
  import { j as jsxRuntimeExports } from "./react-text-annotator.es6.js";
2
- import { createPortal } from "react-dom";
3
- import { useRef, useState, useEffect } from "react";
4
- import { useAnnotator, useSelection } from "@annotorious/react";
2
+ import { useState, useEffect } from "react";
3
+ import { useSelection } from "@annotorious/react";
4
+ import { getClosestRect, toClientRects } from "./react-text-annotator.es8.js";
5
+ import { useFloating } from "./react-text-annotator.es9.js";
6
+ import { autoPlacement, inline, offset, shift, autoUpdate } from "./react-text-annotator.es10.js";
5
7
  const TextAnnotatorPopup = (props) => {
6
- const el = useRef(null);
7
- const r = useAnnotator();
8
- const [open, setOpen] = useState(false);
9
8
  const { selected, pointerEvent } = useSelection();
9
+ const [mousePos, setMousePos] = useState();
10
+ const [isOpen, setIsOpen] = useState((selected == null ? void 0 : selected.length) > 0);
11
+ const { refs, floatingStyles, update } = useFloating({
12
+ open: isOpen,
13
+ onOpenChange: setIsOpen,
14
+ middleware: [
15
+ autoPlacement({ crossAxis: true, padding: 5 }),
16
+ inline(),
17
+ offset(5),
18
+ shift({ crossAxis: true, padding: 5 })
19
+ ],
20
+ whileElementsMounted: autoUpdate
21
+ });
10
22
  useEffect(() => {
11
23
  if (pointerEvent) {
12
24
  if (selected.length > 0 && pointerEvent.type === "pointerup") {
13
- setOpen(true);
25
+ setIsOpen(true);
14
26
  } else {
15
- setOpen(false);
27
+ setIsOpen(false);
16
28
  }
17
29
  }
18
30
  }, [pointerEvent, selected.map((a) => a.annotation.id).join("-")]);
19
31
  useEffect(() => {
20
- if (!(pointerEvent && open && (r == null ? void 0 : r.element)))
21
- return;
22
- const { left, top } = r.element.getBoundingClientRect();
23
- let x = pointerEvent.clientX - left;
24
- let y = pointerEvent.clientY - top;
25
- const { id } = selected[0].annotation;
26
- const { offsetX, offsetY } = pointerEvent;
27
- const bounds = r.state.store.getAnnotationBounds(id, offsetX, offsetY);
28
- if (bounds) {
29
- x = Math.max(x, bounds.x - left);
30
- x = Math.min(x, bounds.right - left);
31
- }
32
- el.current.style.left = `${x}px`;
33
- el.current.style.top = `${y}px`;
34
- }, [open, pointerEvent, r == null ? void 0 : r.element]);
35
- const onPointerUp = (evt) => evt.stopPropagation();
36
- return open && selected.length > 0 ? createPortal(
37
- /* @__PURE__ */ jsxRuntimeExports.jsx(
38
- "div",
39
- {
40
- ref: el,
41
- className: "a9s-popup r6o-popup not-annotatable",
42
- style: { position: "absolute" },
43
- onPointerUp,
44
- children: props.popup({ selected })
32
+ if ((selected == null ? void 0 : selected.length) > 0) {
33
+ const selector = selected[0].annotation.target.selector;
34
+ const range = Array.isArray(selector) ? selector[0].range : selector.range;
35
+ if (range && !range.collapsed) {
36
+ refs.setReference({
37
+ getBoundingClientRect: () => {
38
+ return range.getBoundingClientRect();
39
+ },
40
+ getClientRects: () => {
41
+ const rect = mousePos ? getClosestRect(range.getClientRects(), mousePos) : range.getClientRects()[0];
42
+ return toClientRects(rect);
43
+ }
44
+ });
45
45
  }
46
- ),
47
- r.element
48
- ) : null;
46
+ }
47
+ }, [open, selected, mousePos]);
48
+ useEffect(() => {
49
+ const onPointerUp = (event) => {
50
+ const { clientX, clientY } = event;
51
+ setMousePos({ x: clientX, y: clientY });
52
+ };
53
+ const config = { attributes: true, childList: true, subtree: true };
54
+ const mutationObserver = new MutationObserver(() => update());
55
+ mutationObserver.observe(document.body, config);
56
+ window.document.addEventListener("scroll", update, true);
57
+ window.document.addEventListener("pointerup", onPointerUp);
58
+ return () => {
59
+ mutationObserver.disconnect();
60
+ window.document.removeEventListener("scroll", update, true);
61
+ window.document.removeEventListener("pointerup", onPointerUp);
62
+ };
63
+ }, [update]);
64
+ return isOpen && selected.length > 0 && /* @__PURE__ */ jsxRuntimeExports.jsx(
65
+ "div",
66
+ {
67
+ className: "annotation-popup text-annotation-popup not-annotatable",
68
+ ref: refs.setFloating,
69
+ style: floatingStyles,
70
+ children: props.popup({ selected })
71
+ }
72
+ );
49
73
  };
50
74
  export {
51
75
  TextAnnotatorPopup
@@ -1 +1 @@
1
- {"version":3,"file":"react-text-annotator.es5.js","sources":["../src/TextAnnotatorPopup.tsx"],"sourcesContent":["import { createPortal } from 'react-dom';\nimport { ReactNode, useEffect, useRef, useState } from 'react';\nimport { TextAnnotator, TextAnnotation, TextAnnotatorState } from '@soomo/text-annotator';\nimport { useAnnotator, useSelection } from '@annotorious/react';\n\nexport interface TextAnnotatorPopupProps {\n\n selected: { annotation: TextAnnotation, editable?: boolean }[];\n\n}\n\nexport interface TextAnnotatorPopupContainerProps {\n\n popup(props: TextAnnotatorPopupProps): ReactNode | JSX.Element;\n\n}\n\nexport const TextAnnotatorPopup = (props: TextAnnotatorPopupContainerProps) => {\n\n const el = useRef<HTMLDivElement>(null);\n\n const r = useAnnotator<TextAnnotator>();\n\n const [open, setOpen] = useState(false);\n\n const { selected, pointerEvent } = useSelection<TextAnnotation>();\n\n useEffect(() => {\n // Ignore all selection changes except those\n // accompanied by a pointer event.\n if (pointerEvent) {\n if (selected.length > 0 && pointerEvent.type === 'pointerup') {\n setOpen(true);\n } else {\n setOpen(false);\n }\n }\n }, [pointerEvent, selected.map(a => a.annotation.id).join('-')]);\n\n useEffect(() => {\n if (!(pointerEvent && open && r?.element))\n return;\n\n const { left, top } = r.element.getBoundingClientRect();\n let x = pointerEvent.clientX - left;\n let y = pointerEvent.clientY - top;\n\n const { id } = selected[0].annotation;\n const { offsetX, offsetY } = pointerEvent;\n const bounds = (r.state as TextAnnotatorState).store.getAnnotationBounds(id, offsetX, offsetY);\n \n if (bounds) {\n x = Math.max(x, bounds.x - left);\n x = Math.min(x, bounds.right - left);\n }\n\n el.current.style.left = `${x}px`;\n el.current.style.top = `${y}px`;\n }, [open, pointerEvent, r?.element]);\n\n const onPointerUp = (evt: React.PointerEvent<HTMLDivElement>) =>\n evt.stopPropagation();\n \n return (open && selected.length > 0) ? createPortal(\n <div \n ref={el}\n className=\"a9s-popup r6o-popup not-annotatable\"\n style={{ position: 'absolute' }}\n onPointerUp={onPointerUp}>\n\n {props.popup({ selected })}\n \n </div>, r.element\n ) : null;\n\n}\n"],"names":["jsx"],"mappings":";;;;AAiBa,MAAA,qBAAqB,CAAC,UAA4C;AAEvE,QAAA,KAAK,OAAuB,IAAI;AAEtC,QAAM,IAAI;AAEV,QAAM,CAAC,MAAM,OAAO,IAAI,SAAS,KAAK;AAEtC,QAAM,EAAE,UAAU,aAAa,IAAI,aAA6B;AAEhE,YAAU,MAAM;AAGd,QAAI,cAAc;AAChB,UAAI,SAAS,SAAS,KAAK,aAAa,SAAS,aAAa;AAC5D,gBAAQ,IAAI;AAAA,MAAA,OACP;AACL,gBAAQ,KAAK;AAAA,MACf;AAAA,IACF;AAAA,EACC,GAAA,CAAC,cAAc,SAAS,IAAI,CAAA,MAAK,EAAE,WAAW,EAAE,EAAE,KAAK,GAAG,CAAC,CAAC;AAE/D,YAAU,MAAM;AACV,QAAA,EAAE,gBAAgB,SAAQ,uBAAG;AAC/B;AAEF,UAAM,EAAE,MAAM,IAAA,IAAQ,EAAE,QAAQ;AAC5B,QAAA,IAAI,aAAa,UAAU;AAC3B,QAAA,IAAI,aAAa,UAAU;AAE/B,UAAM,EAAE,GAAO,IAAA,SAAS,CAAC,EAAE;AACrB,UAAA,EAAE,SAAS,QAAY,IAAA;AAC7B,UAAM,SAAU,EAAE,MAA6B,MAAM,oBAAoB,IAAI,SAAS,OAAO;AAE7F,QAAI,QAAQ;AACV,UAAI,KAAK,IAAI,GAAG,OAAO,IAAI,IAAI;AAC/B,UAAI,KAAK,IAAI,GAAG,OAAO,QAAQ,IAAI;AAAA,IACrC;AAEA,OAAG,QAAQ,MAAM,OAAO,GAAG,CAAC;AAC5B,OAAG,QAAQ,MAAM,MAAM,GAAG,CAAC;AAAA,KAC1B,CAAC,MAAM,cAAc,uBAAG,OAAO,CAAC;AAEnC,QAAM,cAAc,CAAC,QACnB,IAAI,gBAAgB;AAEd,SAAA,QAAQ,SAAS,SAAS,IAAK;AAAA,IACrCA,kCAAA;AAAA,MAAC;AAAA,MAAA;AAAA,QACC,KAAK;AAAA,QACL,WAAU;AAAA,QACV,OAAO,EAAE,UAAU,WAAW;AAAA,QAC9B;AAAA,QAEC,UAAM,MAAA,MAAM,EAAE,SAAA,CAAU;AAAA,MAAA;AAAA,IAE3B;AAAA,IAAQ,EAAE;AAAA,EACR,IAAA;AAEN;"}
1
+ {"version":3,"file":"react-text-annotator.es5.js","sources":["../src/TextAnnotatorPopup.tsx"],"sourcesContent":["import { ReactNode, useEffect, useState } from 'react';\nimport { useSelection } from '@annotorious/react';\nimport type { TextAnnotation, TextSelector } from '@soomo/text-annotator';\nimport { getClosestRect, toClientRects } from './utils';\nimport {\n autoPlacement,\n autoUpdate,\n inline,\n offset,\n shift,\n useFloating\n} from '@floating-ui/react';\n\ninterface TextAnnotationPopupProps {\n\n popup(props: TextAnnotatorPopupProps): ReactNode;\n\n}\n\nexport interface TextAnnotatorPopupProps {\n\n selected: { annotation: TextAnnotation, editable?: boolean }[];\n\n}\n\nexport const TextAnnotatorPopup = (props: TextAnnotationPopupProps) => {\n\n const { selected, pointerEvent } = useSelection<TextAnnotation>();\n\n const [mousePos, setMousePos] = useState<{ x: number, y: number } | undefined>();\n\n const [isOpen, setIsOpen] = useState(selected?.length > 0);\n\n const { refs, floatingStyles, update } = useFloating({\n open: isOpen,\n onOpenChange: setIsOpen,\n middleware: [\n autoPlacement({ crossAxis: true, padding: 5 }),\n inline(),\n offset(5),\n shift({ crossAxis: true, padding: 5 })\n ],\n whileElementsMounted: autoUpdate\n });\n\n useEffect(() => {\n // Ignore all selection changes except those\n // accompanied by a pointer event.\n if (pointerEvent) {\n if (selected.length > 0 && pointerEvent.type === 'pointerup') {\n setIsOpen(true);\n } else {\n setIsOpen(false);\n }\n }\n }, [pointerEvent, selected.map(a => a.annotation.id).join('-')]);\n\n useEffect(() => {\n if (selected?.length > 0) {\n const selector = selected[0].annotation.target.selector as (TextSelector | TextSelector[]);\n const range = Array.isArray(selector) ? selector[0].range : selector.range;\n\n if (range && !range.collapsed) {\n refs.setReference({\n getBoundingClientRect: () => {\n return range.getBoundingClientRect();\n },\n getClientRects: () => {\n const rect = mousePos\n ? getClosestRect(range.getClientRects(), mousePos)\n : range.getClientRects()[0];\n\n return toClientRects(rect);\n }\n });\n }\n }\n }, [open, selected, mousePos]);\n\n useEffect(() => {\n const onPointerUp = (event: PointerEvent) => {\n const { clientX, clientY } = event;\n setMousePos({ x: clientX, y: clientY });\n }\n\n const config: MutationObserverInit = { attributes: true, childList: true, subtree: true };\n\n const mutationObserver = new MutationObserver(() =>\n update());\n\n mutationObserver.observe(document.body, config);\n\n window.document.addEventListener('scroll', update, true);\n window.document.addEventListener('pointerup', onPointerUp);\n\n return () => {\n mutationObserver.disconnect();\n window.document.removeEventListener('scroll', update, true);\n window.document.removeEventListener('pointerup', onPointerUp);\n }\n }, [update]);\n\n return (isOpen && selected.length > 0) && (\n <div\n className=\"annotation-popup text-annotation-popup not-annotatable\"\n ref={refs.setFloating}\n style={floatingStyles}>\n {props.popup({ selected })}\n </div>\n )\n\n}\n"],"names":["jsx"],"mappings":";;;;;;AAyBa,MAAA,qBAAqB,CAAC,UAAoC;AAErE,QAAM,EAAE,UAAU,aAAa,IAAI,aAA6B;AAEhE,QAAM,CAAC,UAAU,WAAW,IAAI,SAA+C;AAE/E,QAAM,CAAC,QAAQ,SAAS,IAAI,UAAS,qCAAU,UAAS,CAAC;AAEzD,QAAM,EAAE,MAAM,gBAAgB,OAAA,IAAW,YAAY;AAAA,IACnD,MAAM;AAAA,IACN,cAAc;AAAA,IACd,YAAY;AAAA,MACV,cAAc,EAAE,WAAW,MAAM,SAAS,GAAG;AAAA,MAC7C,OAAO;AAAA,MACP,OAAO,CAAC;AAAA,MACR,MAAM,EAAE,WAAW,MAAM,SAAS,GAAG;AAAA,IACvC;AAAA,IACA,sBAAsB;AAAA,EAAA,CACvB;AAED,YAAU,MAAM;AAGd,QAAI,cAAc;AAChB,UAAI,SAAS,SAAS,KAAK,aAAa,SAAS,aAAa;AAC5D,kBAAU,IAAI;AAAA,MAAA,OACT;AACL,kBAAU,KAAK;AAAA,MACjB;AAAA,IACF;AAAA,EACC,GAAA,CAAC,cAAc,SAAS,IAAI,CAAA,MAAK,EAAE,WAAW,EAAE,EAAE,KAAK,GAAG,CAAC,CAAC;AAE/D,YAAU,MAAM;AACV,SAAA,qCAAU,UAAS,GAAG;AACxB,YAAM,WAAW,SAAS,CAAC,EAAE,WAAW,OAAO;AACzC,YAAA,QAAQ,MAAM,QAAQ,QAAQ,IAAI,SAAS,CAAC,EAAE,QAAQ,SAAS;AAEjE,UAAA,SAAS,CAAC,MAAM,WAAW;AAC7B,aAAK,aAAa;AAAA,UAChB,uBAAuB,MAAM;AAC3B,mBAAO,MAAM;UACf;AAAA,UACA,gBAAgB,MAAM;AACd,kBAAA,OAAO,WACT,eAAe,MAAM,eAAA,GAAkB,QAAQ,IAC/C,MAAM,eAAe,EAAE,CAAC;AAE5B,mBAAO,cAAc,IAAI;AAAA,UAC3B;AAAA,QAAA,CACD;AAAA,MACH;AAAA,IACF;AAAA,EACC,GAAA,CAAC,MAAM,UAAU,QAAQ,CAAC;AAE7B,YAAU,MAAM;AACR,UAAA,cAAc,CAAC,UAAwB;AACrC,YAAA,EAAE,SAAS,QAAY,IAAA;AAC7B,kBAAY,EAAE,GAAG,SAAS,GAAG,QAAS,CAAA;AAAA,IAAA;AAGxC,UAAM,SAA+B,EAAE,YAAY,MAAM,WAAW,MAAM,SAAS;AAEnF,UAAM,mBAAmB,IAAI,iBAAiB,MAC5C,OAAQ,CAAA;AAEO,qBAAA,QAAQ,SAAS,MAAM,MAAM;AAE9C,WAAO,SAAS,iBAAiB,UAAU,QAAQ,IAAI;AAChD,WAAA,SAAS,iBAAiB,aAAa,WAAW;AAEzD,WAAO,MAAM;AACX,uBAAiB,WAAW;AAC5B,aAAO,SAAS,oBAAoB,UAAU,QAAQ,IAAI;AACnD,aAAA,SAAS,oBAAoB,aAAa,WAAW;AAAA,IAAA;AAAA,EAC9D,GACC,CAAC,MAAM,CAAC;AAEH,SAAA,UAAU,SAAS,SAAS,KAClCA,kCAAA;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAU;AAAA,MACV,KAAK,KAAK;AAAA,MACV,OAAO;AAAA,MACN,UAAM,MAAA,MAAM,EAAE,SAAA,CAAU;AAAA,IAAA;AAAA,EAAA;AAI/B;"}
@@ -1,6 +1,6 @@
1
- import { __module as jsxRuntime } from "./react-text-annotator.es9.js";
2
- import { __require as requireReactJsxRuntime_production_min } from "./react-text-annotator.es10.js";
3
- import { __require as requireReactJsxRuntime_development } from "./react-text-annotator.es11.js";
1
+ import { __module as jsxRuntime } from "./react-text-annotator.es12.js";
2
+ import { __require as requireReactJsxRuntime_production_min } from "./react-text-annotator.es13.js";
3
+ import { __require as requireReactJsxRuntime_development } from "./react-text-annotator.es14.js";
4
4
  if (process.env.NODE_ENV === "production") {
5
5
  jsxRuntime.exports = requireReactJsxRuntime_production_min();
6
6
  } else {
@@ -1,491 +1,27 @@
1
- import defaultBehaviors from "./react-text-annotator.es14.js";
2
- import * as utilities from "./react-text-annotator.es15.js";
3
- import { hideContent, defineCustomElement, tagName } from "./react-text-annotator.es15.js";
4
- import { addBehaviors, addBehavior, removeBehavior } from "./react-text-annotator.es16.js";
5
- import { learnElementNames, learnCustomElementNames } from "./react-text-annotator.es17.js";
6
- class CETEI {
7
- constructor(options) {
8
- this.options = options ? options : {};
9
- this.document = this.options.documentObject ? this.options.documentObject : void 0;
10
- if (this.document === void 0) {
11
- if (typeof window !== "undefined" && window.document) {
12
- this.document = window.document;
13
- } else if (typeof global !== "undefined" && global.document) {
14
- this.document = global.document;
15
- }
16
- }
17
- this.addBehaviors = addBehaviors.bind(this);
18
- this.addBehavior = addBehavior.bind(this);
19
- this.removeBehavior = removeBehavior.bind(this);
20
- this.utilities = {};
21
- for (const u of Object.keys(utilities)) {
22
- if (["getPrefixDef", "rw", "resolveURI"].includes(u)) {
23
- this.utilities[u] = utilities[u].bind(this);
24
- } else {
25
- this.utilities[u] = utilities[u];
26
- }
27
- }
28
- this.els = [];
29
- this.namespaces = /* @__PURE__ */ new Map();
30
- this.behaviors = {};
31
- this.hasStyle = false;
32
- this.prefixDefs = [];
33
- this.debug = this.options.debug === true ? true : false;
34
- this.discardContent = this.options.discardContent === true ? true : false;
35
- if (this.options.base) {
36
- this.base = this.options.base;
37
- } else {
38
- try {
39
- if (window) {
40
- this.base = window.location.href.replace(/\/[^\/]*$/, "/");
41
- }
42
- } catch (e) {
43
- this.base = "";
44
- }
45
- }
46
- if (!this.options.omitDefaultBehaviors) {
47
- this.addBehaviors(defaultBehaviors);
48
- }
49
- if (this.options.ignoreFragmentId) {
50
- if (window) {
51
- window.removeEventListener("ceteiceanload", CETEI.restorePosition);
52
- }
53
- }
54
- }
55
- /*
56
- Returns a Promise that fetches an XML source document from the URL
57
- provided in the first parameter and then calls the makeHTML5 method
58
- on the returned document.
59
- */
60
- async getHTML5(XML_url, callback, perElementFn) {
61
- if (window && window.location.href.startsWith(this.base) && XML_url.indexOf("/") >= 0) {
62
- this.base = XML_url.replace(/\/[^\/]*$/, "/");
63
- }
64
- try {
65
- const response = await fetch(XML_url);
66
- if (response.ok) {
67
- const XML = await response.text();
68
- return this.makeHTML5(XML, callback, perElementFn);
69
- } else {
70
- console.log(`Could not get XML file ${XML_url}.
71
- Server returned ${response.status}: ${response.statusText}`);
72
- }
73
- } catch (error) {
74
- console.log(error);
75
- }
76
- }
77
- /*
78
- Converts the supplied XML string into HTML5 Custom Elements. If a callback
79
- function is supplied, calls it on the result.
80
- */
81
- makeHTML5(XML, callback, perElementFn) {
82
- this.XML_dom = new DOMParser().parseFromString(XML, "text/xml");
83
- return this.domToHTML5(this.XML_dom, callback, perElementFn);
84
- }
85
- preprocess(XML_dom, callback, perElementFn) {
86
- this.els = learnElementNames(XML_dom, this.namespaces);
87
- let convertEl = (el) => {
88
- let newElement;
89
- if (this.namespaces.has(el.namespaceURI ? el.namespaceURI : "")) {
90
- let prefix = this.namespaces.get(el.namespaceURI ? el.namespaceURI : "");
91
- newElement = this.document.createElement(`${prefix}-${el.localName.toLowerCase()}`);
92
- } else {
93
- newElement = this.document.importNode(el, false);
94
- }
95
- for (let att of Array.from(el.attributes)) {
96
- if (att.name == "xmlns") {
97
- newElement.setAttribute("data-xmlns", att.value);
98
- } else {
99
- newElement.setAttribute(att.name, att.value);
100
- }
101
- if (att.name == "xml:id") {
102
- newElement.setAttribute("id", att.value);
103
- }
104
- if (att.name == "xml:lang") {
105
- newElement.setAttribute("lang", att.value);
106
- }
107
- if (att.name == "rendition") {
108
- newElement.setAttribute("class", att.value.replace(/#/g, ""));
109
- }
110
- }
111
- newElement.setAttribute("data-origname", el.localName);
112
- if (el.hasAttributes()) {
113
- newElement.setAttribute("data-origatts", el.getAttributeNames().join(" "));
114
- }
115
- if (el.childNodes.length == 0) {
116
- newElement.setAttribute("data-empty", "");
117
- }
118
- if (el.localName == "head") {
119
- let level = XML_dom.evaluate("count(ancestor::*[tei:head])", el, function(ns) {
120
- if (ns == "tei")
121
- return "http://www.tei-c.org/ns/1.0";
122
- }, 1, null);
123
- newElement.setAttribute("data-level", level.numberValue);
124
- }
125
- if (el.localName == "tagsDecl") {
126
- let style = this.document.createElement("style");
127
- for (let node of Array.from(el.childNodes)) {
128
- if (node.nodeType == 1 && node.localName == "rendition" && node.getAttribute("scheme") == "css") {
129
- let rule = "";
130
- if (node.hasAttribute("selector")) {
131
- rule += node.getAttribute("selector").replace(/([^#, >]+\w*)/g, "tei-$1").replace(/#tei-/g, "#") + "{\n";
132
- rule += node.textContent;
133
- } else {
134
- rule += "." + node.getAttribute("xml:id") + "{\n";
135
- rule += node.textContent;
136
- }
137
- rule += "\n}\n";
138
- style.appendChild(this.document.createTextNode(rule));
139
- }
140
- }
141
- if (style.childNodes.length > 0) {
142
- newElement.appendChild(style);
143
- this.hasStyle = true;
144
- }
145
- }
146
- if (el.localName == "prefixDef") {
147
- this.prefixDefs.push(el.getAttribute("ident"));
148
- this.prefixDefs[el.getAttribute("ident")] = {
149
- "matchPattern": el.getAttribute("matchPattern"),
150
- "replacementPattern": el.getAttribute("replacementPattern")
151
- };
152
- }
153
- for (let node of Array.from(el.childNodes)) {
154
- if (node.nodeType == 1) {
155
- newElement.appendChild(convertEl(node));
156
- } else {
157
- newElement.appendChild(node.cloneNode());
158
- }
159
- }
160
- if (perElementFn) {
161
- perElementFn(newElement, el);
162
- }
163
- return newElement;
164
- };
165
- this.dom = this.document.createDocumentFragment();
166
- for (let node of Array.from(XML_dom.childNodes)) {
167
- if (node.nodeType == 1) {
168
- this.dom.appendChild(convertEl(node));
169
- }
170
- if (node.nodeType == 7) {
171
- this.dom.appendChild(this.document.importNode(node, true));
172
- }
173
- if (node.nodeType == 8) {
174
- this.dom.appendChild(this.document.importNode(node, true));
175
- }
176
- }
177
- this.utilities.dom = this.dom.firstElementChild;
178
- if (callback) {
179
- callback(this.dom, this);
180
- if (window) {
181
- window.dispatchEvent(ceteiceanLoad);
182
- }
183
- } else {
184
- if (typeof window !== "undefined") {
185
- window.dispatchEvent(ceteiceanLoad);
186
- }
187
- return this.dom;
188
- }
189
- }
190
- /*
191
- Converts the supplied XML DOM into HTML5 Custom Elements. If a callback
192
- function is supplied, calls it on the result.
193
- */
194
- domToHTML5(XML_dom, callback, perElementFn) {
195
- this.preprocess(XML_dom, null, perElementFn);
196
- this.applyBehaviors();
197
- this.done = true;
198
- if (callback) {
199
- callback(this.dom, this);
200
- if (window) {
201
- window.dispatchEvent(ceteiceanLoad);
202
- }
203
- } else {
204
- if (typeof window !== "undefined") {
205
- window.dispatchEvent(ceteiceanLoad);
206
- }
207
- return this.dom;
208
- }
209
- }
210
- /*
211
- Convenience method for HTML pages containing pre-processed CETEIcean Custom
212
- Elements. Usage:
213
- const c = new CETEI();
214
- c.processPage();
215
- */
216
- processPage() {
217
- this.els = learnCustomElementNames(this.document);
218
- this.applyBehaviors();
219
- if (window) {
220
- window.dispatchEvent(ceteiceanLoad);
221
- }
222
- }
223
- /*
224
- To change a namespace -> prefix mapping, the namespace must first be
225
- unset. Takes a namespace URI. In order to process a TEI P4 document, e.g.,
226
- the TEI namespace must be unset before it can be set to the empty string.
227
- */
228
- unsetNamespace(ns) {
229
- this.namespaces.delete(ns);
230
- }
231
- /*
232
- Sets the base URL for the document. Used to rewrite relative links in the
233
- XML source (which may be in a completely different location from the HTML
234
- wrapper).
235
- */
236
- setBaseUrl(base) {
237
- this.base = base;
238
- }
239
- /*
240
- Appends any element returned by the function passed in the first
241
- parameter to the element in the second parameter. If the function
242
- returns nothing, this is a no-op aside from any side effects caused
243
- by the provided function.
244
-
245
- Called by getHandler() and fallback()
246
- */
247
- append(fn, elt) {
248
- let self = this;
249
- if (elt && !elt.hasAttribute("data-processed")) {
250
- let content = fn.call(self.utilities, elt);
251
- if (content) {
252
- self.appendBasic(elt, content);
253
- }
254
- } else {
255
- return function() {
256
- if (!this.hasAttribute("data-processed")) {
257
- let content = fn.call(self.utilities, this);
258
- if (content) {
259
- self.appendBasic(this, content);
260
- }
261
- }
262
- };
263
- }
264
- }
265
- appendBasic(elt, content) {
266
- if (this.discardContent) {
267
- elt.innerHTML = "";
268
- } else {
269
- hideContent(elt, true);
270
- }
271
- elt.appendChild(content);
272
- }
273
- // Given an element, return its qualified name as defined in a behaviors object
274
- bName(e) {
275
- return e.tagName.substring(0, e.tagName.indexOf("-")).toLowerCase() + ":" + e.getAttribute("data-origname");
276
- }
277
- /*
278
- Private method called by append(). Takes a child element and a name, and recurses through the
279
- child's siblings until an element with that name is found, returning true if it is and false if not.
280
- */
281
- childExists(elt, name) {
282
- if (elt && elt.nodeName == name) {
283
- return true;
284
- } else {
285
- return elt && elt.nextElementSibling && this.childExists(elt.nextElementSibling, name);
286
- }
287
- }
288
- /*
289
- Takes a template in the form of either an array of 1 or 2
290
- strings or an object with CSS selector keys and either functions
291
- or arrays as described above. Returns a closure around a function
292
- that can be called in the element constructor or applied to an
293
- individual element. An empty array is considered a no-op.
294
-
295
- Called by the getHandler() and getFallback() methods
296
- */
297
- decorator(template) {
298
- if (Array.isArray(template) && template.length == 0) {
299
- return function(e) {
300
- };
301
- }
302
- if (Array.isArray(template) && !Array.isArray(template[0])) {
303
- return this.applyDecorator(template);
304
- }
305
- let self = this;
306
- return function(elt) {
307
- for (let rule of template) {
308
- if (elt.matches(rule[0]) || rule[0] === "_") {
309
- if (Array.isArray(rule[1])) {
310
- return self.decorator(rule[1]).call(this, elt);
311
- } else {
312
- return rule[1].call(this, elt);
313
- }
314
- }
315
- }
316
- };
317
- }
318
- applyDecorator(strings) {
319
- let self = this;
320
- return function(elt) {
321
- let copy = [];
322
- for (let i = 0; i < strings.length; i++) {
323
- copy.push(self.template(strings[i], elt));
324
- }
325
- return self.insert(elt, copy);
326
- };
327
- }
328
- /*
329
- Returns the fallback function for the given element name.
330
- Called by fallback().
331
- */
332
- getFallback(behaviors, fn) {
333
- if (behaviors[fn]) {
334
- if (behaviors[fn] instanceof Function) {
335
- return behaviors[fn];
336
- } else {
337
- return this.decorator(behaviors[fn]);
338
- }
339
- }
340
- }
341
- /*
342
- Returns the handler function for the given element name
343
- Called by define().
344
- */
345
- getHandler(behaviors, fn) {
346
- if (behaviors[fn]) {
347
- if (behaviors[fn] instanceof Function) {
348
- return this.append(behaviors[fn]);
349
- } else {
350
- return this.append(this.decorator(behaviors[fn]));
351
- }
352
- }
353
- }
354
- insert(elt, strings) {
355
- let content = this.document.createElement("cetei-content");
356
- for (let node of Array.from(elt.childNodes)) {
357
- if (node.nodeType === 1 && !node.hasAttribute("data-processed")) {
358
- this.processElement(node);
359
- }
360
- }
361
- if (strings[0].match("<[^>]+>") && strings[1] && strings[1].match("<[^>]+>")) {
362
- content.innerHTML = strings[0] + elt.innerHTML + (strings[1] ? strings[1] : "");
363
- } else {
364
- content.innerHTML = strings[0];
365
- content.setAttribute("data-before", strings[0].replace(/<[^>]+>/g, "").length);
366
- for (let node of Array.from(elt.childNodes)) {
367
- content.appendChild(node.cloneNode(true));
368
- }
369
- if (strings.length > 1) {
370
- content.innerHTML += strings[1];
371
- content.setAttribute("data-after", strings[1].replace(/<[^>]+>/g, "").length);
372
- }
373
- }
374
- if (content.childNodes.length < 2) {
375
- return content.firstChild;
376
- } else {
377
- return content;
378
- }
379
- }
380
- // Runs behaviors recursively on the supplied element and children
381
- processElement(elt) {
382
- if (elt.hasAttribute("data-origname") && !elt.hasAttribute("data-processed")) {
383
- let fn = this.getFallback(this.bName(elt));
384
- if (fn) {
385
- this.append(fn, elt);
386
- elt.setAttribute("data-processed", "");
387
- }
388
- }
389
- for (let node of Array.from(elt.childNodes)) {
390
- if (node.nodeType === 1) {
391
- this.processElement(node);
392
- }
393
- }
394
- }
395
- template(str, elt) {
396
- let result = str;
397
- if (str.search(/\$(\w*)(@([a-zA-Z:]+))/)) {
398
- let re = /\$(\w*)@([a-zA-Z:]+)/g;
399
- let replacements;
400
- while (replacements = re.exec(str)) {
401
- if (elt.hasAttribute(replacements[2])) {
402
- if (replacements[1] && this.utilities[replacements[1]]) {
403
- result = result.replace(replacements[0], this.utilities[replacements[1]](elt.getAttribute(replacements[2])));
404
- } else {
405
- result = result.replace(replacements[0], elt.getAttribute(replacements[2]));
406
- }
407
- } else {
408
- result = result.replace(replacements[0], "");
409
- }
410
- }
411
- }
412
- return result;
413
- }
414
- // Define or apply behaviors for the document
415
- applyBehaviors() {
416
- if (typeof window !== "undefined" && window.customElements) {
417
- this.define.call(this, this.els);
418
- } else {
419
- this.fallback.call(this, this.els);
420
- }
421
- }
422
- /*
423
- Registers the list of elements provided with the browser.
424
- Called by makeHTML5(), but can be called independently if, for example,
425
- you've created Custom Elements via an XSLT transformation instead.
426
- */
427
- define(names) {
428
- for (let name of names) {
429
- const fn = this.getHandler(this.behaviors, name);
430
- defineCustomElement(name, fn, this.debug);
431
- }
432
- }
433
- /*
434
- Provides fallback functionality for environments where Custom Elements
435
- are not supported.
436
-
437
- Like define(), this is called by makeHTML5(), but can be called
438
- independently.
439
- */
440
- fallback(names) {
441
- for (let name of names) {
442
- let fn = this.getFallback(this.behaviors, name);
443
- if (fn) {
444
- for (let elt of Array.from((this.dom && !this.done ? this.dom : this.document).querySelectorAll(tagName(name)))) {
445
- if (!elt.hasAttribute("data-processed")) {
446
- this.append(fn, elt);
447
- elt.setAttribute("data-processed", "");
448
- }
449
- }
450
- }
451
- }
452
- }
453
- /**********************
454
- * Utility functions *
455
- **********************/
456
- static savePosition() {
457
- window.sessionStorage.setItem(window.location + "-scroll", window.scrollY);
458
- }
459
- static restorePosition() {
460
- if (!window.location.hash) {
461
- let scroll;
462
- if (scroll = window.sessionStorage.getItem(window.location + "-scroll")) {
463
- window.sessionStorage.removeItem(window.location + "-scroll");
464
- setTimeout(function() {
465
- window.scrollTo(0, scroll);
466
- }, 100);
467
- }
468
- } else {
469
- setTimeout(function() {
470
- let h = this.document.querySelector(window.decodeURI(window.location.hash));
471
- if (h) {
472
- h.scrollIntoView();
473
- }
474
- }, 100);
475
- }
476
- }
477
- }
478
- try {
479
- if (typeof window !== "undefined") {
480
- window.CETEI = CETEI;
481
- window.addEventListener("beforeunload", CETEI.savePosition);
482
- var ceteiceanLoad = new Event("ceteiceanload");
483
- window.addEventListener("ceteiceanload", CETEI.restorePosition);
484
- }
485
- } catch (e) {
486
- console.log(e);
487
- }
1
+ const getClosestRect = (rects, pos) => {
2
+ const uncollapsed = [...rects].filter((r) => r.width > 0 && r.height > 0);
3
+ let closest;
4
+ let minDist = Number.MAX_VALUE;
5
+ uncollapsed.forEach((rect) => {
6
+ const centerY = rect.top + rect.height / 2;
7
+ const dist = Math.abs(centerY - pos.y);
8
+ if (dist < minDist) {
9
+ minDist = dist;
10
+ closest = rect;
11
+ }
12
+ });
13
+ return closest;
14
+ };
15
+ const toClientRects = (rect) => ({
16
+ length: 1,
17
+ item: (index) => index === 0 ? rect : void 0,
18
+ [Symbol.iterator]: function* () {
19
+ for (let i = 0; i < this.length; i++)
20
+ yield this.item(i);
21
+ }
22
+ });
488
23
  export {
489
- CETEI as default
24
+ getClosestRect,
25
+ toClientRects
490
26
  };
491
27
  //# sourceMappingURL=react-text-annotator.es8.js.map