-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathlocalizedTypes.ts
223 lines (196 loc) · 6.01 KB
/
localizedTypes.ts
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
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
import { sortBy } from 'lodash'
import { components } from './apiSchema'
import { tokenizeReference } from './tokenize'
type Id = number
type IdDict<T> = { [key: Id]: T }
const PENDING_ID: Id = -1
/* Note:
* "_Type" here refers to the entity in our problem domain
* (e.g. kind of fruit)
* and not type as programming concept
*/
type SchemaType = components['schemas']['Type']
export type LocalizedType = {
id: Id
parentId: Id
scientificName: string
commonName: string
taxonomicRank: number
urls: { [url: string]: string }
categories: string[]
synonyms: string[]
}
type TypeSelectMenuEntry = {
value: Id
searchReference: string
scientificName: string
commonName: string
label: string
synonyms: string[]
taxonomicRank: number
}
const localize = (type: SchemaType, language: string): LocalizedType => {
const scientificName = type.scientific_names?.[0] || ''
let commonName = type.common_names?.[language]?.[0] || ''
// If both scientific and common names are empty, use English common name as fallback
if (!scientificName && !commonName) {
commonName = type.common_names?.en?.[0] || ''
}
const synonyms = type.common_names?.[language]?.slice(1) || []
return {
id: type.id,
parentId: type.pending ? PENDING_ID : type.parent_id || 0,
scientificName,
commonName,
taxonomicRank: type.taxonomic_rank || 0,
urls: type.urls || {},
categories: type.categories || [],
synonyms,
}
}
const createTypesAccess = (localizedTypes: LocalizedType[]) => {
const idIndex: IdDict<number> = {}
const childrenById: IdDict<Id[]> = {}
localizedTypes.forEach((type, index) => {
idIndex[type.id] = index
if (!childrenById[type.parentId]) {
childrenById[type.parentId] = []
}
childrenById[type.parentId].push(type.id)
})
return new TypesAccess(localizedTypes, idIndex, childrenById)
}
const toMenuEntry = (
localizedType: LocalizedType,
parentCommonName: string,
) => {
const { id, parentId, commonName, scientificName, taxonomicRank, synonyms } =
localizedType
const referenceStrings = [commonName, scientificName, ...synonyms]
// If common name starts with 'common ' or 'Common ', add version without that prefix
if (commonName.toLowerCase().startsWith('common ')) {
referenceStrings.push(commonName.replace(/^[Cc]ommon\s+/, ''))
}
// Add parent name to references if it appears within common name but not at start
if (
parentCommonName &&
commonName.includes(parentCommonName.toLowerCase()) &&
!commonName.startsWith(parentCommonName)
) {
referenceStrings.push(parentCommonName)
}
const cultivarIndex = scientificName?.indexOf("'")
if (cultivarIndex !== -1) {
const cultivarName = scientificName
.substring(cultivarIndex)
.replaceAll("'", '')
referenceStrings.push(cultivarName)
}
const commonNameLabel =
parentId === PENDING_ID ? `${commonName} (Pending Review)` : commonName
return {
value: id,
searchReference: tokenizeReference(referenceStrings),
commonName: commonNameLabel,
label: commonNameLabel,
scientificName: scientificName,
taxonomicRank,
synonyms,
}
}
export class TypesAccess {
localizedTypes: LocalizedType[]
idIndex: IdDict<number>
childrenById: IdDict<Id[]>
isEmpty: boolean
constructor(
localizedTypes: LocalizedType[],
idIndex: IdDict<number>,
childrenById: IdDict<Id[]>,
) {
this.localizedTypes = localizedTypes
this.idIndex = idIndex
this.childrenById = childrenById
this.isEmpty = localizedTypes.length === 0
}
selectableTypes(): LocalizedType[] {
return this.localizedTypes.filter((t) => t.id !== PENDING_ID)
}
getType(id: Id): LocalizedType {
return this.localizedTypes[this.idIndex[id]]
}
getCommonName(id: Id): string {
const t = this.localizedTypes[this.idIndex[id]]
return t ? t.commonName : ''
}
getScientificName(id: Id): string {
const t = this.localizedTypes[this.idIndex[id]]
return t ? t.scientificName : ''
}
asMenuEntries(): TypeSelectMenuEntry[] {
return this.localizedTypes.map((t) =>
toMenuEntry(t, this.getCommonName(t.parentId)),
)
}
getMenuEntry(id: Id): TypeSelectMenuEntry | null {
const t = this.localizedTypes[this.idIndex[id]]
return t ? toMenuEntry(t, this.getCommonName(t.parentId)) : null
}
filter(predicate: (_type: LocalizedType) => boolean): TypesAccess {
const filteredTypes = this.localizedTypes.filter(predicate)
const newIdIndex: IdDict<number> = {}
const newChildrenById: IdDict<Id[]> = {}
filteredTypes.forEach((type, index) => {
newIdIndex[type.id] = index
if (!newChildrenById[type.parentId]) {
newChildrenById[type.parentId] = []
}
newChildrenById[type.parentId].push(type.id)
})
return new TypesAccess(filteredTypes, newIdIndex, newChildrenById)
}
onlyAllowedParents(): TypesAccess {
return this.filter(
({ taxonomicRank, id }) => taxonomicRank !== 9 && id !== PENDING_ID,
)
}
addType(newType: SchemaType, language: string): TypesAccess {
return createTypesAccess([
...this.localizedTypes,
localize(newType, language),
])
}
selectableTypesWithCategories(...categories: string[]): LocalizedType[] {
return this.localizedTypes.filter(
(t) =>
t.id !== PENDING_ID &&
t.categories.some((category) => categories.includes(category)),
)
}
}
const toDisplayOrder = (localizedTypes: LocalizedType[]) =>
sortBy(localizedTypes, [
(o) => !o.scientificName,
'scientificName',
(o) => -o.taxonomicRank,
'commonName',
])
export const typesAccessInLanguage = (
types: SchemaType[],
language: string,
) => {
const localizedTypes = types.map((t: SchemaType) => localize(t, language))
if (types.some((type) => type.pending)) {
localizedTypes.push({
id: PENDING_ID,
parentId: 0,
scientificName: '',
commonName: 'Pending Review',
taxonomicRank: 0,
urls: {},
categories: [],
synonyms: [],
})
}
return createTypesAccess(toDisplayOrder(localizedTypes))
}