File size: 8,499 Bytes
29b6f8a
 
 
 
b68a02b
29b6f8a
 
 
b68a02b
29b6f8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b68a02b
29b6f8a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b68a02b
 
 
29b6f8a
 
 
 
 
 
 
 
 
 
 
b68a02b
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
import { annotationClipboardText, renderAnnotations } from './annotation';
import { makeBiblatex, TYPE_LABELS } from './biblatex';
import { CITATION_EXAMPLES } from './examples';
import { LiteModel, type Prediction } from './lite';
import { WorkerModel } from './standard';

declare const __BIBFORM_STANDARD__: boolean;
declare const __BIBFORM_STANDARD_V2__: boolean;
declare const __BIBFORM_WORKER_V2__: boolean;

const form = document.querySelector('form');
const source = document.querySelector('#source');
const exampleSelect = document.querySelector('#example');
const modelSelect = document.querySelector('#model');
const modelControl = document.querySelector('#model-control');
const typeSelect = document.querySelector('#type');
const output = document.querySelector('#output');
const status = document.querySelector('#status');
const choices = document.querySelector('#choices');
const download = document.querySelector('#download');
const submit = document.querySelector('#submit');
const candidates = document.querySelector('#candidates');
const annotationResult = document.querySelector('#annotation-result');
const annotatedSource = document.querySelector('#annotated-source');
const copyAnnotation = document.querySelector('#copy-annotation');
const copyStatus = document.querySelector('#copy-status');
const copyFallback = document.querySelector('#copy-fallback');
const copyText = document.querySelector('#copy-text');
if (!(form instanceof HTMLFormElement) || !(source instanceof HTMLTextAreaElement) ||
    !(exampleSelect instanceof HTMLSelectElement) ||
    !(modelSelect instanceof HTMLSelectElement) || !(modelControl instanceof HTMLElement) ||
    !(typeSelect instanceof HTMLSelectElement) || !(output instanceof HTMLTextAreaElement) ||
    !(status instanceof HTMLElement) || !(choices instanceof HTMLElement) ||
    !(download instanceof HTMLButtonElement) || !(submit instanceof HTMLButtonElement) ||
    !(candidates instanceof HTMLElement) || !(annotationResult instanceof HTMLElement) ||
    !(annotatedSource instanceof HTMLElement) || !(copyAnnotation instanceof HTMLButtonElement) ||
    !(copyStatus instanceof HTMLElement) || !(copyFallback instanceof HTMLElement) ||
    !(copyText instanceof HTMLTextAreaElement)) throw new Error('Bibform controls are missing');

type ModelName = 'lite' | 'standard';
const models = new Map<ModelName, Promise<LiteModel | WorkerModel>>();
let prediction: Prediction | undefined;
let original = '';
let predicting = false;
const threshold = .90;
const canRunStandard = __BIBFORM_STANDARD__ && (__BIBFORM_STANDARD_V2__ || 'Suspending' in WebAssembly);
modelControl.hidden = !__BIBFORM_STANDARD__;
modelSelect.value = canRunStandard ? 'standard' : 'lite';
if (!canRunStandard) {
  const standardOption = modelSelect.options[0];
  standardOption.disabled = true;
  standardOption.text = 'Bibform(このブラウザでは利用できません)';
}
for (const [type, label] of TYPE_LABELS) typeSelect.add(new Option(`${label} · @${type}`, type));
for (const [language, examples] of CITATION_EXAMPLES) {
  const group = document.createElement('optgroup');
  group.label = language;
  for (const [label, citation] of examples) group.append(new Option(label, citation));
  exampleSelect.append(group);
}
exampleSelect.disabled = false;

function refreshOutput(): void {
  if (!(typeSelect instanceof HTMLSelectElement) || !(output instanceof HTMLTextAreaElement) ||
      !(download instanceof HTMLButtonElement)) return;
  output.value = prediction && typeSelect.value ? makeBiblatex(original, prediction, typeSelect.value) : '';
  download.disabled = !output.value;
}

function chooseType(type: string): void {
  if (!(typeSelect instanceof HTMLSelectElement) || !(status instanceof HTMLElement)) return;
  typeSelect.value = type;
  status.textContent = type ? `資料種別に「${TYPE_LABELS.get(type)}」を選びました。`
    : '候補から資料種別を選んでください。';
  refreshOutput();
}

