text-range.page.ts 19.5 KB
Newer Older
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
import {ApplicationState} from 'src/app/models/applicationState';
import {NavController, ToastController} from '@ionic/angular';
import {TextRange} from 'src/app/models/textRange';
import {Citation} from 'src/app/models/citation';
import {HttpErrorResponse} from '@angular/common/http';
import {Component} from '@angular/core';
import {CitationLevel} from 'src/app/models/enum';
import {TranslateService} from '@ngx-translate/core';
import {HelperService} from '../helper.service';
import {VocabularyService} from 'src/app/vocabulary.service';
import {ExerciseService} from 'src/app/exercise.service';
import {CorpusService} from 'src/app/corpus.service';

@Component({
    selector: 'app-text-range',
    templateUrl: './text-range.page.html',
    styleUrls: ['./text-range.page.scss'],
})
export class TextRangePage {
    public citationsUnavailableString: string;
    // TODO: rebuild the system so it works for any corpus of arbitrary citation depth
    public CitationLevel = CitationLevel;
    public invalidTextRangeString: string;
    ObjectKeys = Object.keys;
    public currentlyAvailableCitations: string[] = [];
    public currentInputId = 0;
    public citationValuesStart: number[];
    public citationValuesEnd: number[];
    public isTextRangeCheckRunning = false;
    HelperService = HelperService;

    constructor(public navCtrl: NavController,
                public corpusService: CorpusService,
                public toastCtrl: ToastController,
                public translateService: TranslateService,
                public exerciseService: ExerciseService,
                public vocService: VocabularyService) {
        this.currentlyAvailableCitations = [];
        this.corpusService.isTextRangeCorrect = false;
        this.corpusService.currentTextRange = new TextRange({start: ['', '', ''], end: ['', '', '']});
        if (Object.keys(this.corpusService.currentCorpus.citations).length === 0) {
            this.addReferences(this.corpusService.currentCorpus.citation_level_1).then(() => {
                this.initPage();
            }, () => {
            });
        } else {
            this.initPage();
        }
        this.translateService.get('INVALID_TEXT_RANGE').subscribe(value => this.invalidTextRangeString = value);
        this.translateService.get('ERROR_CITATIONS_UNAVAILABLE').subscribe(value => this.citationsUnavailableString = value);
    }

    private addMissingCitations(citationLabelsStart: string[], citationLabelsEnd: string[]) {
        return new Promise((resolve, reject) => {
            this.mapCitationLabelsToValues(citationLabelsStart[0], 0, citationLabelsStart, this.citationValuesStart).then(() => {
                this.mapCitationLabelsToValues(citationLabelsEnd[0], 0, citationLabelsEnd, this.citationValuesEnd).then(() => {
                    if (citationLabelsStart.length > 1) {
                        const cls1: string = citationLabelsStart[1];
                        this.mapCitationLabelsToValues(cls1, 1, citationLabelsStart, this.citationValuesStart).then(() => {
                            this.mapCitationLabelsToValues(citationLabelsEnd[1], 1, citationLabelsEnd, this.citationValuesEnd).then(() => {
                                if (citationLabelsStart.length > 2) {
                                    const cls2: string = citationLabelsStart[2];
                                    this.mapCitationLabelsToValues(cls2, 2, citationLabelsStart, this.citationValuesStart).then(() => {
                                        const cle2: string = citationLabelsEnd[2];
                                        this.mapCitationLabelsToValues(cle2, 2, citationLabelsEnd, this.citationValuesEnd).then(() => {
                                            resolve();
                                        });
                                    });
                                } else {
                                    resolve();
                                }
                            });
                        }, () => reject());
                    } else {
                        resolve();
                    }
                });
            }, () => reject());
        });
    }

