@arbetsformedlingen/yrkesvaljaren 2.0.12 → 2.2.0

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 (98) hide show
  1. package/README.md +52 -21
  2. package/dist/cjs/{af-validation-message-Cy89nVEv.js → af-validation-message-BdR9X_qh.js} +1 -1
  3. package/dist/cjs/core-selector.cjs.entry.js +342 -23
  4. package/dist/cjs/digi-service-job-selector.cjs.entry.js +352 -61
  5. package/dist/cjs/{index-hZgOvC17.js → index-DMQDFAL7.js} +0 -22
  6. package/dist/cjs/index.cjs.js +4 -7
  7. package/dist/cjs/loader.cjs.js +2 -2
  8. package/dist/{esm/fuse-BPnhMTul.js → cjs/types-DdzCbiye.js} +965 -1
  9. package/dist/cjs/yrkesvaljaren.cjs.js +2 -2
  10. package/dist/collection/collection-manifest.json +0 -1
  11. package/dist/collection/components/core-selector/core-selector.css +70 -49
  12. package/dist/collection/components/core-selector/core-selector.js +309 -14
  13. package/dist/collection/components/design-compat/af-icon.js +8 -7
  14. package/dist/collection/components/job-selector/job-selector-controller.js +13 -3
  15. package/dist/collection/components/job-selector/job-selector.css +188 -34
  16. package/dist/collection/components/job-selector/job-selector.js +199 -10
  17. package/dist/components/core-selector2.js +1 -1
  18. package/dist/components/digi-service-job-selector.js +1 -1
  19. package/dist/components/index.js +1 -1
  20. package/dist/components/types.js +1 -1
  21. package/dist/esm/{af-validation-message-BgoGzzBf.js → af-validation-message-DMoOu-0k.js} +1 -1
  22. package/dist/esm/core-selector.entry.js +342 -23
  23. package/dist/esm/digi-service-job-selector.entry.js +310 -19
  24. package/dist/esm/{index-HNd02eQb.js → index-vJ-tamti.js} +1 -22
  25. package/dist/esm/index.js +2 -4
  26. package/dist/esm/loader.js +3 -3
  27. package/dist/{cjs/fuse-BTLNKxuL.js → esm/types-DVos4HHS.js} +948 -2
  28. package/dist/esm/yrkesvaljaren.js +3 -3
  29. package/dist/types/components/core-selector/core-selector.d.ts +68 -0
  30. package/dist/types/components/job-selector/job-selector-controller.d.ts +5 -0
  31. package/dist/types/components/job-selector/job-selector.d.ts +21 -3
  32. package/dist/types/components/job-selector/types.d.ts +12 -0
  33. package/dist/types/components.d.ts +20 -99
  34. package/dist/types/index.d.ts +1 -1
  35. package/dist/vendor/taxonomy-core/af-data-layer.d.ts +16 -0
  36. package/dist/vendor/taxonomy-core/af-data-layer.js +24 -0
  37. package/dist/vendor/taxonomy-core/index.d.ts +1 -1
  38. package/dist/vendor/taxonomy-core/index.js +1 -1
  39. package/dist/vendor/taxonomy-core/pii-sanitizer.d.ts +25 -0
  40. package/dist/vendor/taxonomy-core/pii-sanitizer.js +137 -0
  41. package/dist/vendor/taxonomy-core/selector-navigation.d.ts +9 -1
  42. package/dist/vendor/taxonomy-core/selector-navigation.js +28 -1
  43. package/dist/vendor/taxonomy-core/selector-types.d.ts +12 -0
  44. package/dist/yrkesvaljaren/index.esm.js +1 -1
  45. package/dist/yrkesvaljaren/p-0f19a308.entry.js +1 -0
  46. package/dist/yrkesvaljaren/{p-BUviBbwX.js → p-DHK95AvZ.js} +1 -1
  47. package/dist/yrkesvaljaren/p-DVos4HHS.js +1 -0
  48. package/dist/yrkesvaljaren/p-b81496c8.entry.js +1 -0
  49. package/dist/yrkesvaljaren/p-vJ-tamti.js +3 -0
  50. package/dist/yrkesvaljaren/yrkesvaljaren.esm.js +1 -1
  51. package/package.json +12 -10
  52. package/dist/cjs/geo-valjaren.cjs.entry.js +0 -14910
  53. package/dist/cjs/job-selector-demo.cjs.entry.js +0 -690
  54. package/dist/cjs/neobrutal-search.cjs.entry.js +0 -171
  55. package/dist/cjs/search.engine-D4cpbVzd.js +0 -504
  56. package/dist/cjs/taxonomy-registry-Dzt0SPzT.js +0 -454
  57. package/dist/cjs/types-CtHBl6Ra.js +0 -14
  58. package/dist/collection/components/geovaljaren/geovaljaren.css +0 -21
  59. package/dist/collection/components/geovaljaren/geovaljaren.js +0 -304
  60. package/dist/collection/components/geovaljaren/logic/adapter.utils.js +0 -20
  61. package/dist/collection/components/geovaljaren/logic/data.utils.js +0 -12
  62. package/dist/collection/components/geovaljaren/logic/history-service.js +0 -25
  63. package/dist/collection/components/geovaljaren/logic/search.engine.js +0 -28
  64. package/dist/collection/verkstad/verkstad.js +0 -408
  65. package/dist/components/fuse.js +0 -1
  66. package/dist/components/geo-valjaren.d.ts +0 -11
  67. package/dist/components/geo-valjaren.js +0 -1
  68. package/dist/components/job-selector-demo.d.ts +0 -11
  69. package/dist/components/job-selector-demo.js +0 -1
  70. package/dist/components/job-selector.js +0 -1
  71. package/dist/components/neobrutal-search.d.ts +0 -11
  72. package/dist/components/neobrutal-search.js +0 -1
  73. package/dist/components/search.engine.js +0 -1
  74. package/dist/esm/geo-valjaren.entry.js +0 -14908
  75. package/dist/esm/job-selector-demo.entry.js +0 -688
  76. package/dist/esm/neobrutal-search.entry.js +0 -169
  77. package/dist/esm/search.engine-BaWUTc3r.js +0 -493
  78. package/dist/esm/taxonomy-registry-C-pSh51L.js +0 -449
  79. package/dist/esm/types-DHUftoZJ.js +0 -12
  80. package/dist/types/components/geovaljaren/geovaljaren.d.ts +0 -24
  81. package/dist/types/components/geovaljaren/logic/adapter.utils.d.ts +0 -7
  82. package/dist/types/components/geovaljaren/logic/data.utils.d.ts +0 -7
  83. package/dist/types/components/geovaljaren/logic/history-service.d.ts +0 -6
  84. package/dist/types/components/geovaljaren/logic/search.engine.d.ts +0 -7
  85. package/dist/types/components/job-selector-demo/job-selector-demo.d.ts +0 -65
  86. package/dist/types/components/neobrutal-search/neobrutal-search.d.ts +0 -18
  87. package/dist/types/verkstad/verkstad.d.ts +0 -1
  88. package/dist/types/vitest-globals.d.ts +0 -1
  89. package/dist/yrkesvaljaren/p-5c3a5308.entry.js +0 -1
  90. package/dist/yrkesvaljaren/p-9ecd5177.entry.js +0 -1
  91. package/dist/yrkesvaljaren/p-BPnhMTul.js +0 -1
  92. package/dist/yrkesvaljaren/p-C-pSh51L.js +0 -1
  93. package/dist/yrkesvaljaren/p-CjMoDiZD.js +0 -1
  94. package/dist/yrkesvaljaren/p-DHUftoZJ.js +0 -1
  95. package/dist/yrkesvaljaren/p-HNd02eQb.js +0 -3
  96. package/dist/yrkesvaljaren/p-b6130085.entry.js +0 -1
  97. package/dist/yrkesvaljaren/p-dbbea724.entry.js +0 -1
  98. package/dist/yrkesvaljaren/p-df3fa43b.entry.js +0 -1
