apache / incubator-annotator

Apache Annotator provides annotation enabling code for browsers, servers, and humans.
https://annotator.apache.org/
Apache License 2.0
218 stars 44 forks source link

I'm not getting the text position #128

Closed raphael10-collab closed 1 year ago

raphael10-collab commented 2 years ago

The text is highlighted but I do not get the text position, needed for further annotating

image

image

This is the code I'm using:

// https://annotator.apache.org/docs/getting-started/

import { describeTextQuote } from '@apache-annotator/dom'
import { createTextQuoteSelectorMatcher, highlightText } from '@apache-annotator/dom';

async function describeCurrentSelection() {
  const userSelection = window.getSelection()?.getRangeAt(0);

  console.log("view-preload.ts-userSelection: ", userSelection)

  if (!userSelection || userSelection.isCollapsed) return;

  console.log("view-preloads-describeTextQuote(userSelection): ", describeTextQuote(userSelection))

  return describeTextQuote(userSelection);
}

async function highlightSelectorTarget(textQuoteSelector) {
  const matches = createTextQuoteSelectorMatcher(textQuoteSelector)(document.body);

  console.log("view-preload.ts-highlighSelectorTarger-matches: ", matches)

  // Modifying the DOM while searching can mess up; see issue #112.
  // Therefore, we first collect all matches before highlighting them.
  const matchList = [];
  for await (const match of matches) matchList.push(match);

  for (const match of matchList) highlightText(match);
}

document.addEventListener('mouseup', async () => {

  const selector = await describeCurrentSelection();
  const existingSelectors = JSON.parse(localStorage[document.URL] || '[]');
  localStorage[document.URL] = JSON.stringify([...existingSelectors, selector]);
  await highlightSelectorTarget(selector);
})

// Highlight the last selection that was stored, if any.
async function highlightStoredSelectors() {
  if (localStorage[document.URL]) {
    const selectors = JSON.parse(localStorage[document.URL]);
    for (const selector of selectors) {
      console.log("view-preload.ts-highlightStoredSelectors-selector: ", selector)
      await highlightSelectorTarget(selector);
    }
  }
}
highlightStoredSelectors()

window.addEventListener('mouseup', (e) => {
  if (e.button === 3) {
    e.preventDefault();
    goBack();
  } else if (e.button === 4) {
    e.preventDefault();
    goForward();
  }
});
Treora commented 1 year ago

A quick response, as I (nor others, it seems) get around to look further at your issue. From your description it’s not clear to me what you mean. If you mean to create a TextPositionSelector, see the describeTextPosition. Best to get the position of the selection before highlighting it (if you do both), because the highlighter will modify the dom and thereby the selection. If you mean position as in coordinates on the page, you can get those from the browser’s APIs, e.g. Range.getBoundingClientRect. I hope that helps.