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