    private addReferences(targetCitationLevel: string, relevantCitations: Citation[] = []) {
        if (relevantCitations.some(x => !x)) {
            return new Promise((resolve) => resolve());
        }
        const urnLastPart: string = relevantCitations.map(x => x.value.toString()).join('.');
        const fullUrn: string = this.corpusService.currentCorpus.source_urn + (urnLastPart ? ':' + urnLastPart : '');
        HelperService.currentError = null;
        HelperService.isLoading = true;
        return new Promise((resolve, reject) => {
            this.corpusService.getCTSvalidReff(fullUrn).subscribe((result: string[] | object) => {
                HelperService.isLoading = false;
                let newCitations: Citation[] = [];
                if (!Array.isArray(result)) {
                    // this is a custom corpus
                    const textparts: object[] = result['textparts'];
                    newCitations = textparts.map(x => x['citation']) as Citation[];
                } else {
                    // this is a CTS corpus
                    const urnList: string[] = result as string[];
                    const replaceString: string = fullUrn + (urnLastPart ? '.' : ':');
                    urnList.forEach((urn) => {
                        newCitations.push(new Citation({
                            level: targetCitationLevel,
                            label: urn.replace(replaceString, ''),
                            value: +urn.replace(replaceString, '')
                        }));
                    });
                }
                newCitations.forEach((citation) => {
                    citation.subcitations = {};
                    if (relevantCitations.length === 0) {
                        this.corpusService.currentCorpus.citations[citation.label] = citation;
                        this.currentlyAvailableCitations.push(citation.label);
                    } else if (relevantCitations.length === 1) {
                        this.corpusService.currentCorpus.citations[relevantCitations[0].label].subcitations[citation.label] = citation;
                        const firstLabel: string = this.corpusService.currentCorpus.citations[relevantCitations[0].label].label;
                        this.currentlyAvailableCitations.push(firstLabel.concat('.', citation.label));
                    } else if (relevantCitations.length === 2) {
                        const rc0Label: string = relevantCitations[0].label;
                        const rc1Label: string = relevantCitations[1].label;
                        this.corpusService.currentCorpus.citations[rc0Label].subcitations[rc1Label].subcitations[citation.label] = citation;
                        const firstLabel: string = this.corpusService.currentCorpus.citations[rc0Label].label;
                        const secondLabel: string = this.corpusService.currentCorpus.citations[rc0Label].subcitations[rc1Label].label;
                        this.currentlyAvailableCitations.push(firstLabel.concat('.', secondLabel, '.', citation.label));
                    }
                    resolve();
                });
            }, async (error: HttpErrorResponse) => {
                HelperService.isLoading = false;
                HelperService.currentError = error;
                const toast = await this.toastCtrl.create({
                    message: this.citationsUnavailableString,
                    duration: 3000,
                    position: 'top'
                });
                toast.present().then();
                reject();
            });
        });
    }

    applyAutoComplete(isStart: boolean) {
        this.showFurtherReferences(isStart).then(() => {
            const newId: string = 'input' + (this.currentInputId + 1).toString();
            this.currentInputId = 0;
            const newEl: HTMLInputElement = <HTMLInputElement>document.getElementById(newId);
            if (newEl) {
                // adjust disabled state manually because the focus won't work otherwise and the automatic check comes too late
                newEl.disabled = false;
                newEl.focus();
            }
        });
    }

    checkTextRange(citationLabelsStart: string[], citationLabelsEnd: string[]) {
        return new Promise(resolve => {
158
159
            citationLabelsStart = citationLabelsStart.filter(x => x);
            citationLabelsEnd = citationLabelsEnd.filter(x => x);
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
            if (this.corpusService.currentCorpus.citation_level_2 === CitationLevel[CitationLevel.default]) {
                if (citationLabelsStart.length !== 1 || citationLabelsEnd.length !== 1) {
                    resolve(false);
                    return;
                }
            } else {
                if (citationLabelsStart.length < 2 || citationLabelsEnd.length < 2) {
                    resolve(false);
                    return;
                } else {
                    if (this.corpusService.currentCorpus.citation_level_3 === CitationLevel[CitationLevel.default]) {
                        if (citationLabelsStart.length !== 2 || citationLabelsEnd.length !== 2) {
                            resolve(false);
                            return;
                        }
                    } else if (citationLabelsStart.length !== 3 || citationLabelsEnd.length !== 3) {
                        resolve(false);
                        return;
                    }
                }
            }
            this.citationValuesEnd = [];
            this.citationValuesStart = [];
            this.addMissingCitations(citationLabelsStart, citationLabelsEnd).then(() => {
                const citationValuesStart: number[] = this.citationValuesStart;
                const citationValuesEnd: number[] = this.citationValuesEnd;

                if (citationValuesStart[0] < citationValuesEnd[0]) {
                    resolve(true);
                } else if (citationValuesStart[0] === citationValuesEnd[0]) {
                    if (citationValuesStart.length > 1) {
                        if (citationValuesStart[1] < citationValuesEnd[1]) {
                            resolve(true);
                        } else if (this.citationValuesStart[1] === citationValuesEnd[1]) {
                            if (citationValuesStart.length > 2) {
                                resolve(citationValuesStart[2] <= citationValuesEnd[2]);
                            } else {
                                resolve(true);
                            }
                        } else {
                            resolve(false);
                        }
                    } else {
                        resolve(true);
                    }
                } else {
                    resolve(false);
                }
            }, () => {
                // if the citation system does not work, we allow the user to choose the correct citations on his own
                resolve(true);
            });
        });
    }

