@taekwondo-db/database 0.0.0-stage → 0.2.2

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 (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +282 -2
  3. package/db/chagi.json +720 -0
  4. package/db/chigi.json +1153 -0
  5. package/db/ditgi.json +101 -0
  6. package/db/japgi.json +154 -0
  7. package/db/jireugi.json +458 -0
  8. package/db/jjireugi.json +111 -0
  9. package/db/kkeokgi.json +58 -0
  10. package/db/makgi.json +1447 -0
  11. package/db/milgi.json +63 -0
  12. package/db/neomgigi.json +45 -0
  13. package/db/pihagi.json +68 -0
  14. package/db/ppaegi.json +174 -0
  15. package/db/schemas/grades.json +22 -0
  16. package/db/schemas/historic.json +21 -0
  17. package/db/schemas/image.json +24 -0
  18. package/db/schemas/include.json +31 -0
  19. package/db/schemas/localized-string.json +17 -0
  20. package/db/schemas/patches.json +12 -0
  21. package/db/schemas/source.json +12 -0
  22. package/db/schemas/sources.json +22 -0
  23. package/db/schemas/techniques.json +86 -0
  24. package/db/schemas/terms.json +52 -0
  25. package/db/seogi.json +602 -0
  26. package/db/sources.json +29 -0
  27. package/db/terms.json +995 -0
  28. package/db/ttwigi.json +59 -0
  29. package/dist/search.browser.js +1197 -0
  30. package/index.js +1 -0
  31. package/package.json +50 -5
  32. package/src/builtins-empty.d.ts +1 -0
  33. package/src/builtins-empty.js +10 -0
  34. package/src/builtins.d.ts +10 -0
  35. package/src/builtins.js +46 -0
  36. package/src/compose-builtins.d.ts +11 -0
  37. package/src/compose-builtins.js +39 -0
  38. package/src/compose.d.ts +76 -0
  39. package/src/compose.js +313 -0
  40. package/src/database.ts +457 -0
  41. package/src/description.d.ts +13 -0
  42. package/src/description.js +63 -0
  43. package/src/grade.d.ts +22 -0
  44. package/src/grade.js +44 -0
  45. package/src/search.d.ts +31 -0
  46. package/src/search.js +59 -0
  47. package/types/historic.d.ts +13 -0
  48. package/types/image.d.ts +9 -0
  49. package/types/localized-string.d.ts +3 -0
  50. package/types/source.d.ts +34 -0
  51. package/types/technique.d.ts +114 -0
  52. package/types/term.d.ts +38 -0
@@ -0,0 +1,457 @@
1
+ import {
2
+ builtinSources,
3
+ builtinTechniqueGroups,
4
+ builtinTerms,
5
+ } from "@taekwondo-db/database/builtins";
6
+ import type { Historic, HistoricJson } from "../types/historic";
7
+ import type { Source, SourceJson, Sources, SourcesJson } from "../types/source";
8
+ import type {
9
+ Ref,
10
+ Technique,
11
+ TechniqueGroup,
12
+ TechniqueJson,
13
+ TechniqueReference,
14
+ TechniqueReferenceJson,
15
+ } from "../types/technique.d.ts";
16
+ import type { Term, TermJson, TermType } from "../types/term.d.ts";
17
+ import type { ComposeOptions } from "./compose.js";
18
+ import { composeDatabase, NO_BUILTINS } from "./compose.js";
19
+ import { parseDescription } from "./description.js";
20
+ import type { Grade } from "./grade.js";
21
+ import { parseGrade } from "./grade.js";
22
+ import { createTechniqueSearch, createTermSearch } from "./search.js";
23
+
24
+ export type { ComposeOptions, Include, TechniqueGroupJson } from "./compose.js";
25
+ export { applyPatch } from "./compose.js";
26
+ export type { DescriptionSegmentJson, RefKind } from "./description.js";
27
+ export {
28
+ inferRefKind,
29
+ parseDescription,
30
+ REF_PATTERN,
31
+ stripRefs,
32
+ } from "./description.js";
33
+ export type { Grade, GradeKind, GradesJson } from "./grade.js";
34
+ export { compareGrades, parseGrade } from "./grade.js";
35
+ export type {
36
+ Search,
37
+ TechniqueSearchItem,
38
+ TermSearchItem,
39
+ } from "./search.js";
40
+ export { createTechniqueSearch, createTermSearch } from "./search.js";
41
+ export type { SourcesJson };
42
+ export { builtinTechniqueGroups };
43
+
44
+ /**
45
+ * Options for {@link TaekwondoDatabase}.
46
+ *
47
+ * Set `includeBuiltins: false` to build a database that contains none of the
48
+ * bundled Kukkiwon data — the consumer then supplies its own `terms`,
49
+ * `sources` and `techniqueGroups`. Set `include` to load only some of the
50
+ * bundled techniques.
51
+ */
52
+ export interface DatabaseOptions extends ComposeOptions {
53
+ /** Load the bundled Kukkiwon terms, sources and technique groups. Default `true`. */
54
+ includeBuiltins?: boolean;
55
+ }
56
+
57
+ /**
58
+ * A segment of a description with its references resolved. A reference whose
59
+ * target is not loaded (e.g. excluded via `include`) becomes plain text.
60
+ */
61
+ export type DescriptionSegment =
62
+ | { type: "text"; text: string }
63
+ | { type: "technique"; technique: Technique; label: string }
64
+ | { type: "term"; term: Term; label: string };
65
+
66
+ export class TaekwondoDatabase {
67
+ private techniques = new Map<string, Technique>();
68
+ private terms = new Map<string, Term>();
69
+ private sources = new Map<string, Sources>();
70
+ private json: Record<string, TechniqueJson | string> = {};
71
+ private allTermJson: Record<string, TermJson | string> = {};
72
+ private groups: TechniqueGroup[] = [];
73
+ private grades: Grade[] = [];
74
+ private gradeTechniques = new Map<string, Technique[]>();
75
+
76
+ constructor(options: DatabaseOptions = {}) {
77
+ const includeBuiltins = options.includeBuiltins ?? true;
78
+
79
+ // Selection, patches and own data are resolved on the JSON first —
80
+ // see compose.js, which apps also run at build time.
81
+ const composed = composeDatabase(
82
+ options,
83
+ includeBuiltins
84
+ ? {
85
+ sources: builtinSources,
86
+ techniqueGroups: builtinTechniqueGroups,
87
+ terms: builtinTerms,
88
+ }
89
+ : NO_BUILTINS,
90
+ );
91
+
92
+ // 1. sources — techniques cannot be built without them.
93
+ this.jsonToSources(composed.sources);
94
+
95
+ // 2. terms.
96
+ this.addTermJson(composed.terms);
97
+
98
+ // 3. technique groups.
99
+ for (const [group, json] of Object.entries(composed.techniqueGroups)) {
100
+ this.groups.push(group as TechniqueGroup);
101
+ this.json = { ...this.json, ...json };
102
+ this.loadTechniques(json, group as TechniqueGroup);
103
+ }
104
+
105
+ this.json = { ...this.json, ...composed.customTechniques };
106
+ this.loadTechniques(composed.customTechniques);
107
+
108
+ this.addReferences();
109
+ this.assignGrades(composed.grades);
110
+ }
111
+
112
+ /**
113
+ * Splits a description text into plain text and resolved `#[...]` references,
114
+ * e.g. `db.resolveDescription(technique.description.de)`.
115
+ */
116
+ public resolveDescription(text: string): DescriptionSegment[] {
117
+ const segments: DescriptionSegment[] = [];
118
+ const pushText = (value: string) => {
119
+ const previous = segments[segments.length - 1];
120
+ if (previous?.type === "text") {
121
+ previous.text += value;
122
+ } else {
123
+ segments.push({ text: value, type: "text" });
124
+ }
125
+ };
126
+
127
+ for (const segment of parseDescription(text)) {
128
+ if (segment.type === "text") {
129
+ pushText(segment.text);
130
+ continue;
131
+ }
132
+ if (segment.kind === "technique") {
133
+ const technique = this.techniques.get(segment.key);
134
+ if (technique) {
135
+ segments.push({ label: segment.label, technique, type: "technique" });
136
+ continue;
137
+ }
138
+ } else {
139
+ const term = this.terms.get(segment.key);
140
+ if (term) {
141
+ segments.push({ label: segment.label, term, type: "term" });
142
+ continue;
143
+ }
144
+ }
145
+ pushText(segment.label);
146
+ }
147
+ return segments;
148
+ }
149
+
150
+ public getTerm(key: string): Term | undefined {
151
+ return this.terms.get(key.toLowerCase());
152
+ }
153
+
154
+ public getTechnique(key: string): Technique | undefined {
155
+ return this.techniques.get(key);
156
+ }
157
+
158
+ public getSource(key: string): Sources | undefined {
159
+ return this.sources.get(key);
160
+ }
161
+
162
+ public getAllTerms(): MapIterator<[string, Term]> {
163
+ return this.terms.entries();
164
+ }
165
+
166
+ public getAllTechniques(): MapIterator<[string, Technique]> {
167
+ return this.techniques.entries();
168
+ }
169
+
170
+ public getAllSources(): MapIterator<[string, Sources]> {
171
+ return this.sources.entries();
172
+ }
173
+
174
+ public getGroups(): TechniqueGroup[] {
175
+ return [...this.groups];
176
+ }
177
+
178
+ public getTechniquesByGroup(group: TechniqueGroup): Technique[] {
179
+ return Array.from(this.techniques.values()).filter(
180
+ (t) => t.group === group,
181
+ );
182
+ }
183
+
184
+ /** The grades given via `options.grades`, lowest first. */
185
+ public getGrades(): Grade[] {
186
+ return [...this.grades];
187
+ }
188
+
189
+ /** The techniques that become relevant at this grade, in the given order. */
190
+ public getTechniquesByGrade(key: string): Technique[] {
191
+ return [...(this.gradeTechniques.get(key) ?? [])];
192
+ }
193
+
194
+ public searchTechniques(input: string, lang: string): Technique[] {
195
+ return createTechniqueSearch([...this.techniques.values()], lang)(input);
196
+ }
197
+
198
+ public searchTerms(input: string, lang: string): Term[] {
199
+ return createTermSearch([...this.terms.values()], lang)(input);
200
+ }
201
+
202
+ private loadTechniques(
203
+ json: Record<string, TechniqueJson | string>,
204
+ defaultGroup?: TechniqueGroup,
205
+ ) {
206
+ for (const [key, entry] of Object.entries(json)) {
207
+ if (typeof entry === "string") {
208
+ continue;
209
+ }
210
+
211
+ const group = entry.group ?? defaultGroup;
212
+ if (!group) {
213
+ throw new Error(`Technique "${key}" has no group`);
214
+ }
215
+
216
+ this.techniques.set(key, this.buildTechnique(key, entry, group));
217
+ }
218
+ }
219
+
220
+ /** Composition has validated the grades already. */
221
+ private assignGrades(grades: Record<string, string[]>) {
222
+ for (const [key, names] of Object.entries(grades)) {
223
+ const grade = parseGrade(key) as Grade;
224
+ const techniques = names.map(
225
+ (name) => this.techniques.get(name) as Technique,
226
+ );
227
+ for (const technique of techniques) technique.grade = grade;
228
+ this.grades.push(grade);
229
+ this.gradeTechniques.set(key, techniques);
230
+ }
231
+ }
232
+
233
+ private addTermJson(json: Record<string, TermJson | string>) {
234
+ this.allTermJson = { ...this.allTermJson, ...json };
235
+ this.loadTerms(json);
236
+ }
237
+
238
+ private loadTerms(json: Record<string, TermJson | string>) {
239
+ for (const [key, entry] of Object.entries(json)) {
240
+ if (typeof entry === "string") {
241
+ continue;
242
+ }
243
+
244
+ this.terms.set(key, this.buildTerm(key, entry));
245
+ }
246
+ }
247
+
248
+ private jsonToSources(json: SourcesJson) {
249
+ const keys = Object.keys(json) as Array<keyof typeof json>;
250
+ for (const key of keys) {
251
+ if (typeof json[key] === "string") {
252
+ continue;
253
+ }
254
+ const entry = json[key] as Sources;
255
+ this.sources.set(key, { ...entry, name: key });
256
+ }
257
+ }
258
+
259
+ private buildTechnique(
260
+ key: string,
261
+ entry: TechniqueJson,
262
+ group: TechniqueGroup,
263
+ ): Technique {
264
+ const technique: Technique = {
265
+ group,
266
+ name: key,
267
+ supplementaryName: entry.supplementaryName,
268
+ translation: entry.translation,
269
+ weight: entry.weight,
270
+ ...(entry.description && { description: entry.description }),
271
+ ...(entry.images && { images: entry.images }),
272
+ ...(entry.videos && { videos: entry.videos }),
273
+ ...(entry.generic && { generic: entry.generic }),
274
+ };
275
+
276
+ if (entry.terms) {
277
+ technique.terms = this.derefMultipleTerms(technique, entry.terms);
278
+ }
279
+
280
+ if (entry.sources) {
281
+ technique.sources = this.buildMultipleSources(entry.sources);
282
+ for (const source of technique.sources) {
283
+ if (source.type.techniques === undefined) {
284
+ source.type.techniques = [];
285
+ }
286
+
287
+ source.type.techniques.push(technique);
288
+ }
289
+ }
290
+
291
+ if (entry.historic) {
292
+ technique.historic = this.buildMultipleHistoric(entry.historic);
293
+ }
294
+
295
+ return technique;
296
+ }
297
+
298
+ private buildTerm(key: string, entry: TermJson): Term {
299
+ const term: Term = {
300
+ description: entry.description,
301
+ hangeul: entry.hangeul,
302
+ hanja: entry.hanja,
303
+ name: key,
304
+ type: entry.type as TermType | undefined,
305
+ };
306
+
307
+ if (entry.historic) {
308
+ term.historic = this.buildMultipleHistoric(entry.historic);
309
+ }
310
+
311
+ return term;
312
+ }
313
+
314
+ private buildMultipleHistoric(historicJson: HistoricJson[]): Historic[] {
315
+ const historic = [];
316
+ for (const historicEntry of historicJson) {
317
+ const newHistoricEntry = {
318
+ hangeul: historicEntry.hangeul,
319
+ hanja: historicEntry.hanja,
320
+ name: historicEntry.name,
321
+ rr: historicEntry.rr,
322
+ sources: this.buildMultipleSources(historicEntry.sources),
323
+ };
324
+ for (const source of newHistoricEntry.sources) {
325
+ if (source.type.historic === undefined) {
326
+ source.type.historic = [];
327
+ }
328
+
329
+ source.type.historic.push(newHistoricEntry);
330
+ }
331
+ historic.push(newHistoricEntry);
332
+ }
333
+ return historic;
334
+ }
335
+
336
+ private buildMultipleSources(sourceJson: SourceJson[]): Source[] {
337
+ const sources = [];
338
+ for (const sourceEntry of sourceJson) {
339
+ const type = this.deref(this.sources, sourceEntry);
340
+ if (!type) {
341
+ throw new Error(`Could not found source: ${sourceEntry.$ref}`);
342
+ }
343
+ sources.push({
344
+ page: sourceEntry.page,
345
+ type,
346
+ });
347
+ }
348
+
349
+ return sources;
350
+ }
351
+
352
+ private addReferences() {
353
+ for (const [key, technique] of this.techniques) {
354
+ this.addTechniqueReferences(key, technique);
355
+ }
356
+
357
+ for (const [key, term] of this.terms) {
358
+ this.addTermReferences(key, term);
359
+ }
360
+ }
361
+
362
+ private addTermReferences(key: string, term: Term) {
363
+ const entry = (this.allTermJson as any)[key] as TermJson;
364
+ if (entry.lemma) {
365
+ term.lemma = this.deref(this.terms, entry.lemma);
366
+ if (!term.lemma) {
367
+ throw new Error(`Could not find term reference: ${entry.lemma.$ref}`);
368
+ }
369
+ if (!term.lemma.forms) {
370
+ term.lemma.forms = [];
371
+ }
372
+ term.lemma.forms.push(term);
373
+ }
374
+
375
+ if (entry.terms) {
376
+ for (const row of entry.terms) {
377
+ const referenced = this.deref(this.terms, row);
378
+
379
+ if (!referenced) {
380
+ throw new Error(`Could not find term reference: ${row.$ref}`);
381
+ }
382
+
383
+ if (!referenced.combinations) {
384
+ referenced.combinations = [];
385
+ }
386
+
387
+ referenced.combinations.push(term);
388
+ if (!term.terms) {
389
+ term.terms = [];
390
+ }
391
+ term.terms.push(referenced);
392
+ }
393
+ }
394
+ }
395
+
396
+ private addTechniqueReferences(key: string, technique: Technique) {
397
+ const entry = (this.json as any)[key] as TechniqueJson;
398
+
399
+ if (entry.references) {
400
+ technique.references = this.derefTechniqueReferences(
401
+ technique,
402
+ entry.references,
403
+ );
404
+ }
405
+ }
406
+
407
+ private deref<T>(map: Map<string, T>, ref: Ref): T | undefined {
408
+ const key = ref.$ref.split("#/")[1];
409
+ return map.get(key);
410
+ }
411
+
412
+ private derefMultipleTerms(technique: Technique, refs: Ref[]): Term[] {
413
+ const terms = [];
414
+ for (const ref of refs) {
415
+ const result = this.deref(this.terms, ref);
416
+ if (result === undefined) {
417
+ throw new Error(`Could not find term reference: ${ref.$ref}`);
418
+ }
419
+ if (result.techniques === undefined) {
420
+ result.techniques = [];
421
+ }
422
+ result.techniques.push(technique);
423
+ terms.push(result);
424
+ }
425
+ return terms;
426
+ }
427
+
428
+ private derefTechniqueReferences(
429
+ referencingTechnique: Technique,
430
+ references: TechniqueReferenceJson[],
431
+ ): TechniqueReference[] {
432
+ const dereferenced = [];
433
+ for (const ref of references) {
434
+ const technique = this.deref(this.techniques, ref);
435
+ if (technique === undefined) {
436
+ throw new Error(`Could not find technique reference: ${ref.$ref}`);
437
+ }
438
+ const result: TechniqueReference = {
439
+ description: ref.description,
440
+ technique,
441
+ type: ref.type,
442
+ };
443
+ dereferenced.push(result);
444
+
445
+ if (ref.type === "generic") {
446
+ if (technique.references === undefined) {
447
+ technique.references = [];
448
+ }
449
+ technique.references?.push({
450
+ technique: referencingTechnique,
451
+ type: "specialization",
452
+ });
453
+ }
454
+ }
455
+ return dereferenced;
456
+ }
457
+ }
@@ -0,0 +1,13 @@
1
+ export type RefKind = "technique" | "term";
2
+
3
+ /** A segment of a parsed description, before the references are resolved. */
4
+ export type DescriptionSegmentJson =
5
+ | { type: "text"; text: string }
6
+ | { type: "ref"; kind: RefKind; key: string; label: string };
7
+
8
+ export declare const REF_PATTERN: RegExp;
9
+ export declare function inferRefKind(key: string): RefKind;
10
+ export declare function parseDescription(
11
+ text: string,
12
+ ): DescriptionSegmentJson[];
13
+ export declare function stripRefs(text: string): string;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Inline references in description texts.
3
+ *
4
+ * Syntax: `#[Key]`, `#[Key|label]`, `#[technique:Key]`, `#[term:key]`.
5
+ *
6
+ * Without an explicit kind the casing of the key decides: technique names
7
+ * start with an upper-case letter ("Ieochagi"), term keys are lower-case
8
+ * ("palmok"). The label is the displayed text and defaults to the key.
9
+ */
10
+
11
+ /** Matches one reference; groups: kind, key, label. Global — reset `lastIndex` or use `matchAll`. */
12
+ export const REF_PATTERN =
13
+ /#\[(?:(technique|term):)?([^\]|]+?)(?:\|([^\]]+))?\]/g;
14
+
15
+ /**
16
+ * Determines whether a key without explicit kind refers to a technique or a term.
17
+ * @param {string} key
18
+ * @returns {"technique" | "term"}
19
+ */
20
+ export function inferRefKind(key) {
21
+ const first = key.charAt(0);
22
+ return first !== first.toLowerCase() ? "technique" : "term";
23
+ }
24
+
25
+ /**
26
+ * Splits a description into plain text and reference segments.
27
+ * @param {string} text
28
+ * @returns {import("./description").DescriptionSegmentJson[]}
29
+ */
30
+ export function parseDescription(text) {
31
+ const segments = [];
32
+ let last = 0;
33
+ for (const match of text.matchAll(REF_PATTERN)) {
34
+ if (match.index > last) {
35
+ segments.push({ text: text.slice(last, match.index), type: "text" });
36
+ }
37
+ const [, kind, rawKey, label] = match;
38
+ const key = rawKey.trim();
39
+ segments.push({
40
+ key,
41
+ kind: kind ?? inferRefKind(key),
42
+ label: label ?? key,
43
+ type: "ref",
44
+ });
45
+ last = match.index + match[0].length;
46
+ }
47
+ if (last < text.length) {
48
+ segments.push({ text: text.slice(last), type: "text" });
49
+ }
50
+ return segments;
51
+ }
52
+
53
+ /**
54
+ * Replaces every reference by its label, e.g. for plain-text output or search.
55
+ * @param {string} text
56
+ * @returns {string}
57
+ */
58
+ export function stripRefs(text) {
59
+ return text.replace(
60
+ REF_PATTERN,
61
+ (_, _kind, key, label) => label ?? key.trim(),
62
+ );
63
+ }
package/src/grade.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ export type GradeKind = "kup" | "poom" | "dan";
2
+
3
+ /** A Kup, Poom or Dan grade, e.g. `{ key: "9-kup", kind: "kup", level: 9 }`. */
4
+ export interface Grade {
5
+ key: string;
6
+ kind: GradeKind;
7
+ level: number;
8
+ }
9
+
10
+ /**
11
+ * From which grade on a technique is relevant, keyed by grade
12
+ * (`"10-kup"` … `"1-kup"`, `"1-poom"` … `"4-poom"`, `"1-dan"` … `"9-dan"`).
13
+ * Each technique is listed at most once, at the first grade it belongs to.
14
+ */
15
+ export interface GradesJson {
16
+ [grade: string]: string[] | string;
17
+ }
18
+
19
+ export declare function parseGrade(key: string): Grade | undefined;
20
+
21
+ /** Sort comparator: lower grades first; a Poom before the Dan of its level. */
22
+ export declare function compareGrades(a: Grade, b: Grade): number;
package/src/grade.js ADDED
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Grades (Kup, Poom, Dan) — plain JavaScript, so that compose.js can use it
3
+ * in Node as well.
4
+ */
5
+
6
+ const GRADE_PATTERN = /^(\d+)-(kup|poom|dan)$/;
7
+ const MAX_LEVEL = { dan: 9, kup: 10, poom: 4 };
8
+
9
+ /**
10
+ * `"9-kup"` → `{ key: "9-kup", kind: "kup", level: 9 }`.
11
+ *
12
+ * @param {string} key
13
+ * @returns {import("./grade").Grade | undefined} `undefined` for anything that
14
+ * is not a grade
15
+ */
16
+ export function parseGrade(key) {
17
+ const match = GRADE_PATTERN.exec(key);
18
+ if (!match) return undefined;
19
+ const level = Number(match[1]);
20
+ const kind = /** @type {import("./grade").GradeKind} */ (match[2]);
21
+ if (level < 1 || level > MAX_LEVEL[kind]) return undefined;
22
+ return { key, kind, level };
23
+ }
24
+
25
+ /**
26
+ * Position on the way from beginner to master: 10th Kup first, then 1st Kup,
27
+ * then Poom and Dan by level — a Poom right before the Dan of the same level.
28
+ *
29
+ * @param {import("./grade").Grade} grade
30
+ */
31
+ function rank(grade) {
32
+ if (grade.kind === "kup") return -grade.level;
33
+ return grade.kind === "poom" ? grade.level - 0.5 : grade.level;
34
+ }
35
+
36
+ /**
37
+ * Sort comparator: lower grades first.
38
+ *
39
+ * @param {import("./grade").Grade} a
40
+ * @param {import("./grade").Grade} b
41
+ */
42
+ export function compareGrades(a, b) {
43
+ return rank(a) - rank(b);
44
+ }
@@ -0,0 +1,31 @@
1
+ import type { LocalizedString } from "../types/localized-string";
2
+
3
+ /** What the technique search matches on; loaded techniques qualify. */
4
+ export interface TechniqueSearchItem {
5
+ name: string;
6
+ supplementaryName?: string;
7
+ /** Localized, or already in the language searched. */
8
+ translation?: LocalizedString | string;
9
+ }
10
+
11
+ /** What the term search matches on; loaded terms qualify. */
12
+ export interface TermSearchItem {
13
+ name: string;
14
+ /** Localized, or already in the language searched; may contain references. */
15
+ description?: LocalizedString | string;
16
+ }
17
+
18
+ /** A search over fixed items: from a query to the matching items, best first. */
19
+ export type Search<T> = (query: string) => T[];
20
+
21
+ /** Searches techniques by name, `supplementaryName` and translation. */
22
+ export declare function createTechniqueSearch<T extends TechniqueSearchItem>(
23
+ items: readonly T[],
24
+ lang?: string,
25
+ ): Search<T>;
26
+
27
+ /** Searches terms by name and description, without reference markup. */
28
+ export declare function createTermSearch<T extends TermSearchItem>(
29
+ items: readonly T[],
30
+ lang?: string,
31
+ ): Search<T>;
package/src/search.js ADDED
@@ -0,0 +1,59 @@
1
+ /**
2
+ * The fuzzy search over techniques and terms, in one place for the library
3
+ * (`TaekwondoDatabase#searchTechniques`, `#searchTerms`) and for apps that
4
+ * search a compact index of their own, e.g. in the browser.
5
+ *
6
+ * Works on loaded entries as well as on flat index entries: `translation` and
7
+ * `description` may be a localized object (`{ de, en }`) or already a string
8
+ * in one language.
9
+ *
10
+ * Plain JavaScript without Node APIs, so it also runs in the browser; the
11
+ * package ships it bundled with Fuse.js as `search.browser.js`.
12
+ */
13
+ import Fuse from "fuse.js/basic";
14
+
15
+ import { stripRefs } from "./description.js";
16
+
17
+ const THRESHOLD = 0.3;
18
+
19
+ function localized(value, lang) {
20
+ if (typeof value === "string") return value;
21
+ return value?.[lang] ?? "";
22
+ }
23
+
24
+ /**
25
+ * Searches techniques by name, `supplementaryName` and translation.
26
+ * Returns a function from a query to the matching items, best first.
27
+ */
28
+ export function createTechniqueSearch(items, lang) {
29
+ const fuse = new Fuse(items, {
30
+ keys: [
31
+ "name",
32
+ "supplementaryName",
33
+ {
34
+ getFn: (item) => localized(item.translation, lang),
35
+ name: "translation",
36
+ },
37
+ ],
38
+ threshold: THRESHOLD,
39
+ });
40
+ return (query) => fuse.search(query).map((result) => result.item);
41
+ }
42
+
43
+ /**
44
+ * Searches terms by name and description, without reference markup.
45
+ * Returns a function from a query to the matching items, best first.
46
+ */
47
+ export function createTermSearch(items, lang) {
48
+ const fuse = new Fuse(items, {
49
+ keys: [
50
+ "name",
51
+ {
52
+ getFn: (item) => stripRefs(localized(item.description, lang)),
53
+ name: "description",
54
+ },
55
+ ],
56
+ threshold: THRESHOLD,
57
+ });
58
+ return (query) => fuse.search(query).map((result) => result.item);
59
+ }
@@ -0,0 +1,13 @@
1
+ import type { Source, SourceJson } from "./source";
2
+
3
+ export interface Historic {
4
+ name: string;
5
+ hangeul: string;
6
+ hanja?: string;
7
+ rr: string;
8
+ sources: Source[];
9
+ }
10
+
11
+ export interface HistoricJson extends Omit<Historic, "sources"> {
12
+ sources: SourceJson[];
13
+ }