Repository navigation
Expand file tree
/
Copy pathmake-model-dropdown.js
More file actions
1961 lines (1826 loc) · 89.6 KB
/
Copy pathmake-model-dropdown.js
File metadata and controls
1961 lines (1826 loc) · 89.6 KB
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
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
342
343
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* VehiclesDropdown — the car make and model dropdown.
* https://vehiclesdb.com/make-and-model-dropdown
*
* A dependent make → model picker for any web page, powered by the VehiclesDB
* API or by the open VehiclesDB dataset file (no key): every make and model in
* the dataset (cars, motorcycles, mopeds, vans, trucks, buses), reconciled from
* official national vehicle registers; live counts at vehiclesdb.com/makes. An optional third step picks the model
* year, and API keys whose plan includes full records can add the model's
* generation.
*
* One tag: `<div data-vehiclesdb-picker></div>` next to this script is a whole
* install (see README, "One tag").
*
* Zero dependencies. No build step. MIT licensed.
* Data: CC-BY 4.0 (identity layer) — the widget renders attribution for you.
*/
(function (root, factory) {
if (typeof module === "object" && module.exports) module.exports = factory(false)
else root.VehiclesDropdown = factory(true)
})(globalThis, function (autoStart) {
"use strict"
const DEFAULTS = {
source: "api", // "api" (publishable key) | "dataset" (the open dataset file, no key)
apiBase: "https://vehiclesdb.com/api/v1",
version: "latest", // dataset mode: the release to read, e.g. "2026.11.2"
datasetUrl: null, // dataset mode: your own copy of dist/vehicles.json
data: null, // dataset mode: an already-parsed vehicles.json (or a subset in its shape)
kind: null, // "car" | "motorcycle" | "moped" | "van" | "truck" | "bus"
country: null, // two-letter code, e.g. "de"
order: "popular", // "popular" | "alphabetical" (models)
topMakes: null, // e.g. 40 — only the N most-registered makes, best first
initialMake: null, // slug (or name) preselected on load, e.g. "audi"
initialModel: null, // slug (or name) preselected once its make's models load
initialYear: null, // e.g. 2019 — preselected once its model's years fill
yearFallback: "range", // a model with no register span: "range" | "none"
initialGeneration: null, // a generation id (or name) preselected once its model's generations load
values: "slug", // what option values hold: "slug" | "name"
includeOther: false, // append an "Other / not listed" escape hatch
otherLabel: "Other / not listed", // its text
otherValue: "other", // its option value
keepUnknown: true, // a stored value the list does not carry stays selected, unchanged
idInput: null, // an <input> kept filled with the selected model's canonical id
logos: false, // render make logos (combobox mode only)
search: false, // searchable combobox instead of a plain <select>
attribution: true, // "Vehicle data by VehiclesDB (CC-BY 4.0)" line (the licence's credit)
attributionText: null, // its wording: a template with {source} and {license}, e.g. "Datos: {source} ({license})"
locale: "en", // "en" | "es" | "de" | "fr" | "it" | "pt" | "pl" | "nl": default wording for the credit line, placeholders, Other and the required message
placeholderMake: "Make",
placeholderModel: "Model",
placeholderYear: "Year",
placeholderGeneration: "Generation",
requiredMessage: "Please select a vehicle make.", // validity message on a required make field
onChange: null, // ({ make, model }) => {} — plus `year`/`generation`/`id` when those are attached
onError: null // (error) => {}
}
// `locale` picks these defaults; an option the host sets explicitly wins.
// The credit line's template must keep {source} (the VehiclesDB link) and
// {license} (the CC-BY 4.0 link): CC-BY 4.0 §3(a) asks for both.
const LOCALES = {
en: {
placeholderMake: "Make",
placeholderModel: "Model",
placeholderYear: "Year",
placeholderGeneration: "Generation",
otherLabel: "Other / not listed",
requiredMessage: "Please select a vehicle make.",
attributionText: "Vehicle data by {source} ({license})"
},
es: {
placeholderMake: "Marca",
placeholderModel: "Modelo",
placeholderYear: "Año",
placeholderGeneration: "Generación",
otherLabel: "Otro / no está en la lista",
requiredMessage: "Selecciona la marca del vehículo.",
attributionText: "Datos de vehículos de {source} ({license})"
},
de: {
placeholderMake: "Marke",
placeholderModel: "Modell",
placeholderYear: "Baujahr",
placeholderGeneration: "Generation",
otherLabel: "Andere / nicht aufgeführt",
requiredMessage: "Bitte wählen Sie die Fahrzeugmarke aus.",
attributionText: "Fahrzeugdaten von {source} ({license})"
},
fr: {
placeholderMake: "Marque",
placeholderModel: "Modèle",
placeholderYear: "Année",
placeholderGeneration: "Génération",
otherLabel: "Autre / non répertorié",
requiredMessage: "Veuillez sélectionner la marque du véhicule.",
attributionText: "Données véhicules fournies par {source} ({license})"
},
it: {
placeholderMake: "Marca",
placeholderModel: "Modello",
placeholderYear: "Anno",
placeholderGeneration: "Generazione",
otherLabel: "Altro / non in elenco",
requiredMessage: "Selezionare la marca del veicolo.",
attributionText: "Dati sui veicoli forniti da {source} ({license})"
},
pt: {
placeholderMake: "Marca",
placeholderModel: "Modelo",
placeholderYear: "Ano",
placeholderGeneration: "Geração",
otherLabel: "Outro / não listado",
requiredMessage: "Selecione a marca do veículo.",
attributionText: "Dados de veículos fornecidos por {source} ({license})"
},
pl: {
placeholderMake: "Marka",
placeholderModel: "Model",
placeholderYear: "Rok",
placeholderGeneration: "Generacja",
otherLabel: "Inne / brak na liście",
requiredMessage: "Proszę wybrać markę pojazdu.",
attributionText: "Dane o pojazdach: {source} ({license})"
},
nl: {
placeholderMake: "Merk",
placeholderModel: "Model",
placeholderYear: "Bouwjaar",
placeholderGeneration: "Generatie",
otherLabel: "Anders / niet vermeld",
requiredMessage: "Selecteer het merk van het voertuig.",
attributionText: "Voertuiggegevens van {source} ({license})"
}
}
// The credit's VehiclesDB link: the picker's own page, tagged so the site
// can count visits from the credit line. Nothing about the embedding page
// or its visitor is added.
const SOURCE_URL = "https://vehiclesdb.com/make-and-model-dropdown?utm_source=widget&utm_medium=credit"
const LICENSE_URL = "https://creativecommons.org/licenses/by/4.0/"
// "es", "es-ES", "ES_es" → "es", "de-AT" → "de"; anything without a table → "en", warned.
function localeFor(value) {
if (value == null || value === "") return "en"
const code = String(value).toLowerCase().split(/[-_]/)[0]
if (Object.prototype.hasOwnProperty.call(LOCALES, code)) return code
console.warn(`VehiclesDropdown: no "${value}" locale; using "en" (available: ${Object.keys(LOCALES).join(", ")})`)
return "en"
}
// The host's options over the locale's defaults over DEFAULTS. An option
// passed as undefined counts as not passed.
function configFor(options) {
const given = {}
for (const [key, value] of Object.entries(options || {})) if (value !== undefined) given[key] = value
const locale = localeFor(given.locale)
return Object.assign({}, DEFAULTS, LOCALES[locale], given, { locale })
}
// How far back `yearFallback: "range"` reaches: the current year down to
// forty years ago covers the cars a garage actually sees on its ramps.
const FALLBACK_YEARS = 40
// The bounds of a believable register span: nothing was registered as a
// motor vehicle before 1886 (the Benz Patent-Motorwagen), and nothing is on
// record past next year's model year. They also cap every year list at
// ~140 rows, whatever the payload says.
const FIRST_YEAR = 1886
// In-page caches — the dataset is immutable per release, so one fetch per
// URL per pageview is the right amount of network.
const jsonCache = new Map()
const logoCache = new Map()
// Dataset mode: one fetch (and one preparation) per dataset URL, and one
// preparation per `data` object the host passes, shared by every widget on
// the page.
const datasetCache = new Map()
const preparedData = new WeakMap()
// The record behind each <option> the widget renders. Option VALUES cannot
// say which record they stand for: without a `kind`, Iveco's Daily is three
// records (bus, truck, van) with one slug, and the canonical id needs the
// one actually selected.
const optionItems = new WeakMap()
// A pinned dataset release more than this many months behind today gets
// one console.info per page (see oldDatasetNotice).
const STALE_MONTHS = 2
const STALE_DOCS_URL = "https://github.com/vehiclesdb/make-model-dropdown#keeping-the-data-current"
let staleNoticeShown = false
// The generation step's plan notice: one console.info per page, the first
// time the API says the key's plan does not include generations. After
// that, no more generation requests for that API and key on this page (a
// plan does not change between two clicks).
const PRICING_URL = "https://vehiclesdb.com/pricing"
let planNoticeShown = false
const planBlocked = new Set()
// The same file the SDKs and the Ruby gem read (dist/vehicles.min.json
// lacks names, aliases, forms and availability, so it cannot serve here).
const DATASET_BASE = "https://cdn.jsdelivr.net/gh/vehiclesdb/vehiclesdb"
function resolveEl(elOrSelector, name) {
const el = typeof elOrSelector === "string" ? document.querySelector(elOrSelector) : elOrSelector
if (!el) throw new Error(`VehiclesDropdown: ${name} element not found`)
if (el.tagName !== "SELECT" || el.multiple) {
throw new Error(`VehiclesDropdown: ${name} must be a single-select <select> element`)
}
return el
}
function resolveInput(elOrSelector) {
const el = typeof elOrSelector === "string" ? document.querySelector(elOrSelector) : elOrSelector
if (!el || el.tagName !== "INPUT") throw new Error("VehiclesDropdown: idInput must be an <input> element (a hidden field works)")
return el
}
function requestCacheKey(url, key) {
return JSON.stringify([url, key])
}
function logoURL(apiBase, slug) {
return `${apiBase}/makes/${encodeURIComponent(slug)}/logo?variant=emblem`
}
function namedItem(item) {
return Boolean(item) && typeof item.name === "string" && typeof item.slug === "string"
}
async function fetchJSON(url, key, collection, valid = namedItem) {
const cacheKey = requestCacheKey(url, key)
if (jsonCache.has(cacheKey)) return jsonCache.get(cacheKey)
const promise = fetch(url, { headers: { Authorization: `Bearer ${key}` } }).then(async (response) => {
if (!response.ok) {
const body = await response.json().catch(() => ({}))
const error = new Error(body.message || `VehiclesDB API answered ${response.status}`)
error.status = response.status
error.code = body.error
error.body = body
throw error
}
const body = await response.json()
const items = body && body[collection]
if (!Array.isArray(items) || items.some((item) => !valid(item))) {
throw new Error(`VehiclesDB API returned malformed ${collection} data`)
}
return body
})
jsonCache.set(cacheKey, promise)
promise.catch(() => jsonCache.delete(cacheKey))
return promise
}
// Logos need the Authorization header, and an <img src> cannot send one —
// so fetch each Blob once per API/key pair. Object URLs belong to an
// instance, though: destroy() revokes them instead of leaking page-lifetime
// browser resources. A 404 is a normal, cacheable miss.
async function fetchLogoBlob(apiBase, key, slug) {
const url = logoURL(apiBase, slug)
const cacheKey = requestCacheKey(url, key)
if (logoCache.has(cacheKey)) return logoCache.get(cacheKey)
const promise = fetch(url, {
headers: { Authorization: `Bearer ${key}` }
}).then(async (response) => {
if (response.status === 404) return null
if (!response.ok) throw new Error(`VehiclesDB logo API answered ${response.status}`)
return response.blob()
// ANY failure is a cached miss for the rest of the pageview: the letter
// chip renders instead. Every keystroke re-renders up to 50 rows, so a
// misbehaving logo endpoint retried per render would be a request storm.
}).catch(() => null)
logoCache.set(cacheKey, promise)
return promise
}
function query(config) {
const params = new URLSearchParams()
if (config.kind) params.set("kind", config.kind)
if (config.country) params.set("country", config.country)
if (config.topMakes) {
params.set("order", "popular")
params.set("limit", config.topMakes)
}
const s = params.toString()
return s ? `?${s}` : ""
}
function optionValue(config, item) {
return config.values === "name" ? item.name : item.slug
}
// ---- Dataset mode: the open file, filtered in the page ------------------
// `dist/vehicles.json` is `{version, makes: [{name, slug, aliases?,
// models: [{name, slug, kind, availability, aliases?, forms?, former_ids?,
// mass_decile?, global_decile?, country_ranks?}]}]}`. A host may pass a
// subset in that shape as `data` (one country's cars, rendered by its
// server) instead of the whole release.
function prepareDataset(data) {
if (!data || !Array.isArray(data.makes) || data.makes.some((make) =>
!make || typeof make.name !== "string" || typeof make.slug !== "string" ||
(make.models != null && !Array.isArray(make.models)))) {
throw new Error("VehiclesDB dataset is malformed: expected {makes: [{name, slug, models: [...]}]}")
}
const makes = data.makes.map((raw) => ({
name: raw.name,
slug: raw.slug,
kinds: raw.kinds || [],
aliases: raw.aliases || [],
models: (raw.models || []).filter((model) =>
model && typeof model.name === "string" && typeof model.slug === "string")
}))
// Name-alphabetical, diacritic-insensitive, like the gem, the SDKs and
// the API's make list (the file arrives slug-sorted).
makes.sort((a, b) => ordinal(norm(a.name), norm(b.name)) || ordinal(a.slug, b.slug))
return { version: data.version || null, makes }
}
function datasetFor(config) {
if (config.data) {
let prepared = preparedData.get(config.data)
if (!prepared) {
prepared = Promise.resolve().then(() => prepareDataset(config.data))
preparedData.set(config.data, prepared)
}
return prepared
}
const url = config.datasetUrl ||
`${DATASET_BASE}@${encodeURIComponent(config.version || "latest")}/dist/vehicles.json`
if (datasetCache.has(url)) return datasetCache.get(url)
const promise = fetch(url).then(async (response) => {
if (!response.ok) {
const error = new Error(`VehiclesDB dataset answered ${response.status}`)
error.status = response.status
throw error
}
return prepareDataset(await response.json())
})
datasetCache.set(url, promise)
// A failed fetch is not cached: the next widget (or a retry) asks again.
promise.catch(() => datasetCache.delete(url))
return promise
}
// A site that pins `version` (or a datasetUrl at `@v2026.10.1`) never gets
// new models or fixes. Releases are named YYYY.MM.PATCH, so the age needs
// no request: when the pinned month is more than STALE_MONTHS behind
// today, say so ONCE per page, in the console only (never to visitors).
function pinnedRelease(config) {
if (config.datasetUrl) {
const match = /@v?(\d{4})\.(\d{1,2})\.\d+(?:[/?#]|$)/.exec(String(config.datasetUrl))
return match ? { release: match[0].replace(/^@|[/?#]$/g, ""), year: Number(match[1]), month: Number(match[2]) } : null
}
const match = /^v?(\d{4})\.(\d{1,2})\.\d+$/.exec(String(config.version || "").trim())
return match ? { release: match[0], year: Number(match[1]), month: Number(match[2]) } : null
}
function oldDatasetNotice(config) {
if (staleNoticeShown || config.data) return
const pinned = pinnedRelease(config)
if (!pinned || pinned.month < 1 || pinned.month > 12) return
const now = new Date()
const age = (now.getFullYear() * 12 + now.getMonth() + 1) - (pinned.year * 12 + pinned.month)
if (age <= STALE_MONTHS) return
staleNoticeShown = true
console.info(`VehiclesDropdown: the pinned vehicle dataset release ${pinned.release} is ${age} months old, ` +
"so this picker is missing newer models and fixes. Omit `version` (or use @latest in `datasetUrl`) " +
`to keep it current: ${STALE_DOCS_URL}`)
}
// The scoped list, the same filters the API applies server-side: `kind`
// keeps that kind, `country` keeps models the registers have evidence for
// there (`availability`).
function inScope(config, model) {
const country = config.country ? String(config.country).toLowerCase() : null
return (!config.kind || model.kind === config.kind) &&
(!country || (Array.isArray(model.availability) && model.availability.includes(country)))
}
// The API's two orders. Popular: the country's own registration rank when
// the data has one, then the global decile, then the name.
function orderModels(config, models) {
const country = config.country ? String(config.country).toLowerCase() : null
if (config.order !== "popular") return models.slice().sort((a, b) => ordinal(a.name, b.name))
const rank = (model) => {
const value = country && model.country_ranks ? model.country_ranks[country] : null
return Number.isFinite(value) ? value : null
}
const decile = (model) => Number.isFinite(model.global_decile) ? model.global_decile : 99
return models.slice().sort((a, b) => {
const ra = rank(a), rb = rank(b)
if ((ra === null) !== (rb === null)) return ra === null ? 1 : -1
return (ra || 0) - (rb || 0) || decile(a) - decile(b) || ordinal(a.name, b.name)
})
}
// The canonical id a database should store: kind/make_slug/model_slug.
function modelId(make, model) {
return make && model && model.kind ? `${model.kind}/${make.slug}/${model.slug}` : ""
}
// ---- Matching typed text to a make or model ------------------------------
// VehiclesDB's resolution contract (RESOLUTION.md in the dataset repo) is
// one set of rules for every surface: the Ruby gem, the API, the SDKs and
// this widget. A stored "Citroen" or "VW" or "Focus C-Max" must pick the
// same record here that the API resolves it to, so this is a port of the
// contract's strict rungs, not a widget-flavoured approximation. Only the
// curated rungs run here (name/slug, published aliases, curated forms):
// typo correction is a guess, and a picker that silently preselects a
// guess writes a wrong answer into someone's form.
// The contract's one normalization: NFKD, drop combining marks, lowercase,
// every run of non-[a-z0-9] becomes one space. "Škoda" → "skoda",
// "Mercedes-Benz" → "mercedes benz", "Lynk & Co" → "lynk co".
function norm(value) {
return String(value == null ? "" : value).normalize("NFKD").replace(/\p{Mn}+/gu, "")
.toLowerCase().replace(/[^a-z0-9]+/g, " ").trim()
}
// A native-script alias (比亚迪, 현대) normalizes to nothing; like the gem,
// it is then compared by its trimmed, lowercased raw text instead.
function key(value) {
return norm(value) || `raw:${String(value == null ? "" : value).trim().toLowerCase()}`
}
// Spacing-blind: "XCeed" is the dataset's "X Ceed", "A 5" is the "A5".
function squash(k) { return k.replace(/ /g, "") }
// "Serie 3" is how BMW sells the 3 Series in Spain and Italy ("Série" in
// France normalizes the same).
const LOCALIZED_SERIES = /^serie (\w+)$/
// Code point order, never locale-aware: the contract's string comparison.
function ordinal(a, b) { return a < b ? -1 : a > b ? 1 : 0 }
// RESOLUTION §3a, the kind-collision tie-break: when a rung's hits are ONE
// nameplate in several kinds (Iveco's Daily: bus, truck, van), the record
// with the lowest `mass_decile` answers (absent = unranked = last), then by
// kind precedence, then by id. Every surface applies the same rule, so an
// unhinted "Iveco Daily" is the van in the gem, the API, the SDKs and here.
const KIND_PRECEDENCE = [ "van", "car", "bus", "truck", "moped", "motorcycle" ]
function massDecile(item) {
const value = item.mass_decile != null ? item.mass_decile : item.massDecile
return Number.isFinite(value) ? value : Infinity
}
function kindCollisionOrder(a, b) {
const da = massDecile(a), db = massDecile(b)
if (da !== db) return da < db ? -1 : 1
const ka = KIND_PRECEDENCE.indexOf(a.kind), kb = KIND_PRECEDENCE.indexOf(b.kind)
const ra = ka < 0 ? KIND_PRECEDENCE.length : ka, rb = kb < 0 ? KIND_PRECEDENCE.length : kb
if (ra !== rb) return ra - rb
return ordinal(String(a.kind), String(b.kind)) ||
ordinal(String(a.id || a.slug), String(b.id || b.slug))
}
// Run rungs strongest first; the first that finds anything decides. Hits
// on one nameplate answer (several kinds of it are a kind collision,
// settled by the tie-break above, never ambiguity); hits on two nameplates
// are AMBIGUOUS and stop the ladder, because a weaker rung must never
// overrule data that says "either".
const AMBIGUOUS = []
function firstRung(rungs) {
for (const rung of rungs) {
const hits = rung()
if (hits === AMBIGUOUS) return null
if (!hits.length) continue
const slugs = new Set(hits.map((item) => item.slug))
if (slugs.size > 1) return null
return hits.slice().sort(kindCollisionOrder)[0]
}
return null
}
function fieldHits(items, field, k) {
const tight = squash(k)
const exact = items.filter((item) => (item[field] || []).some((v) => key(v) === k))
if (exact.length) return exact
return items.filter((item) => (item[field] || []).some((v) => squash(key(v)) === tight))
}
// A make by slug or name, then by a published alias ("VW", "Merc").
function findMake(makes, wanted) {
const k = key(wanted)
if (!makes || k === "raw:") return null
return firstRung([
() => makes.filter((m) => key(m.slug) === k || key(m.name) === k),
() => fieldHits(makes, "aliases", k)
])
}
// A model of one make: name or slug (then spacing-blind, then "Serie N"),
// then a published alias, then a curated form, the registry spelling the
// dataset folds into the record ("Focus C-Max" is the C-Max).
function findModel(models, wanted) {
const k = key(wanted)
if (!models || k === "raw:") return null
const named = (q) => () => {
const exact = models.filter((m) => key(m.slug) === q || key(m.name) === q)
if (exact.length) return exact
// Spacing-blind only counts when it lands on ONE name: "a 5" must not
// choose between an "A5" and an "A 5" if a make had both.
const loose = models.filter((m) => squash(key(m.name)) === squash(q))
return new Set(loose.map((m) => key(m.name))).size > 1 ? AMBIGUOUS : loose
}
const series = k.replace(LOCALIZED_SERIES, "$1 series")
return firstRung([
named(k),
...(series !== k ? [ named(series) ] : []),
() => fieldHits(models, "aliases", k),
() => fieldHits(models, "forms", k)
])
}
// A stored canonical id (`van/iveco/daily`), then a published former id,
// among one make's models: the contract's id rungs, the strongest there
// are. A hidden id field saved by an earlier edit keeps naming its exact
// record, kind included, even where the name alone would collide.
function findModelById(make, models, id) {
const wanted = String(id == null ? "" : id).trim()
if (!make || !models || !wanted) return null
return firstRung([
() => models.filter((m) => modelId(make, m) === wanted),
() => models.filter((m) => Array.isArray(m.former_ids) && m.former_ids.includes(wanted))
])
}
// The searchable list: every make whose name, slug or published alias
// contains what was typed, compared by `norm` and spacing-blind. Exact
// answers first, then name hits, then alias-only hits ("vw" lists
// Volkswagen), each group in the list's own order (popular or A to Z).
function filterItems(items, text) {
const needle = norm(text)
if (!needle) return items
const tight = squash(needle)
const groups = [ [], [], [], [] ]
for (const item of items) {
const names = [ norm(item.name), norm(item.slug) ]
const aliases = (item.aliases || []).map(norm).filter(Boolean)
if (names.concat(aliases).some((n) => n === needle || squash(n) === tight)) groups[0].push(item)
else if (names.some((n) => n.includes(needle))) groups[1].push(item)
else if (names.some((n) => squash(n).includes(tight))) groups[2].push(item)
else if (aliases.some((n) => n.includes(needle) || squash(n).includes(tight))) groups[3].push(item)
}
return groups.flat()
}
function fillSelect(select, placeholder, items, config, selected) {
const previous = selected !== undefined ? selected : select.value
select.replaceChildren(new Option(placeholder, "", previous === "", previous === ""))
for (const item of items) {
const value = optionValue(config, item)
const option = new Option(item.name, value, value === previous, value === previous)
optionItems.set(option, item)
select.add(option)
}
}
// The escape hatch's text and value are the host's: `otherLabel` to
// translate, `otherValue` ("other" by default) for apps that store their
// own word for it.
function appendOther(select, config) {
select.add(new Option(config.otherLabel, config.otherValue))
}
// Select one option as the field's initial state, the one a form reset
// restores.
function preselect(select, option) {
option.selected = true
Array.from(select.options).forEach((each) => { each.defaultSelected = each === option })
}
function optionFor(select, item) {
return Array.from(select.options).find((option) => optionItems.get(option) === item)
}
// NEVER BLANK A STORED VALUE. A value the list does not carry (a legacy
// free-text model, a make outside the `kind`/`country` scope, a name the
// data says could be two records) is kept as one extra option, selected,
// so the form submits it unchanged until the person picks something else.
// It sits right under the placeholder, where an editor sees it. `id` is
// the canonical id it stands for, when one is known (see failModels).
function keepOption(select, value, id) {
const option = new Option(value, value)
optionItems.set(option, { kept: true, id: id || "" })
select.insertBefore(option, select.options[1] || null)
preselect(select, option)
}
// A model's register span, or null: the API's `years_on_record`, or, in
// dataset mode, the release file's `registration_years` (same {first,
// last} shape, 2026.11.3+). A missing key (older responses and releases, mocks) means
// the same as an explicit null — and so does anything that is not a sane
// {first, last} pair inside FIRST_YEAR..next year. Never trust a span
// enough to render nonsense: `last: 1e300` passes Number.isInteger and,
// since 1e300 - 1 === 1e300, would never finish counting down.
function yearSpan(model, currentYear) {
const span = model && (model.years_on_record || model.registration_years)
if (!span || !Number.isInteger(span.first) || !Number.isInteger(span.last)) return null
const sane = FIRST_YEAR <= span.first && span.first <= span.last && span.last <= currentYear + 1
return sane ? span : null
}
// Years as fillSelect items, NEWEST FIRST: a garage books a recent car far
// more often than a classic, so the likely answer sits at the top.
function yearItems(first, last) {
const items = []
for (let year = last; year >= first; year -= 1) items.push({ name: String(year), slug: String(year) })
return items
}
// ---- Generations (API mode, plans with full records) ---------------------
// A row of GET /makes/{make}/models/{model}/generations: {id, name,
// years: {start, end}, ended}. Only id and name are required; a year is a
// year or it is unknown, and an unknown year is never filled in.
function generationRow(item) {
return Boolean(item) && typeof item.id === "string" && item.id !== "" && typeof item.name === "string"
}
function knownYear(value) {
return Number.isInteger(value) && value >= FIRST_YEAR ? value : null
}
function generationYears(item) {
const years = item && item.years
return { start: knownYear(years && years.start), end: knownYear(years && years.end) }
}
// "Mk7 (2012–2020)", "8Y (2020–)" (still in production), "B5 (–2005)",
// or the bare name when no year is known. A generation that has ended
// without a sourced last year shows "2003–?", never "2003–" (which reads
// as still in production) and never a guessed year.
function generationLabel(item) {
const { start, end } = generationYears(item)
if (start == null && end == null) return item.name
const tail = end != null ? String(end) : start != null && item.ended === true ? "?" : ""
return `${item.name} (${start != null ? start : ""}–${tail})`
}
// Does this generation's span contain `year`? "yes", "maybe" (a bound is
// unknown, so it cannot be ruled out) or "no".
function generationContains(item, year) {
const { start, end } = generationYears(item)
if (start != null && year < start) return "no"
if (end != null && year > end) return "no"
if (start == null) return "maybe"
if (end == null && item.ended === true) return "maybe"
return "yes"
}
// The credit line: the host's words around two links it cannot drop. A
// template missing {source} or {license} (or not a string) falls back to
// the locale's own wording, with a warning: the credit is a licence
// condition, so it can be translated but not blanked. The template is
// text, never HTML.
function attributionParts(config) {
const template = config.attributionText
const usable = typeof template === "string" &&
template.includes("{source}") && template.includes("{license}")
if (!usable && template != null) {
console.warn("VehiclesDropdown: attributionText must contain {source} and {license} " +
"(the VehiclesDB credit and the CC-BY 4.0 licence link); using the default wording")
}
return (usable ? template : LOCALES[config.locale].attributionText).split(/(\{source\}|\{license\})/)
}
function creditLink(href, text) {
const a = document.createElement("a")
a.href = href
a.target = "_blank"
a.rel = "noopener"
a.textContent = text
a.style.cssText = "color:inherit;text-decoration:underline;"
return a
}
function attributionLine(container, config) {
const p = document.createElement("p")
p.className = "vdb-attribution"
p.style.cssText = "font-size:var(--vdb-credit-font-size, .75rem);color:var(--vdb-credit-color, #6b7280);margin:.375rem 0 0;"
for (const part of attributionParts(config)) {
if (part === "{source}") p.append(creditLink(SOURCE_URL, "VehiclesDB"))
else if (part === "{license}") p.append(creditLink(LICENSE_URL, "CC-BY 4.0"))
else if (part) p.append(part)
}
container.append(p)
return p
}
// The initial-letter chip — the fallback that always works. Rendered
// whenever a make has no logo (most do not; coverage is partial on
// purpose) or the logo fails to load.
function chip(name) {
const span = document.createElement("span")
span.className = "vdb-chip"
span.textContent = (name[0] || "?").toUpperCase()
span.style.cssText = "display:inline-flex;align-items:center;justify-content:center;" +
"width:1.25rem;height:1.25rem;border-radius:9999px;background:#e5e7eb;color:#374151;" +
"font-size:.7rem;font-weight:600;flex:none;"
return span
}
class Instance {
constructor(options) {
this.config = configFor(options)
if (this.config.source !== "api" && this.config.source !== "dataset") {
throw new Error(`VehiclesDropdown: source must be "api" or "dataset", got ${JSON.stringify(this.config.source)}`)
}
if (this.config.data != null && typeof this.config.data !== "object") {
throw new Error("VehiclesDropdown: `data` must be the parsed dataset object ({makes: [...]}), not a string")
}
// `data` is a dataset by definition; passing it is enough.
this.datasetMode = this.config.source === "dataset" || this.config.data != null
if (this.datasetMode) oldDatasetNotice(this.config)
const key = this.config.key
if (!this.datasetMode && (typeof key !== "string" || !key.trim())) {
throw new Error("VehiclesDropdown: pass your publishable API key as `key` (get one free at https://vehiclesdb.com), " +
"or use the open dataset with no key: `source: \"dataset\"`")
}
this.makeSelect = resolveEl(this.config.make, "make")
this.modelSelect = this.config.model ? resolveEl(this.config.model, "model") : null
if (this.modelSelect === this.makeSelect) {
throw new Error("VehiclesDropdown: make and model must be different <select> elements")
}
// A server-rendered model belongs to the server-rendered make (both
// come from one record), whatever `initialMake` says.
this.modelFromHost = false
if (!this.config.initialModel && this.modelSelect?.value) {
this.config.initialModel = this.modelSelect.value
this.modelFromHost = true
}
// The year depends on the model, so a year select without one has
// nothing to fill from — say so now, not with a silently empty field.
this.yearSelect = this.config.year ? resolveEl(this.config.year, "year") : null
if (this.yearSelect && !this.modelSelect) {
throw new Error("VehiclesDropdown: year needs a model <select> to depend on")
}
if (this.yearSelect && (this.yearSelect === this.makeSelect || this.yearSelect === this.modelSelect)) {
throw new Error("VehiclesDropdown: year must be a different <select> element from make and model")
}
if (!this.config.initialYear && this.yearSelect?.value) {
this.config.initialYear = this.yearSelect.value
}
// The generation depends on the model too. It is the only step that
// can be absent for a model: hidden (and disabled, so it is neither
// required nor submitted) until a model with generations the key's
// plan may see is chosen. See showGeneration.
this.generationSelect = this.config.generation ? resolveEl(this.config.generation, "generation") : null
if (this.generationSelect && !this.modelSelect) {
throw new Error("VehiclesDropdown: generation needs a model <select> to depend on")
}
if (this.generationSelect && [ this.makeSelect, this.modelSelect, this.yearSelect ].includes(this.generationSelect)) {
throw new Error("VehiclesDropdown: generation must be a different <select> element from make, model and year")
}
if (this.generationSelect) {
if (!this.config.initialGeneration && this.generationSelect.value) {
this.config.initialGeneration = this.generationSelect.value
}
const select = this.generationSelect
const labels = select.id
? Array.from(select.ownerDocument.querySelectorAll("label[for]")).filter((label) => label.htmlFor === select.id)
: []
// What hides with the step: the select, its <label for>, a <label>
// wrapped around it, and a wrapper the page marks
// data-vdb-field="generation" (the one-tag install marks its own).
this.generationTargets = Array.from(new Set([ select, ...labels, select.closest("label"),
select.closest('[data-vdb-field="generation"]') ].filter(Boolean)))
this.generationRequired = select.required
this.generationHiddenByWidget = []
this.generationDisabledByWidget = false
this.generationShown = true
this.showGeneration(false)
}
// The canonical id of the selected model, for the host's database. Its
// server-rendered value is a stored id: the strongest answer there is
// for which record the saved model is (see findModelById).
this.idInput = this.config.idInput ? resolveInput(this.config.idInput) : null
if (this.idInput && !this.modelSelect) {
throw new Error("VehiclesDropdown: idInput needs a model <select> to take the id from")
}
this.initialId = this.idInput ? this.idInput.value : ""
// `disabled` belongs to the host. The widget only ever disables the
// year select for its OWN reason (yearFallback "none" with nothing to
// choose), remembers that it did, and only ever undoes that.
this.yearDisabledByWidget = false
this.destroyed = false
this.logoUrls = new Map()
this.objectUrls = new Set()
this.handleMakeChange = () => {
this.combobox?.sync()
this.makeChanged()
}
this.handleModelChange = () => { this.modelChanged() }
this.handleYearChange = () => {
this.matchGenerationToYear()
this.notify()
}
this.handleGenerationChange = () => {
// The visitor chose: a later year pick no longer moves it.
this.generationFromYear = false
this.notify()
}
this.makeSelect.addEventListener("change", this.handleMakeChange)
if (this.modelSelect) this.modelSelect.addEventListener("change", this.handleModelChange)
if (this.yearSelect) this.yearSelect.addEventListener("change", this.handleYearChange)
if (this.generationSelect) this.generationSelect.addEventListener("change", this.handleGenerationChange)
this.form = this.makeSelect.form
this.handleFormReset = () => {
// The reset event fires before the browser restores form controls.
// Wait one task, then rebuild the dependent options for the restored
// make and reapply the configured/server-rendered initial model and year.
setTimeout(() => {
if (this.destroyed) return
this.initialModelApplied = false
this.initialYearApplied = false
this.initialGenerationApplied = false
this.combobox?.sync()
this.makeChanged()
}, 0)
}
this.form?.addEventListener("reset", this.handleFormReset)
if (this.config.search || this.config.logos) this.enhance()
if (this.config.attribution) {
const anchor = (this.yearSelect || this.modelSelect || this.makeSelect).parentElement || this.makeSelect
this.attributionEl = attributionLine(anchor, this.config)
}
this.loading = this.loadMakes()
}
get api() { return this.config.apiBase.replace(/\/$/, "") }
// The make list for this widget's scope: from the API, or from the
// dataset filtered here (a make stays when one of its models does).
async fetchMakes() {
if (!this.datasetMode) {
const data = await fetchJSON(`${this.api}/makes${query(this.config)}`, this.config.key, "makes")
return data.makes
}
const dataset = await datasetFor(this.config)
return dataset.makes.filter((make) => make.models.some((model) => inScope(this.config, model)))
}
async fetchModels(make, slug) {
if (this.datasetMode) {
if (!make) return []
await datasetFor(this.config)
return orderModels(this.config, make.models.filter((model) => inScope(this.config, model)))
}
const params = new URLSearchParams()
if (this.config.kind) params.set("kind", this.config.kind)
if (this.config.country) params.set("country", this.config.country)
if (this.config.order === "popular") params.set("order", "popular")
const url = `${this.api}/makes/${encodeURIComponent(slug)}/models?${params}`
return (await fetchJSON(url, this.config.key, "models")).models
}
async loadMakes() {
try {
const makes = await this.fetchMakes()
if (this.destroyed) return
this.makes = makes
// The host's own selection (a server-rendered edit form) wins over
// `initialMake`, as it always has.
const preselected = this.makeSelect.value
this.renderMakes()
// The preselected make, by the resolution contract (slug, name or a
// published alias, by `norm`): a stored "Citroen" or "VW" lands on
// its make. Resolved even when the host already rendered a make, so
// the model and year steps can tell whether that is the intended one.
this.initialMakeItem = this.config.initialMake ? findMake(makes, this.config.initialMake) : null
const configured = this.config.initialMake == null ? "" : String(this.config.initialMake)
// With no make at all, a stored id still names one: its record's.
const wanted = preselected || configured || this.makeForId(this.initialId)
this.hostMakeRendered = Boolean(preselected)
this.initialMakeKept = null
const outcome = this.selectMake(wanted)
if ((outcome === "kept" || outcome === "other") && (!preselected || preselected === configured)) {
this.initialMakeKept = wanted
}
this.combobox?.sync()
if (this.makeSelect.value) this.makeChanged()
else if (preselected) {
// `keepUnknown: false`: a server-rendered selection the list does
// not carry has just been dropped. Say so: the consumer's own state
// still holds the old value, and a silent empty submit is the
// worst outcome.
console.warn(`[VehiclesDropdown] preselected make ${JSON.stringify(preselected)} is not in the fetched list; selection cleared`)
this.notify()
}
} catch (error) {
if (!this.destroyed) this.fail(error)
}
}
// The make option value of the record a stored id (or former id) names,
// or "". The dataset can look the id up; the API's make list cannot, so
// there the id's own make slug answers.
makeForId(id) {
if (!id) return ""
const make = this.datasetMode
? this.makes.find((each) => findModelById(each, each.models.filter((m) => inScope(this.config, m)), id))
: this.makes.find((each) => each.slug === String(id).split("/")[1])
return make ? optionValue(this.config, make) : ""
}
renderMakes() {
fillSelect(this.makeSelect, this.config.placeholderMake, this.makes, this.config, "")
if (this.config.includeOther) appendOther(this.makeSelect, this.config)
if (this.combobox) this.combobox.setItems(this.makes)
}
// Put a stored make on the make select: the option itself, or its make
// by the contract, or (keepUnknown) the value as given. Returns what
// happened: "selected", "other", "kept" or "" (nothing selected).
selectMake(wanted) {
if (!wanted) return ""
const select = this.makeSelect
if (wanted === this.config.otherValue && this.config.includeOther) {
preselect(select, Array.from(select.options).find((option) => option.value === wanted))
return "other"
}
const item = this.makes.find((make) => optionValue(this.config, make) === wanted) || findMake(this.makes, wanted)
if (item) {
preselect(select, optionFor(select, item))
this.combobox?.display(item)
return "selected"
}
if (!this.config.keepUnknown) return ""
keepOption(select, wanted)
return "kept"
}
// Set a stored make/model (and year, and id) after attach, by the same
// rules as the initial values: resolved to the canonical options when the
// data can, kept as given when it cannot. Resolves once applied.
async setValue({ make = null, model = null, year = null, generation = null, id = null } = {}) {
await this.loading
if (this.destroyed || !this.makes) return
this.config.initialMake = make
this.config.initialModel = model
this.config.initialYear = year
this.config.initialGeneration = generation
this.initialId = id || ""
this.modelFromHost = false
this.initialModelApplied = false
this.initialYearApplied = false
this.initialGenerationApplied = false
this.renderMakes()
this.initialMakeItem = make ? findMake(this.makes, make) : null
this.initialMakeKept = null
const wanted = make == null ? this.makeForId(this.initialId) : String(make)
const outcome = this.selectMake(wanted)
if (outcome === "kept" || outcome === "other") this.initialMakeKept = wanted
this.combobox?.sync()
await this.makeChanged()
// The generation list is a request of its own: resolve once it lands.
await this.generationLoading
}
async makeChanged() {
// CLEAR THE MODEL BEFORE ANNOUNCING. The old model belongs to the old
// make, so reporting {make: "suzuki", model: "golf"} for the moment
// between the change and the fetch is not a lag, it is a wrong answer —
// and onChange consumers write it straight into their form state.
// The year belongs to the old model, so it goes with it.
this.models = null
this.modelsMake = null
// Only the latest call may fill the model select: a value check alone
// cannot tell two loads for the same make apart (setValue right after
// attach), and the older one would spend the initial model.
const turn = this.makeTurn = (this.makeTurn || 0) + 1
if (this.modelSelect) {
fillSelect(this.modelSelect, this.config.placeholderModel, [], this.config, "")
}
if (this.yearSelect) this.fillYears()
if (this.generationSelect) this.clearGenerations()
this.notify()
if (this.destroyed) return
if (!this.modelSelect) return
const makeValue = this.makeSelect.value
if (!makeValue) return
// `values: "name"` still needs the slug for the URL — look it up.
const make = this.makes?.find((m) => optionValue(this.config, m) === makeValue)
// Other, or a kept make the list does not carry: there are no models to
// load, but a stored model still deserves to survive the edit.
if ((makeValue === this.config.otherValue && this.config.includeOther) || (!make && (this.makes || this.datasetMode))) {
if (this.config.includeOther) appendOther(this.modelSelect, this.config)
this.applyInitialModel(null, [])
// An Other make has one possible model, Other: choose it, so a
// required model field is satisfied and the year step can follow.
if (makeValue === this.config.otherValue && this.config.includeOther && !this.modelSelect.value) {
this.modelSelect.value = this.config.otherValue
this.modelChanged()
}
return