    private initPage() {
        if (this.corpusService.currentCorpus.citation_level_2 === CitationLevel[CitationLevel.default]) {
            const firstKey: string = Object.keys(this.corpusService.currentCorpus.citations)[0];
            const randomLabel: string = this.corpusService.currentCorpus.citations[firstKey].label;
            this.corpusService.currentTextRange.start[0] = this.corpusService.currentTextRange.end[0] = randomLabel;
        }
    }

    isInputDisabled(isStart: boolean) {
        const baseCits: { [label: string]: Citation } = this.corpusService.currentCorpus.citations;
        const ctrPart: string[] = isStart ? this.corpusService.currentTextRange.start : this.corpusService.currentTextRange.end;
        if (!baseCits.hasOwnProperty(ctrPart[0])) {
            return true;
        }
        return !baseCits[ctrPart[0]].subcitations.hasOwnProperty(ctrPart[1]);
    }

    public mapCitationLabelsToValues(label: string, index: number, citationLabels: string[], valueList: number[]) {
        return new Promise((resolve, reject) => {
            if (index === 0 && this.corpusService.currentCorpus.citations[label]) {
                valueList.push(this.corpusService.currentCorpus.citations[label].value);
                resolve();
            } else if (index === 1) {
                if (!this.corpusService.currentCorpus.citations[citationLabels[index - 1]]) {
                    if (!!+label) {
                        valueList.push(+label);
                        resolve();
                    } else {
                        reject();
                    }
                }
                if (Object.keys(this.corpusService.currentCorpus.citations[citationLabels[index - 1]].subcitations).length === 0) {
                    const relevantCitations: Citation[] = [this.corpusService.currentCorpus.citations[citationLabels[index - 1]]];
                    this.addReferences(this.corpusService.currentCorpus.citation_level_2, relevantCitations).then(() => {
                        valueList.push(this.corpusService.currentCorpus.citations[citationLabels[index - 1]].subcitations[label].value);
                        resolve();
                    }, () => reject());
                } else {
                    valueList.push(this.corpusService.currentCorpus.citations[citationLabels[index - 1]].subcitations[label].value);
                    resolve();
                }
            } else if (index === 2) {
                if (!this.corpusService.currentCorpus.citations[citationLabels[index - 2]] ||
                    !this.corpusService.currentCorpus.citations[citationLabels[index - 2]].subcitations[citationLabels[index - 1]]) {
                    if (!!+label) {
                        valueList.push(+label);
                        resolve();
                    } else {
                        reject();
                    }
                }
                const citation: Citation = this.corpusService.currentCorpus.citations[citationLabels[index - 2]];
                const subCitation: Citation = citation.subcitations[citationLabels[index - 1]];
                if (Object.keys(subCitation.subcitations).length === 0) {
                    this.addReferences(this.corpusService.currentCorpus.citation_level_3, [citation, subCitation]).then(() => {
                        valueList.push(subCitation.subcitations[label].value);
                        resolve();
                    }, () => reject());
                } else {
                    valueList.push(subCitation.subcitations[label].value);
                    resolve();
                }
            } else if (!!+label) {
                valueList.push(+label);
                resolve();
            }
        });
    }