@@ -1,3 +1,453 @@
1
+ 'use strict';
2
+
3
+ function getDefaultExportFromCjs (x) {
4
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5
+ }
6
+
7
+ var loglevel$1 = {exports: {}};
8
+
9
+ /*
10
+ * loglevel - https://github.com/pimterry/loglevel
11
+ *
12
+ * Copyright (c) 2013 Tim Perry
13
+ * Licensed under the MIT license.
14
+ */
15
+ var loglevel = loglevel$1.exports;
16
+
17
+ var hasRequiredLoglevel;
18
+
19
+ function requireLoglevel () {
20
+ if (hasRequiredLoglevel) return loglevel$1.exports;
21
+ hasRequiredLoglevel = 1;
22
+ (function (module) {
23
+ (function (root, definition) {
24
+ if (module.exports) {
25
+ module.exports = definition();
26
+ } else {
27
+ root.log = definition();
28
+ }
29
+ }(loglevel, function () {
30
+
31
+ // Slightly dubious tricks to cut down minimized file size
32
+ var noop = function() {};
33
+ var undefinedType = "undefined";
34
+ var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
35
+ /Trident\/|MSIE /.test(window.navigator.userAgent)
36
+ );
37
+
38
+ var logMethods = [
39
+ "trace",
40
+ "debug",
41
+ "info",
42
+ "warn",
43
+ "error"
44
+ ];
45
+
46
+ var _loggersByName = {};
47
+ var defaultLogger = null;
48
+
49
+ // Cross-browser bind equivalent that works at least back to IE6
50
+ function bindMethod(obj, methodName) {
51
+ var method = obj[methodName];
52
+ if (typeof method.bind === 'function') {
53
+ return method.bind(obj);
54
+ } else {
55
+ try {
56
+ return Function.prototype.bind.call(method, obj);
57
+ } catch (e) {
58
+ // Missing bind shim or IE8 + Modernizr, fallback to wrapping
59
+ return function() {
60
+ return Function.prototype.apply.apply(method, [obj, arguments]);
61
+ };
62
+ }
63
+ }
64
+ }
65
+
66
+ // Trace() doesn't print the message in IE, so for that case we need to wrap it
67
+ function traceForIE() {
68
+ if (console.log) {
69
+ if (console.log.apply) {
70
+ console.log.apply(console, arguments);
71
+ } else {
72
+ // In old IE, native console methods themselves don't have apply().
73
+ Function.prototype.apply.apply(console.log, [console, arguments]);
74
+ }
75
+ }
76
+ if (console.trace) console.trace();
77
+ }
78
+
79
+ // Build the best logging method possible for this env
80
+ // Wherever possible we want to bind, not wrap, to preserve stack traces
81
+ function realMethod(methodName) {
82
+ if (methodName === 'debug') {
83
+ methodName = 'log';
84
+ }
85
+
86
+ if (typeof console === undefinedType) {
87
+ return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
88
+ } else if (methodName === 'trace' && isIE) {
89
+ return traceForIE;
90
+ } else if (console[methodName] !== undefined) {
91
+ return bindMethod(console, methodName);
92
+ } else if (console.log !== undefined) {
93
+ return bindMethod(console, 'log');
94
+ } else {
95
+ return noop;
96
+ }
97
+ }
98
+
99
+ // These private functions always need `this` to be set properly
100
+
101
+ function replaceLoggingMethods() {
102
+ /*jshint validthis:true */
103
+ var level = this.getLevel();
104
+
105
+ // Replace the actual methods.
106
+ for (var i = 0; i < logMethods.length; i++) {
107
+ var methodName = logMethods[i];
108
+ this[methodName] = (i < level) ?
109
+ noop :
110
+ this.methodFactory(methodName, level, this.name);
111
+ }
112
+
113
+ // Define log.log as an alias for log.debug
114
+ this.log = this.debug;
115
+
116
+ // Return any important warnings.
117
+ if (typeof console === undefinedType && level < this.levels.SILENT) {
118
+ return "No console available for logging";
119
+ }
120
+ }
121
+
122
+ // In old IE versions, the console isn't present until you first open it.
123
+ // We build realMethod() replacements here that regenerate logging methods
124
+ function enableLoggingWhenConsoleArrives(methodName) {
125
+ return function () {
126
+ if (typeof console !== undefinedType) {
127
+ replaceLoggingMethods.call(this);
128
+ this[methodName].apply(this, arguments);
129
+ }
130
+ };
131
+ }
132
+
133
+ // By default, we use closely bound real methods wherever possible, and
134
+ // otherwise we wait for a console to appear, and then try again.
135
+ function defaultMethodFactory(methodName, _level, _loggerName) {
136
+ /*jshint validthis:true */
137
+ return realMethod(methodName) ||
138
+ enableLoggingWhenConsoleArrives.apply(this, arguments);
139
+ }
140
+
141
+ function Logger(name, factory) {
142
+ // Private instance variables.
143
+ var self = this;
144
+ /**
145
+ * The level inherited from a parent logger (or a global default). We
146
+ * cache this here rather than delegating to the parent so that it stays
147
+ * in sync with the actual logging methods that we have installed (the
148
+ * parent could change levels but we might not have rebuilt the loggers
149
+ * in this child yet).
150
+ * @type {number}
151
+ */
152
+ var inheritedLevel;
153
+ /**
154
+ * The default level for this logger, if any. If set, this overrides
155
+ * `inheritedLevel`.
156
+ * @type {number|null}
157
+ */
158
+ var defaultLevel;
159
+ /**
160
+ * A user-specific level for this logger. If set, this overrides
161
+ * `defaultLevel`.
162
+ * @type {number|null}
163
+ */
164
+ var userLevel;
165
+
166
+ var storageKey = "loglevel";
167
+ if (typeof name === "string") {
168
+ storageKey += ":" + name;
169
+ } else if (typeof name === "symbol") {
170
+ storageKey = undefined;
171
+ }
172
+
173
+ function persistLevelIfPossible(levelNum) {
174
+ var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
175
+
176
+ if (typeof window === undefinedType || !storageKey) return;
177
+
178
+ // Use localStorage if available
179
+ try {
180
+ window.localStorage[storageKey] = levelName;
181
+ return;
182
+ } catch (ignore) {}
183
+
184
+ // Use session cookie as fallback
185
+ try {
186
+ window.document.cookie =
187
+ encodeURIComponent(storageKey) + "=" + levelName + ";";
188
+ } catch (ignore) {}
189
+ }
190
+
191
+ function getPersistedLevel() {
192
+ var storedLevel;
193
+
194
+ if (typeof window === undefinedType || !storageKey) return;
195
+
196
+ try {
197
+ storedLevel = window.localStorage[storageKey];
198
+ } catch (ignore) {}
199
+
200
+ // Fallback to cookies if local storage gives us nothing
201
+ if (typeof storedLevel === undefinedType) {
202
+ try {
203
+ var cookie = window.document.cookie;
204
+ var cookieName = encodeURIComponent(storageKey);
205
+ var location = cookie.indexOf(cookieName + "=");
206
+ if (location !== -1) {
207
+ storedLevel = /^([^;]+)/.exec(
208
+ cookie.slice(location + cookieName.length + 1)
209
+ )[1];
210
+ }
211
+ } catch (ignore) {}
212
+ }
213
+
214
+ // If the stored level is not valid, treat it as if nothing was stored.
215
+ if (self.levels[storedLevel] === undefined) {
216
+ storedLevel = undefined;
217
+ }
218
+
219
+ return storedLevel;
220
+ }
221
+
222
+ function clearPersistedLevel() {
223
+ if (typeof window === undefinedType || !storageKey) return;
224
+
225
+ // Use localStorage if available
226
+ try {
227
+ window.localStorage.removeItem(storageKey);
228
+ } catch (ignore) {}
229
+
230
+ // Use session cookie as fallback
231
+ try {
232
+ window.document.cookie =
233
+ encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
234
+ } catch (ignore) {}
235
+ }
236
+
237
+ function normalizeLevel(input) {
238
+ var level = input;
239
+ if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
240
+ level = self.levels[level.toUpperCase()];
241
+ }
242
+ if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
243
+ return level;
244
+ } else {
245
+ throw new TypeError("log.setLevel() called with invalid level: " + input);
246
+ }
247
+ }
248
+
249
+ /*
250
+ *
251
+ * Public logger API - see https://github.com/pimterry/loglevel for details
252
+ *
253
+ */
254
+
255
+ self.name = name;
256
+
257
+ self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
258
+ "ERROR": 4, "SILENT": 5};
259
+
260
+ self.methodFactory = factory || defaultMethodFactory;
261
+
262
+ self.getLevel = function () {
263
+ if (userLevel != null) {
264
+ return userLevel;
265
+ } else if (defaultLevel != null) {
266
+ return defaultLevel;
267
+ } else {
268
+ return inheritedLevel;
269
+ }
270
+ };
271
+
272
+ self.setLevel = function (level, persist) {
273
+ userLevel = normalizeLevel(level);
274
+ if (persist !== false) { // defaults to true
275
+ persistLevelIfPossible(userLevel);
276
+ }
277
+
278
+ // NOTE: in v2, this should call rebuild(), which updates children.
279
+ return replaceLoggingMethods.call(self);
280
+ };
281
+
282
+ self.setDefaultLevel = function (level) {
283
+ defaultLevel = normalizeLevel(level);
284
+ if (!getPersistedLevel()) {
285
+ self.setLevel(level, false);
286
+ }
287
+ };
288
+
289
+ self.resetLevel = function () {
290
+ userLevel = null;
291
+ clearPersistedLevel();
292
+ replaceLoggingMethods.call(self);
293
+ };
294
+
295
+ self.enableAll = function(persist) {
296
+ self.setLevel(self.levels.TRACE, persist);
297
+ };
298
+
299
+ self.disableAll = function(persist) {
300
+ self.setLevel(self.levels.SILENT, persist);
301
+ };
302
+
303
+ self.rebuild = function () {
304
+ if (defaultLogger !== self) {
305
+ inheritedLevel = normalizeLevel(defaultLogger.getLevel());
306
+ }
307
+ replaceLoggingMethods.call(self);
308
+
309
+ if (defaultLogger === self) {
310
+ for (var childName in _loggersByName) {
311
+ _loggersByName[childName].rebuild();
312
+ }
313
+ }
314
+ };
315
+
316
+ // Initialize all the internal levels.
317
+ inheritedLevel = normalizeLevel(
318
+ defaultLogger ? defaultLogger.getLevel() : "WARN"
319
+ );
320
+ var initialLevel = getPersistedLevel();
321
+ if (initialLevel != null) {
322
+ userLevel = normalizeLevel(initialLevel);
323
+ }
324
+ replaceLoggingMethods.call(self);
325
+ }
326
+
327
+ /*
328
+ *
329
+ * Top-level API
330
+ *
331
+ */
332
+
333
+ defaultLogger = new Logger();
334
+
335
+ defaultLogger.getLogger = function getLogger(name) {
336
+ if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
337
+ throw new TypeError("You must supply a name when creating a logger.");
338
+ }
339
+
340
+ var logger = _loggersByName[name];
341
+ if (!logger) {
342
+ logger = _loggersByName[name] = new Logger(
343
+ name,
344
+ defaultLogger.methodFactory
345
+ );
346
+ }
347
+ return logger;
348
+ };
349
+
350
+ // Grab the current global log variable in case of overwrite
351
+ var _log = (typeof window !== undefinedType) ? window.log : undefined;
352
+ defaultLogger.noConflict = function() {
353
+ if (typeof window !== undefinedType &&
354
+ window.log === defaultLogger) {
355
+ window.log = _log;
356
+ }
357
+
358
+ return defaultLogger;
359
+ };
360
+
361
+ defaultLogger.getLoggers = function getLoggers() {
362
+ return _loggersByName;
363
+ };
364
+
365
+ // ES6 default export, for compatibility
366
+ defaultLogger['default'] = defaultLogger;
367
+
368
+ return defaultLogger;
369
+ }));
370
+ } (loglevel$1));
371
+ return loglevel$1.exports;
372
+ }
373
+
374
+ var loglevelExports = requireLoglevel();
375
+ var log = /*@__PURE__*/getDefaultExportFromCjs(loglevelExports);
376
+
377
+ let registeredTaxonomy = [];
378
+ let registeredVersion = null;
379
+ function isRecord(value) {
380
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
381
+ }
382
+ function isNonEmptyString(value) {
383
+ return typeof value === 'string' && value.trim().length > 0;
384
+ }
385
+ function isOptionalString(value) {
386
+ return value === undefined || typeof value === 'string';
387
+ }
388
+ function isTaxonomyItem(value) {
389
+ if (!isRecord(value))
390
+ return false;
391
+ return (isNonEmptyString(value.id)
392
+ && (value.type === 'job-title' || value.type === 'occupation-name')
393
+ && isNonEmptyString(value.preferred_label)
394
+ && isOptionalString(value.ssyk_level_4_id)
395
+ && isOptionalString(value.ssyk_code_2012)
396
+ && isOptionalString(value.occupation_name_id)
397
+ && isOptionalString(value.occupation_name_preferred_label)
398
+ && (value.weight === undefined || (typeof value.weight === 'number' && Number.isFinite(value.weight)))
399
+ && (value.search_aliases === undefined
400
+ || (Array.isArray(value.search_aliases) && value.search_aliases.every((alias) => typeof alias === 'string'))));
401
+ }
402
+ function isTaxonomyRegistration(value) {
403
+ if (!isRecord(value) || !Array.isArray(value.data) || value.data.length === 0) {
404
+ return false;
405
+ }
406
+ return value.data.every((item) => isTaxonomyItem(item));
407
+ }
408
+ function normalizeTaxonomyData(data) {
409
+ const seenRelationsByConceptId = new Map();
410
+ return data.filter((item) => {
411
+ const relationId = item.type === 'job-title'
412
+ ? item.occupation_name_id ?? ''
413
+ : '';
414
+ const seenRelations = seenRelationsByConceptId.get(item.id) ?? new Set();
415
+ if (seenRelations.has(relationId))
416
+ return false;
417
+ seenRelations.add(relationId);
418
+ seenRelationsByConceptId.set(item.id, seenRelations);
419
+ return true;
420
+ });
421
+ }
422
+ /**
423
+ * Registrerar validerad taxonomidata för webbkomponenten.
424
+ * Ogiltig data ersätter aldrig en tidigare giltig registrering.
425
+ */
426
+ function registerTaxonomy(data) {
427
+ if (!isTaxonomyRegistration(data)) {
428
+ log.error('[TaxonomyRegistry] Felaktigt format på taxonomidata vid registrering.');
429
+ return;
430
+ }
431
+ // Public data can repeat one SSYK 6 job-title Concept ID for distinct
432
+ // SSYK 5 occupation-name relations. Keep those relation rows while
433
+ // removing exact duplicates. The concept identity remains item.id.
434
+ registeredTaxonomy = normalizeTaxonomyData(data.data).map((item) => ({ ...item }));
435
+ const metadataVersion = isRecord(data.metadata)
436
+ ? data.metadata.labour_market_taxonomy_version
437
+ : undefined;
438
+ registeredVersion = metadataVersion !== undefined
439
+ ? String(metadataVersion)
440
+ : (data.taxonomyVersion !== undefined ? String(data.taxonomyVersion) : 'unknown');
441
+ log.debug(`[TaxonomyRegistry] Taxonomi version ${registeredVersion} registrerades med ${registeredTaxonomy.length} yrken.`);
442
+ }
443
+ /** Hämtar den registrerade taxonomin. */
444
+ function getRegisteredTaxonomy() {
445
+ if (registeredTaxonomy.length === 0) {
446
+ log.warn('[TaxonomyRegistry] Ingen taxonomi är registrerad ännu! Anropa registerTaxonomy(data) först.');
447
+ }
448
+ return registeredTaxonomy;
449
+ }
450
+
1
451
  /**
2
452
  * Fuse.js v7.5.0 - Lightweight fuzzy-search (http://fusejs.io)
3
453
  *
@@ -1626,4 +2076,518 @@ Fuse.use = function(...plugins) {
1626
2076
  };
1627
2077
  var entry_default = Fuse;
1628
2078
 
1629
- export { entry_default as e };
2079
+ // Minimum number of characters required to trigger search
2080
+ const MIN_INPUT_LENGTH = 1;
2081
+ // Debounce time for search input (ms)
2082
+ const DEBOUNCE_TIME = 100; // ms - Återställt till 250 baserat på sok-box.tsx initialt
2083
+ // Default maximum number of results to display
2084
+ const MAX_RESULTS = 20;
2085
+ // Configuration for Fuse.js
2086
+ const FUSE_OPTIONS = {
2087
+ keys: ['preferred_label'], // Ändrat från 'label' till 'preferred_label' för att matcha datastrukturen
2088
+ includeScore: true,
2089
+ ignoreDiacritics: true, // Lägg till för att matcha t.ex. vard -> vård
2090
+ ignoreFieldNorm: true, // Lägg till för att ignorera fältlängd vid poängsättning
2091
+ threshold: 0.6, // Behåll 0.6
2092
+ minMatchCharLength: MIN_INPUT_LENGTH, // Refererar till konstant ovan
2093
+ ignoreLocation: true, // Match anywhere in the string
2094
+ distance: 100, // Allow matches further apart
2095
+ };
2096
+ // UI Text Strings
2097
+ const PLACEHOLDER_TEXT = "T.ex. målare, florist, kock";
2098
+
2099
+ const LabelFormatter = {
2100
+ format: (label, query, occupationLabel) => {
2101
+ // 1. Highlight the main label based on query
2102
+ const labelSegments = highlightText(label, query);
2103
+ // 2. Append occupation label if it exists (the "metadata" part)
2104
+ if (occupationLabel) {
2105
+ return [
2106
+ ...labelSegments,
2107
+ { text: ' ', isMatch: false },
2108
+ { text: `(${occupationLabel})`, isMetadata: true }
2109
+ ];
2110
+ }
2111
+ return labelSegments;
2112
+ }
2113
+ };
2114
+ function calculateEditDistance$1(a, b) {
2115
+ const m = a.length;
2116
+ const n = b.length;
2117
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
2118
+ for (let i = 0; i <= m; i++)
2119
+ dp[i][0] = i;
2120
+ for (let j = 0; j <= n; j++)
2121
+ dp[0][j] = j;
2122
+ for (let i = 1; i <= m; i++) {
2123
+ for (let j = 1; j <= n; j++) {
2124
+ dp[i][j] = a[i - 1] === b[j - 1]
2125
+ ? dp[i - 1][j - 1]
2126
+ : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
2127
+ }
2128
+ }
2129
+ return dp[m][n];
2130
+ }
2131
+ function findBestFuzzySubstring$1(text, qToken) {
2132
+ const lowerText = text.toLowerCase();
2133
+ const targetLen = qToken.length;
2134
+ let bestDist = 99;
2135
+ let bestStart = -1;
2136
+ let bestLen = 0;
2137
+ const minLen = Math.max(3, targetLen - 2);
2138
+ const maxLen = Math.min(lowerText.length, targetLen + 2);
2139
+ for (let start = 0; start <= lowerText.length - minLen; start++) {
2140
+ for (let len = minLen; len <= maxLen && start + len <= lowerText.length; len++) {
2141
+ const sub = lowerText.slice(start, start + len);
2142
+ const dist = calculateEditDistance$1(qToken, sub);
2143
+ if (dist < bestDist) {
2144
+ bestDist = dist;
2145
+ bestStart = start;
2146
+ bestLen = len;
2147
+ }
2148
+ }
2149
+ }
2150
+ const maxAllowedDist = Math.max(2, Math.floor(targetLen * 0.25));
2151
+ if (bestDist <= maxAllowedDist && bestStart !== -1) {
2152
+ return { start: bestStart, length: bestLen };
2153
+ }
2154
+ return null;
2155
+ }
2156
+ /**
2157
+ * Highlights matches in text based on query.
2158
+ * Supports multi-word queries.
2159
+ */
2160
+ function highlightText(text, query) {
2161
+ if (!text)
2162
+ return [];
2163
+ if (!query || query.trim().length === 0) {
2164
+ return [{ text, isMatch: false }];
2165
+ }
2166
+ const lowerText = text.toLowerCase();
2167
+ const tokens = query.toLowerCase().split(/\s+/).filter(t => t.length > 0);
2168
+ // Set of indices in the original text that should be highlighted
2169
+ const highlightedIndices = new Set();
2170
+ tokens.forEach(token => {
2171
+ let startIndex = 0;
2172
+ while ((startIndex = lowerText.indexOf(token, startIndex)) !== -1) {
2173
+ for (let i = 0; i < token.length; i++) {
2174
+ highlightedIndices.add(startIndex + i);
2175
+ }
2176
+ startIndex += token.length;
2177
+ }
2178
+ });
2179
+ if (highlightedIndices.size === 0) {
2180
+ // Fuzzy highlight fallback: Hitta bästa matchande delsträng i sammansatta ord eller felstavningar
2181
+ tokens.forEach(qToken => {
2182
+ const match = findBestFuzzySubstring$1(text, qToken);
2183
+ if (match) {
2184
+ for (let i = 0; i < match.length; i++) {
2185
+ highlightedIndices.add(match.start + i);
2186
+ }
2187
+ }
2188
+ });
2189
+ }
2190
+ if (highlightedIndices.size === 0) {
2191
+ return [{ text, isMatch: false }];
2192
+ }
2193
+ const segments = [];
2194
+ let currentSegmentText = '';
2195
+ let currentIsMatch = highlightedIndices.has(0);
2196
+ for (let i = 0; i < text.length; i++) {
2197
+ const isMatch = highlightedIndices.has(i);
2198
+ if (isMatch !== currentIsMatch) {
2199
+ // Push previous segment
2200
+ if (currentSegmentText.length > 0) {
2201
+ segments.push({ text: currentSegmentText, isMatch: currentIsMatch });
2202
+ }
2203
+ // Start new segment
2204
+ currentSegmentText = text[i];
2205
+ currentIsMatch = isMatch;
2206
+ }
2207
+ else {
2208
+ currentSegmentText += text[i];
2209
+ }
2210
+ }
2211
+ // Push the last segment
2212
+ if (currentSegmentText.length > 0) {
2213
+ segments.push({ text: currentSegmentText, isMatch: currentIsMatch });
2214
+ }
2215
+ return segments;
2216
+ }
2217
+
2218
+ const MAX_WEAK_FUZZY_RESULTS = 3;
2219
+ const MIN_FUZZY_SCORE = 0.4;
2220
+ const MAX_FUZZY_SCORE = 0.84;
2221
+ {
2222
+ log.setLevel(log.levels.DEBUG); // Set log level to DEBUG for development/testing
2223
+ }
2224
+ const normalizeForComparison = (text) => {
2225
+ if (!text) {
2226
+ return '';
2227
+ }
2228
+ const normalized = text.toLowerCase().trim();
2229
+ return normalized;
2230
+ };
2231
+ function formatDisplayLabel(item) {
2232
+ if (item.occupation_name_preferred_label) {
2233
+ return `${item.preferred_label || ''} (${item.occupation_name_preferred_label})`;
2234
+ }
2235
+ return item.preferred_label || '';
2236
+ }
2237
+ /**
2238
+ * Job titles can appear once per related occupation, so the ID alone does not
2239
+ * identify a row. Compare ID and occupation, falling back to the raw label.
2240
+ */
2241
+ function isSameSearchResult(a, b) {
2242
+ if (a.id && b.id) {
2243
+ const occupationA = a.occupationId ?? a.occupation_name_id ?? '';
2244
+ const occupationB = b.occupationId ?? b.occupation_name_id ?? '';
2245
+ return a.id === b.id && occupationA === occupationB;
2246
+ }
2247
+ return a.rawLabel === b.rawLabel;
2248
+ }
2249
+ function sortResultsStrict(results) {
2250
+ return results.sort((a, b) => {
2251
+ const scoreA = a.score ?? 0;
2252
+ const scoreB = b.score ?? 0;
2253
+ if (scoreA !== scoreB) {
2254
+ return scoreB - scoreA;
2255
+ }
2256
+ const weightA = a.weight ?? 0;
2257
+ const weightB = b.weight ?? 0;
2258
+ if (weightA !== weightB) {
2259
+ return weightB - weightA;
2260
+ }
2261
+ return a.displayLabel.localeCompare(b.displayLabel, 'sv');
2262
+ });
2263
+ }
2264
+ function segmentsToHtml(segments) {
2265
+ return segments.map(seg => {
2266
+ if (seg.isMatch) {
2267
+ return `<strong>${seg.text}</strong>`;
2268
+ }
2269
+ if (seg.isMetadata) {
2270
+ return `<span class="occupation-variant-label">${seg.text}</span>`;
2271
+ }
2272
+ return seg.text;
2273
+ }).join('');
2274
+ }
2275
+ const styleParentheticalText = (text) => {
2276
+ if (!text)
2277
+ return '';
2278
+ return text.replace(/ (\([^)]+\))/g, ' <span class="occupation-variant-label">$1</span>');
2279
+ };
2280
+ function getDirectScore(normalizedLabel, normalizedQuery, searchTokens) {
2281
+ if (normalizedLabel === normalizedQuery) {
2282
+ return 1.0;
2283
+ }
2284
+ if (searchTokens.length > 1) {
2285
+ return searchTokens.every(token => normalizedLabel.includes(token)) ? 0.98 : null;
2286
+ }
2287
+ if (normalizedLabel.startsWith(normalizedQuery)) {
2288
+ return 0.99;
2289
+ }
2290
+ if (normalizedLabel.includes(normalizedQuery)) {
2291
+ return 0.95;
2292
+ }
2293
+ return null;
2294
+ }
2295
+ function calculateEditDistance(a, b) {
2296
+ const m = a.length;
2297
+ const n = b.length;
2298
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
2299
+ for (let i = 0; i <= m; i++)
2300
+ dp[i][0] = i;
2301
+ for (let j = 0; j <= n; j++)
2302
+ dp[0][j] = j;
2303
+ for (let i = 1; i <= m; i++) {
2304
+ for (let j = 1; j <= n; j++) {
2305
+ dp[i][j] = a[i - 1] === b[j - 1]
2306
+ ? dp[i - 1][j - 1]
2307
+ : 1 + Math.min(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1]);
2308
+ }
2309
+ }
2310
+ return dp[m][n];
2311
+ }
2312
+ function findBestFuzzySubstring(text, qToken) {
2313
+ const lowerText = text.toLowerCase();
2314
+ const targetLen = qToken.length;
2315
+ let bestDist = 99;
2316
+ const minLen = Math.max(3, targetLen - 2);
2317
+ const maxLen = Math.min(lowerText.length, targetLen + 2);
2318
+ for (let start = 0; start <= lowerText.length - minLen; start++) {
2319
+ for (let len = minLen; len <= maxLen && start + len <= lowerText.length; len++) {
2320
+ const sub = lowerText.slice(start, start + len);
2321
+ const dist = calculateEditDistance(qToken, sub);
2322
+ if (dist < bestDist) {
2323
+ bestDist = dist;
2324
+ }
2325
+ }
2326
+ }
2327
+ const maxAllowedDist = Math.max(2, Math.floor(targetLen * 0.25));
2328
+ return bestDist <= maxAllowedDist ? bestDist : null;
2329
+ }
2330
+ function isSingleWordOrCompoundRoot(query, label) {
2331
+ const normQ = query.toLowerCase().trim();
2332
+ const normL = label.toLowerCase().trim();
2333
+ if (normL.includes(' ')) {
2334
+ const dist = calculateEditDistance(normQ, normL);
2335
+ return dist <= Math.max(2, Math.floor(normQ.length * 0.25)) && Math.abs(normQ.length - normL.length) <= 2;
2336
+ }
2337
+ const subDist = findBestFuzzySubstring(normL, normQ);
2338
+ return subDist !== null;
2339
+ }
2340
+ // Canonical aliases (alternative/hidden labels from the taxonomy) only match
2341
+ // exactly; they never feed fuzzy search.
2342
+ function hasExactSearchAlias(item, normalizedQuery) {
2343
+ return (item.search_aliases ?? []).some((alias) => normalizeForComparison(alias) === normalizedQuery);
2344
+ }
2345
+ function createSearchResult(item, query, score) {
2346
+ const displayLabel = formatDisplayLabel(item);
2347
+ const displaySegments = LabelFormatter.format(item.preferred_label || '', query, item.occupation_name_preferred_label);
2348
+ return {
2349
+ id: item.id,
2350
+ type: item.type,
2351
+ preferred_label: item.preferred_label || '',
2352
+ rawLabel: item.preferred_label || '',
2353
+ displayLabel,
2354
+ highlightedLabel: segmentsToHtml(displaySegments),
2355
+ displaySegments,
2356
+ weight: item.weight ?? 0,
2357
+ score,
2358
+ occupationId: item.occupation_name_id,
2359
+ occupationLabel: item.occupation_name_preferred_label,
2360
+ ssyk_level_4_id: item.ssyk_level_4_id,
2361
+ ssyk_code_2012: item.ssyk_code_2012,
2362
+ };
2363
+ }
2364
+ function searchIdentity(item) {
2365
+ if (item.type === 'job-title') {
2366
+ return `${item.id}|${item.occupation_name_id ?? ''}`;
2367
+ }
2368
+ return item.id;
2369
+ }
2370
+ function searchConcepts(query, items, fuseInstance, maxResults) {
2371
+ if (!fuseInstance) {
2372
+ return [];
2373
+ }
2374
+ if (!items || !Array.isArray(items)) {
2375
+ log.warn('[searchConcepts] Ogiltig items array.');
2376
+ return [];
2377
+ }
2378
+ if (!query || query.length < MIN_INPUT_LENGTH) {
2379
+ return [];
2380
+ }
2381
+ const normalizedQuery = normalizeForComparison(query);
2382
+ const searchTokens = normalizedQuery.split(' ').filter(t => t.length > 0);
2383
+ const directResults = [];
2384
+ const processedIdentities = new Set();
2385
+ for (const item of items) {
2386
+ const normalizedLabel = normalizeForComparison(item.preferred_label);
2387
+ const preferredLabelScore = getDirectScore(normalizedLabel, normalizedQuery, searchTokens);
2388
+ const score = hasExactSearchAlias(item, normalizedQuery) ? 1.0 : preferredLabelScore;
2389
+ if (score !== null) {
2390
+ directResults.push(createSearchResult(item, query, score));
2391
+ processedIdentities.add(searchIdentity(item));
2392
+ }
2393
+ }
2394
+ if (directResults.length > 0) {
2395
+ return sortResultsStrict(directResults).slice(0, maxResults);
2396
+ }
2397
+ // Fuzzy is a pure fallback when there are no direct matches.
2398
+ if (fuseInstance) {
2399
+ const fuseSearchOutput = fuseInstance.search(normalizedQuery);
2400
+ if (fuseSearchOutput.length === 0) {
2401
+ return [];
2402
+ }
2403
+ const bestRawScore = fuseSearchOutput[0].score ?? 1.0;
2404
+ const candidateResults = [];
2405
+ let hasStrongRootMatch = false;
2406
+ for (const fr of fuseSearchOutput) {
2407
+ const identity = searchIdentity(fr.item);
2408
+ if (processedIdentities.has(identity)) {
2409
+ continue;
2410
+ }
2411
+ const rawScore = fr.score ?? 1.0;
2412
+ const baseFuzzyScore = 1 - rawScore;
2413
+ if (baseFuzzyScore < MIN_FUZZY_SCORE) {
2414
+ continue;
2415
+ }
2416
+ // Strict gap filter: never allow hits more than 0.12 raw-score worse than the best hit.
2417
+ if (rawScore > bestRawScore + 0.12) {
2418
+ continue;
2419
+ }
2420
+ const label = normalizeForComparison(fr.item.preferred_label);
2421
+ const weight = fr.item.weight ?? 0;
2422
+ const isRootMatch = isSingleWordOrCompoundRoot(normalizedQuery, label);
2423
+ if (isRootMatch && rawScore <= 0.25) {
2424
+ hasStrongRootMatch = true;
2425
+ }
2426
+ let score = baseFuzzyScore * 0.70 + (weight * 0.10);
2427
+ if (isRootMatch) {
2428
+ score += 0.12;
2429
+ }
2430
+ const boundedScore = Math.min(MAX_FUZZY_SCORE, Math.max(MIN_FUZZY_SCORE, score));
2431
+ candidateResults.push(createSearchResult(fr.item, query, boundedScore));
2432
+ processedIdentities.add(identity);
2433
+ }
2434
+ const sortedFuzzy = sortResultsStrict(candidateResults);
2435
+ if (sortedFuzzy.length === 0) {
2436
+ return [];
2437
+ }
2438
+ // Dynamic fuzzy result limit:
2439
+ // - strong root match: up to 5 relevant suggestions;
2440
+ // - weak/uncertain match: at most 3 suggestions.
2441
+ const limit = hasStrongRootMatch ? Math.min(5, maxResults) : Math.min(MAX_WEAK_FUZZY_RESULTS, maxResults);
2442
+ return sortedFuzzy.slice(0, limit);
2443
+ }
2444
+ return [];
2445
+ }
2446
+
2447
+ const TaxonomyAdapter = {
2448
+ /** Maps a raw TaxonomyItem to a GenericItem for the CoreSelector */
2449
+ toGenericItem(item) {
2450
+ return {
2451
+ id: item.id,
2452
+ label: item.preferred_label || '',
2453
+ description: item.occupation_name_preferred_label,
2454
+ metadata: {
2455
+ original: item,
2456
+ type: item.type,
2457
+ ssyk_level_4_id: item.ssyk_level_4_id,
2458
+ weight: item.weight
2459
+ }
2460
+ };
2461
+ },
2462
+ /** Maps a SearchResult (from our engine) to a GenericItem */
2463
+ searchResultToGenericItem(result, query) {
2464
+ const segments = LabelFormatter.format(result.preferred_label || '', query, result.occupation_name_preferred_label);
2465
+ return {
2466
+ id: result.id,
2467
+ label: result.preferred_label || '',
2468
+ displaySegments: segments,
2469
+ highlightedLabel: segmentsToHtml(segments),
2470
+ metadata: {
2471
+ original: result,
2472
+ ssyk_level_4_id: result.ssyk_level_4_id,
2473
+ weight: result.weight
2474
+ }
2475
+ };
2476
+ },
2477
+ /** Maps a GenericItem back to our internal SearchResult format */
2478
+ fromGenericItem(item) {
2479
+ return {
2480
+ id: item.id,
2481
+ preferred_label: item.label,
2482
+ weight: item.metadata?.weight,
2483
+ ...item.metadata?.original
2484
+ };
2485
+ },
2486
+ /** Maps an internal item to the public event format */
2487
+ toPublicSelection(item) {
2488
+ const id = item.id || '';
2489
+ const preferredLabel = item.preferred_label || item.rawLabel || '';
2490
+ if (!id) {
2491
+ return {
2492
+ type: 'manual-input',
2493
+ id: null,
2494
+ preferred_label: preferredLabel,
2495
+ };
2496
+ }
2497
+ if (item.type !== 'job-title' && item.type !== 'occupation-name') {
2498
+ throw new Error(`Ogiltig intern yrkestyp för ${id}: ${item.type}`);
2499
+ }
2500
+ const selection = {
2501
+ type: item.type,
2502
+ id,
2503
+ preferred_label: preferredLabel,
2504
+ };
2505
+ if (item.ssyk_code_2012) {
2506
+ selection.ssyk_code_2012 = item.ssyk_code_2012;
2507
+ }
2508
+ const occupationId = item.occupation_name_id || item.occupationId;
2509
+ const occupationLabel = item.occupation_name_preferred_label || item.occupationLabel;
2510
+ if (item.type === 'job-title' && occupationId && occupationLabel) {
2511
+ selection.related = {
2512
+ type: 'occupation-name',
2513
+ id: occupationId,
2514
+ preferred_label: occupationLabel,
2515
+ };
2516
+ }
2517
+ return selection;
2518
+ }
2519
+ };
2520
+
2521
+ class TaxonomySearchEngine {
2522
+ fuseInstance = null;
2523
+ items = [];
2524
+ constructor(data) {
2525
+ this.items = data;
2526
+ this.fuseInstance = new entry_default(data, FUSE_OPTIONS);
2527
+ }
2528
+ /**
2529
+ * Public API: Performs a search and returns clean, official domain objects.
2530
+ * This is what external consumers (headless) should use.
2531
+ */
2532
+ search(query, maxResults = 20) {
2533
+ if (!this.fuseInstance)
2534
+ return [];
2535
+ const results = searchConcepts(query, this.items, this.fuseInstance, maxResults);
2536
+ // Map directly to public selection objects
2537
+ return results.map(result => TaxonomyAdapter.toPublicSelection(result));
2538
+ }
2539
+ /**
2540
+ * Internal API: Performs a search and returns GenericItems for the CoreSelector UI ("Bucky").
2541
+ * Includes highlighting, grouping and internal metadata.
2542
+ */
2543
+ searchAsGeneric(query, maxResults = 20) {
2544
+ if (!this.fuseInstance)
2545
+ return [];
2546
+ // Use the existing robust search function
2547
+ const results = searchConcepts(query, this.items, this.fuseInstance, maxResults);
2548
+ // Adapt SearchResult -> GenericItem
2549
+ return results.map(result => ({
2550
+ id: result.id,
2551
+ label: result.displayLabel, // Use the formatted label (e.g. "Nurse (Healthcare)")
2552
+ description: result.occupationLabel,
2553
+ group: result.type === 'job-title' ? 'Yrke' : 'Yrkesgrupp',
2554
+ metadata: {
2555
+ originalResult: result, // Keep full original result for consumers
2556
+ highlightedLabel: result.highlightedLabel,
2557
+ score: result.score,
2558
+ weight: result.weight
2559
+ }
2560
+ }));
2561
+ }
2562
+ updateData(newData) {
2563
+ this.items = newData;
2564
+ this.fuseInstance = new entry_default(newData, FUSE_OPTIONS);
2565
+ }
2566
+ }
2567
+
2568
+ class InvalidSelectionError extends Error {
2569
+ code;
2570
+ invalidIds;
2571
+ constructor(message, code, invalidIds) {
2572
+ super(message);
2573
+ this.name = 'InvalidSelectionError';
2574
+ this.code = code;
2575
+ this.invalidIds = invalidIds;
2576
+ }
2577
+ }
2578
+
2579
+ exports.DEBOUNCE_TIME = DEBOUNCE_TIME;
2580
+ exports.InvalidSelectionError = InvalidSelectionError;
2581
+ exports.LabelFormatter = LabelFormatter;
2582
+ exports.MAX_RESULTS = MAX_RESULTS;
2583
+ exports.MIN_INPUT_LENGTH = MIN_INPUT_LENGTH;
2584
+ exports.PLACEHOLDER_TEXT = PLACEHOLDER_TEXT;
2585
+ exports.TaxonomyAdapter = TaxonomyAdapter;
2586
+ exports.TaxonomySearchEngine = TaxonomySearchEngine;
2587
+ exports.getRegisteredTaxonomy = getRegisteredTaxonomy;
2588
+ exports.isSameSearchResult = isSameSearchResult;
2589
+ exports.isTaxonomyRegistration = isTaxonomyRegistration;
2590
+ exports.log = log;
2591
+ exports.registerTaxonomy = registerTaxonomy;
2592
+ exports.segmentsToHtml = segmentsToHtml;
2593
+ exports.styleParentheticalText = styleParentheticalText;