File size: 3,732 Bytes
29b6f8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import type { Prediction } from './lite';

const FIELD_LABELS = new Map([
  ['TITLE', '題名'], ['CONTAINER_TITLE', '掲載先'], ['DATE', '日付'], ['VOLUME', '巻'],
  ['ISSUE', '号'], ['PAGES', 'ページ'], ['ISSUER', '発行元'], ['LOCATION', '出版地'],
  ['DOI', 'DOI'], ['ISBN', 'ISBN'], ['URL', 'URL'], ['EDITION', '版'], ['VERSION', 'バージョン'],
]);
const ROLE_LABELS = new Map([
  ['author.work', '著者'], ['editor.work', '編者'], ['translator.work', '訳者'],
  ['author.container', '収録先の著者'], ['editor.container', '収録先の編者'],
  ['translator.container', '収録先の訳者'],
]);
const NAME_LABELS = new Map([['family', '姓'], ['given', '名']]);

interface Annotation {
  start: number;
  end: number;
  label: string;
  tone: 'title' | 'detail' | 'contributor' | 'name';
  parts?: Annotation[];
}

function annotatedText(
  characters: string[], start: number, end: number, annotations: Annotation[],
): DocumentFragment {
  const fragment = document.createDocumentFragment();
  let position = start;
  for (const item of annotations.sort((left, right) => left.start - right.start)) {
    if (item.start < position || item.end > end || item.end <= item.start) continue;
    fragment.append(characters.slice(position, item.start).join(''));
    const highlight = document.createElement(item.tone === 'name' ? 'span' : 'mark');
    highlight.className = `annotation annotation--${item.tone}`;
    highlight.append(item.parts?.length
      ? annotatedText(characters, item.start, item.end, item.parts)
      : characters.slice(item.start, item.end).join(''));
    const label = document.createElement('span');
    label.className = 'annotation-label';
    label.textContent = item.label;
    highlight.append(label);
    fragment.append(highlight);
    position = item.end;
  }
  fragment.append(characters.slice(position, end).join(''));
  return fragment;
}

export function renderAnnotations(target: HTMLElement, source: string, prediction: Prediction): void {
  const annotations: Annotation[] = prediction.fields.map(({ start, end, label }) => ({
    start, end, label: FIELD_LABELS.get(label) ?? label,
    tone: label === 'TITLE' || label === 'CONTAINER_TITLE' ? 'title' : 'detail',
  }));
  for (const { start, end, kind, roles, nameParts } of prediction.contributors) {
    annotations.push({
      start, end, tone: 'contributor',
      label: roles.length ? roles.map((role) => ROLE_LABELS.get(role) ?? role).join('・')
        : kind === 'organization' ? '団体' : '人物',
      parts: Array.from(nameParts, ([part, span]) => ({
        start: span.start, end: span.end, tone: 'name', label: NAME_LABELS.get(part) ?? part,
      })),
    });
  }
  const characters = Array.from(source);
  target.replaceChildren(annotatedText(characters, 0, characters.length, annotations));
}

function appendXmlRanges(source: HTMLElement, target: Element): void {
  source.childNodes.forEach((node) => {
    if (node.nodeType === Node.TEXT_NODE) {
      target.append(node.textContent ?? '');
      return;
    }
    if (!(node instanceof HTMLElement) || !node.classList.contains('annotation')) return;
    const label = node.lastElementChild?.textContent ?? '';
    const tag = /^[\p{L}_][\p{L}\p{N}_.-]*$/u.test(label) ? label : '範囲';
    const range = target.ownerDocument.createElement(tag);
    if (tag !== label) range.setAttribute('ラベル', label);
    appendXmlRanges(node, range);
    target.append(range);
  });
}

export function annotationClipboardText(source: HTMLElement): string {
  const xml = document.implementation.createDocument(null, '引用');
  appendXmlRanges(source, xml.documentElement);
  return new XMLSerializer().serializeToString(xml);
}