function renderCandidates(result: Prediction): void {
  if (!(candidates instanceof HTMLElement) || !(typeSelect instanceof HTMLSelectElement) ||
      !(status instanceof HTMLElement)) return;
  const first = result.candidates[0];
  const automatic = first.score >= threshold;
  typeSelect.value = automatic ? first.type : '';
  status.textContent = automatic
    ? `第1候補を選択しました(スコア ${(first.score * 100).toFixed(1)}%)。`
    : '候補から資料種別を選んでください。';
  candidates.replaceChildren();
  if (!automatic) {
    for (const item of result.candidates.slice(0, 3)) {
      const button = document.createElement('button');
      button.type = 'button';
      button.textContent = `${TYPE_LABELS.get(item.type) ?? item.type} ${(item.score * 100).toFixed(1)}%`;
      button.addEventListener('click', () => chooseType(item.type));
      candidates.append(button);
    }
  }
}

form.addEventListener('submit', async (event) => {
  event.preventDefault();
  if (predicting || !source.value.trim()) return;
  original = source.value;
  clearResult();
  submit.disabled = true;
  exampleSelect.disabled = true;
  modelSelect.disabled = true;
  source.readOnly = true;
  predicting = true;
  const selected = canRunStandard && modelSelect.value === 'standard' ? 'standard' : 'lite';
  status.textContent = models.has(selected) ? '解析中…'
    : selected === 'standard' ? '通常版モデルを読み込み中…' : '軽量版モデルを読み込み中…';
  try {
    let model = models.get(selected);
    if (!model) {
      model = selected === 'standard' || __BIBFORM_WORKER_V2__
        ? Promise.resolve(new WorkerModel(new URL('./standard-worker.js', document.baseURI),
          __BIBFORM_WORKER_V2__ ? selected : undefined))
        : LiteModel.load(new URL('./lite/', document.baseURI));
      models.set(selected, model);
    }
    prediction = await (await model).predict(original);
    renderCandidates(prediction);
    choices.hidden = false;
    refreshOutput();
    renderAnnotations(annotatedSource, original, prediction);
    annotationResult.hidden = false;
  } catch (reason) {
    console.error(reason);
    if (selected === 'lite' && !__BIBFORM_WORKER_V2__) models.delete(selected);
    status.textContent = '解析できませんでした。ページを再読み込みしてからお試しください。';
  } finally {
    predicting = false;
    source.readOnly = false;
    submit.disabled = false;
    exampleSelect.disabled = false;
    modelSelect.disabled = false;
  }
});

function clearResult(): void {
  if (!(choices instanceof HTMLElement) || !(status instanceof HTMLElement) ||
      !(annotationResult instanceof HTMLElement) || !(annotatedSource instanceof HTMLElement) ||
      !(copyStatus instanceof HTMLElement) || !(copyFallback instanceof HTMLElement) ||
      !(copyText instanceof HTMLTextAreaElement)) return;
  prediction = undefined;
  choices.hidden = true;
  annotationResult.hidden = true;
  annotatedSource.replaceChildren();
  copyStatus.textContent = '';
  copyFallback.hidden = true;
  copyText.value = '';
  status.textContent = '';
  refreshOutput();
}

source.addEventListener('input', () => {
  exampleSelect.selectedIndex = 0;
  clearResult();
});
modelSelect.addEventListener('change', clearResult);
exampleSelect.addEventListener('change', () => {
  if (!exampleSelect.value) return;
  source.value = exampleSelect.value;
  clearResult();
});
typeSelect.addEventListener('change', () => chooseType(typeSelect.value));
copyAnnotation.addEventListener('click', async () => {
  const copiedPrediction = prediction;
  if (!copiedPrediction) return;
  const text = annotationClipboardText(annotatedSource);
  try {
    await navigator.clipboard.writeText(text);
    if (prediction !== copiedPrediction) return;
    copyStatus.textContent = 'コピーしました。';
    copyFallback.hidden = true;
  } catch {
    if (prediction !== copiedPrediction) return;
    copyStatus.textContent = '下のテキストをコピーしてください。';
    copyText.value = text;
    copyFallback.hidden = false;
    copyText.focus();
    copyText.select();
  }
});
download.addEventListener('click', () => {
  if (!output.value) return;
  const url = URL.createObjectURL(new Blob([output.value], { type: 'application/x-bibtex' }));
  const anchor = document.createElement('a');
  anchor.href = url;
  anchor.download = 'reference.bib';
  anchor.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
});