    resetCitations() {
        switch (this.currentInputId) {
            case 1:
                if (this.corpusService.currentCorpus.citation_level_2 !== CitationLevel[CitationLevel.default]) {
                    this.corpusService.currentTextRange.start[1] = '';
                    this.corpusService.currentTextRange.start[2] = '';
                }
                break;
            case 2:
                if (this.corpusService.currentCorpus.citation_level_3 !== CitationLevel[CitationLevel.default]) {
                    this.corpusService.currentTextRange.start[2] = '';
                }
                break;
            case 4:
                if (this.corpusService.currentCorpus.citation_level_2 !== CitationLevel[CitationLevel.default]) {
                    this.corpusService.currentTextRange.end[1] = '';
                    this.corpusService.currentTextRange.end[2] = '';
                }
                break;
            case 5:
                if (this.corpusService.currentCorpus.citation_level_3 !== CitationLevel[CitationLevel.default]) {
                    this.corpusService.currentTextRange.end[2] = '';
                }
                break;
            default:
                break;
        }
    }

    resetCurrentInputId() {
        const oldId: number = this.currentInputId;
        // dirty hack to prevent the blur event from triggering before the click event
        setTimeout(() => {
            if (oldId === this.currentInputId) {
                this.currentInputId = 0;
            }
        }, 50);
    }

    async showFurtherReferences(isStart: boolean) {
        const relTextRangePart: string[] = isStart ? this.corpusService.currentTextRange.start : this.corpusService.currentTextRange.end;
        if (!relTextRangePart[0]) {
            return;
        }
        this.resetCitations();
        return new Promise(resolve => {
            const baseCit: Citation = this.corpusService.currentCorpus.citations[relTextRangePart[0]];
            if (baseCit && Object.keys(baseCit.subcitations).length) {
                resolve();
            } else {
                this.addReferences(this.corpusService.currentCorpus.citation_level_2, [baseCit]).then(() => {
                    resolve();
                });
            }
        }).then(() => {
            if ([2, 3, 5, 6].includes(this.currentInputId)) {
                const baseCit: Citation = this.corpusService.currentCorpus.citations[relTextRangePart[0]];
                const relCit: Citation = baseCit.subcitations[relTextRangePart[1]];
342
343
                const hasLvl3: boolean = this.corpusService.currentCorpus.citation_level_3 != CitationLevel[CitationLevel.default];
                if (relTextRangePart[1] && !(relCit && Object.keys(relCit.subcitations).length) && hasLvl3) {
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
                    this.addReferences(this.corpusService.currentCorpus.citation_level_3, [baseCit, relCit]).then();
                }
            }
        });
    }

    showText() {
        if (this.isTextRangeCheckRunning) {
            return;
        }
        const citationLabelsStart: string[] = this.corpusService.currentTextRange.start;
        const citationLabelsEnd: string[] = this.corpusService.currentTextRange.end;
        this.isTextRangeCheckRunning = true;
        this.checkTextRange(citationLabelsStart, citationLabelsEnd).then(async (isTextRangeCorrect: boolean) => {
            this.isTextRangeCheckRunning = false;
            if (!isTextRangeCorrect) {
                const toast = await this.toastCtrl.create({
                    message: this.invalidTextRangeString,
                    duration: 3000,
                    position: 'top'
                });
                toast.present().then();
                return;
            }
            const newUrnBase: string = this.corpusService.currentCorpus.source_urn + ':';
            const workReference: string = this.citationValuesStart.join('.') + '-' + this.citationValuesEnd.join('.');
370
            this.corpusService.currentUrn = newUrnBase + workReference;
371
            HelperService.mostRecentSetup = new ApplicationState({
372
                currentUrn: this.corpusService.currentUrn,
373
374
375
376
377
378
379
                currentCorpus: this.corpusService.currentCorpus,
                workReference: workReference,
                currentTextRange: this.corpusService.currentTextRange
            });
            const lskmrs: string = HelperService.config['localStorageKeyMostRecentSetup'];
            window.localStorage.setItem(lskmrs, JSON.stringify(HelperService.mostRecentSetup));
            this.corpusService.isTextRangeCorrect = true;
380
            this.corpusService.getText().then(() => {
381
382
383
384
385
386
387
388
389
390
                if (HelperService.isVocabularyCheck) {
                    this.navCtrl.navigateForward('/vocabulary-check').then();
                } else {
                    this.navCtrl.navigateForward('show-text').then();
                }
            }, () => {
            });
        });
    }
}