@kubik-cms/interface_elements 0.1.11 → 0.1.14

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.
Binary file
package/.yarnrc.yml ADDED
@@ -0,0 +1,8 @@
1
+ approvedGitRepositories:
2
+ - "**"
3
+
4
+ enableScripts: true
5
+
6
+ nodeLinker: node-modules
7
+
8
+ npmMinimalAgeGate: 0
@@ -1,370 +1,29 @@
1
- function camelize(value) {
2
- return value.replace(/(?:[_-])([a-z0-9])/g, (_, char) => char.toUpperCase());
3
- }
4
- function capitalize(value) {
5
- return value.charAt(0).toUpperCase() + value.slice(1);
6
- }
7
- function dasherize(value) {
8
- return value.replace(/([A-Z])/g, (_, char) => `-${char.toLowerCase()}`);
9
- }
10
- function readInheritableStaticArrayValues(constructor, propertyName) {
11
- const ancestors = getAncestorsForConstructor(constructor);
12
- return Array.from(ancestors.reduce((values, constructor2) => {
13
- getOwnStaticArrayValues(constructor2, propertyName).forEach((name) => values.add(name));
14
- return values;
15
- }, /* @__PURE__ */ new Set()));
16
- }
17
- function readInheritableStaticObjectPairs(constructor, propertyName) {
18
- const ancestors = getAncestorsForConstructor(constructor);
19
- return ancestors.reduce((pairs, constructor2) => {
20
- pairs.push(...getOwnStaticObjectPairs(constructor2, propertyName));
21
- return pairs;
22
- }, []);
23
- }
24
- function getAncestorsForConstructor(constructor) {
25
- const ancestors = [];
26
- while (constructor) {
27
- ancestors.push(constructor);
28
- constructor = Object.getPrototypeOf(constructor);
29
- }
30
- return ancestors.reverse();
31
- }
32
- function getOwnStaticArrayValues(constructor, propertyName) {
33
- const definition = constructor[propertyName];
34
- return Array.isArray(definition) ? definition : [];
35
- }
36
- function getOwnStaticObjectPairs(constructor, propertyName) {
37
- const definition = constructor[propertyName];
38
- return definition ? Object.keys(definition).map((key) => [key, definition[key]]) : [];
39
- }
40
- (() => {
41
- function extendWithReflect(constructor) {
42
- function extended() {
43
- return Reflect.construct(constructor, arguments, new.target);
44
- }
45
- extended.prototype = Object.create(constructor.prototype, {
46
- constructor: { value: extended }
47
- });
48
- Reflect.setPrototypeOf(extended, constructor);
49
- return extended;
50
- }
51
- function testReflectExtension() {
52
- const a = function() {
53
- this.a.call(this);
54
- };
55
- const b = extendWithReflect(a);
56
- b.prototype.a = function() {
57
- };
58
- return new b();
59
- }
60
- try {
61
- testReflectExtension();
62
- return extendWithReflect;
63
- } catch (error) {
64
- return (constructor) => class extended extends constructor {
65
- };
66
- }
67
- })();
68
- function ClassPropertiesBlessing(constructor) {
69
- const classes = readInheritableStaticArrayValues(constructor, "classes");
70
- return classes.reduce((properties, classDefinition) => {
71
- return Object.assign(properties, propertiesForClassDefinition(classDefinition));
72
- }, {});
73
- }
74
- function propertiesForClassDefinition(key) {
75
- return {
76
- [`${key}Class`]: {
77
- get() {
78
- const { classes } = this;
79
- if (classes.has(key)) {
80
- return classes.get(key);
81
- } else {
82
- const attribute = classes.getAttributeName(key);
83
- throw new Error(`Missing attribute "${attribute}"`);
84
- }
85
- }
86
- },
87
- [`${key}Classes`]: {
88
- get() {
89
- return this.classes.getAll(key);
90
- }
91
- },
92
- [`has${capitalize(key)}Class`]: {
93
- get() {
94
- return this.classes.has(key);
95
- }
96
- }
97
- };
98
- }
99
- function TargetPropertiesBlessing(constructor) {
100
- const targets = readInheritableStaticArrayValues(constructor, "targets");
101
- return targets.reduce((properties, targetDefinition) => {
102
- return Object.assign(properties, propertiesForTargetDefinition(targetDefinition));
103
- }, {});
104
- }
105
- function propertiesForTargetDefinition(name) {
106
- return {
107
- [`${name}Target`]: {
108
- get() {
109
- const target = this.targets.find(name);
110
- if (target) {
111
- return target;
112
- } else {
113
- throw new Error(`Missing target element "${name}" for "${this.identifier}" controller`);
114
- }
115
- }
116
- },
117
- [`${name}Targets`]: {
118
- get() {
119
- return this.targets.findAll(name);
120
- }
121
- },
122
- [`has${capitalize(name)}Target`]: {
123
- get() {
124
- return this.targets.has(name);
125
- }
126
- }
127
- };
128
- }
129
- function ValuePropertiesBlessing(constructor) {
130
- const valueDefinitionPairs = readInheritableStaticObjectPairs(constructor, "values");
131
- const propertyDescriptorMap = {
132
- valueDescriptorMap: {
133
- get() {
134
- return valueDefinitionPairs.reduce((result, valueDefinitionPair) => {
135
- const valueDescriptor = parseValueDefinitionPair(valueDefinitionPair, this.identifier);
136
- const attributeName = this.data.getAttributeNameForKey(valueDescriptor.key);
137
- return Object.assign(result, { [attributeName]: valueDescriptor });
138
- }, {});
139
- }
140
- }
141
- };
142
- return valueDefinitionPairs.reduce((properties, valueDefinitionPair) => {
143
- return Object.assign(properties, propertiesForValueDefinitionPair(valueDefinitionPair));
144
- }, propertyDescriptorMap);
145
- }
146
- function propertiesForValueDefinitionPair(valueDefinitionPair, controller) {
147
- const definition = parseValueDefinitionPair(valueDefinitionPair, controller);
148
- const { key, name, reader: read, writer: write } = definition;
149
- return {
150
- [name]: {
151
- get() {
152
- const value = this.data.get(key);
153
- if (value !== null) {
154
- return read(value);
155
- } else {
156
- return definition.defaultValue;
157
- }
158
- },
159
- set(value) {
160
- if (value === void 0) {
161
- this.data.delete(key);
162
- } else {
163
- this.data.set(key, write(value));
164
- }
165
- }
166
- },
167
- [`has${capitalize(name)}`]: {
168
- get() {
169
- return this.data.has(key) || definition.hasCustomDefaultValue;
170
- }
171
- }
172
- };
173
- }
174
- function parseValueDefinitionPair([token, typeDefinition], controller) {
175
- return valueDescriptorForTokenAndTypeDefinition({
176
- controller,
177
- token,
178
- typeDefinition
179
- });
180
- }
181
- function parseValueTypeConstant(constant) {
182
- switch (constant) {
183
- case Array:
184
- return "array";
185
- case Boolean:
186
- return "boolean";
187
- case Number:
188
- return "number";
189
- case Object:
190
- return "object";
191
- case String:
192
- return "string";
193
- }
194
- }
195
- function parseValueTypeDefault(defaultValue) {
196
- switch (typeof defaultValue) {
197
- case "boolean":
198
- return "boolean";
199
- case "number":
200
- return "number";
201
- case "string":
202
- return "string";
203
- }
204
- if (Array.isArray(defaultValue))
205
- return "array";
206
- if (Object.prototype.toString.call(defaultValue) === "[object Object]")
207
- return "object";
208
- }
209
- function parseValueTypeObject(payload) {
210
- const typeFromObject = parseValueTypeConstant(payload.typeObject.type);
211
- if (!typeFromObject)
212
- return;
213
- const defaultValueType = parseValueTypeDefault(payload.typeObject.default);
214
- if (typeFromObject !== defaultValueType) {
215
- const propertyPath = payload.controller ? `${payload.controller}.${payload.token}` : payload.token;
216
- throw new Error(`The specified default value for the Stimulus Value "${propertyPath}" must match the defined type "${typeFromObject}". The provided default value of "${payload.typeObject.default}" is of type "${defaultValueType}".`);
217
- }
218
- return typeFromObject;
219
- }
220
- function parseValueTypeDefinition(payload) {
221
- const typeFromObject = parseValueTypeObject({
222
- controller: payload.controller,
223
- token: payload.token,
224
- typeObject: payload.typeDefinition
225
- });
226
- const typeFromDefaultValue = parseValueTypeDefault(payload.typeDefinition);
227
- const typeFromConstant = parseValueTypeConstant(payload.typeDefinition);
228
- const type = typeFromObject || typeFromDefaultValue || typeFromConstant;
229
- if (type)
230
- return type;
231
- const propertyPath = payload.controller ? `${payload.controller}.${payload.typeDefinition}` : payload.token;
232
- throw new Error(`Unknown value type "${propertyPath}" for "${payload.token}" value`);
233
- }
234
- function defaultValueForDefinition(typeDefinition) {
235
- const constant = parseValueTypeConstant(typeDefinition);
236
- if (constant)
237
- return defaultValuesByType[constant];
238
- const defaultValue = typeDefinition.default;
239
- if (defaultValue !== void 0)
240
- return defaultValue;
241
- return typeDefinition;
242
- }
243
- function valueDescriptorForTokenAndTypeDefinition(payload) {
244
- const key = `${dasherize(payload.token)}-value`;
245
- const type = parseValueTypeDefinition(payload);
246
- return {
247
- type,
248
- key,
249
- name: camelize(key),
250
- get defaultValue() {
251
- return defaultValueForDefinition(payload.typeDefinition);
252
- },
253
- get hasCustomDefaultValue() {
254
- return parseValueTypeDefault(payload.typeDefinition) !== void 0;
255
- },
256
- reader: readers[type],
257
- writer: writers[type] || writers.default
258
- };
259
- }
260
- const defaultValuesByType = {
261
- get array() {
262
- return [];
263
- },
264
- boolean: false,
265
- number: 0,
266
- get object() {
267
- return {};
268
- },
269
- string: ""
270
- };
271
- const readers = {
272
- array(value) {
273
- const array = JSON.parse(value);
274
- if (!Array.isArray(array)) {
275
- throw new TypeError(`expected value of type "array" but instead got value "${value}" of type "${parseValueTypeDefault(array)}"`);
276
- }
277
- return array;
278
- },
279
- boolean(value) {
280
- return !(value == "0" || String(value).toLowerCase() == "false");
281
- },
282
- number(value) {
283
- return Number(value);
284
- },
285
- object(value) {
286
- const object = JSON.parse(value);
287
- if (object === null || typeof object != "object" || Array.isArray(object)) {
288
- throw new TypeError(`expected value of type "object" but instead got value "${value}" of type "${parseValueTypeDefault(object)}"`);
289
- }
290
- return object;
291
- },
292
- string(value) {
293
- return value;
294
- }
295
- };
296
- const writers = {
297
- default: writeString,
298
- array: writeJSON,
299
- object: writeJSON
300
- };
301
- function writeJSON(value) {
302
- return JSON.stringify(value);
303
- }
304
- function writeString(value) {
305
- return `${value}`;
306
- }
307
- class Controller {
308
- constructor(context) {
309
- this.context = context;
310
- }
311
- static get shouldLoad() {
312
- return true;
313
- }
314
- get application() {
315
- return this.context.application;
316
- }
317
- get scope() {
318
- return this.context.scope;
319
- }
320
- get element() {
321
- return this.scope.element;
322
- }
323
- get identifier() {
324
- return this.scope.identifier;
325
- }
326
- get targets() {
327
- return this.scope.targets;
328
- }
329
- get classes() {
330
- return this.scope.classes;
331
- }
332
- get data() {
333
- return this.scope.data;
334
- }
335
- initialize() {
336
- }
337
- connect() {
338
- }
339
- disconnect() {
340
- }
341
- dispatch(eventName, { target = this.element, detail = {}, prefix = this.identifier, bubbles = true, cancelable = true } = {}) {
342
- const type = prefix ? `${prefix}:${eventName}` : eventName;
343
- const event = new CustomEvent(type, { detail, bubbles, cancelable });
344
- target.dispatchEvent(event);
345
- return event;
346
- }
347
- }
348
- Controller.blessings = [ClassPropertiesBlessing, TargetPropertiesBlessing, ValuePropertiesBlessing];
349
- Controller.targets = [];
350
- Controller.values = {};
351
- class modal_controller_default extends Controller {
352
- initialize() {
353
- document.head.insertAdjacentHTML(
354
- "beforeend",
355
- `<template id='kubik-modal-template' data-kubik-modal-target='modalTemplate'>
356
- <div id='kubik-modal' class='kubik-modal-element' data-kubik-modal-target='modalContainer'>
357
- <div class='kubik-modal-background' data-action='click->kubik-modal#closeModal'>
358
- </div>
1
+ import { Controller } from "@hotwired/stimulus";
2
+ const DEFAULT_MODAL_FRAME_ID = "kubik_modal_frame";
3
+ function modalTemplateHtml(frameId = DEFAULT_MODAL_FRAME_ID) {
4
+ return `
5
+ <template id='kubik-modal-template' data-kubik-modal-target='modalTemplate'>
6
+ <div id='kubik-modal' data-turbo-permanent class='kubik-modal-element' data-kubik-modal-target='modalContainer'>
7
+ <div class='kubik-modal-background' data-action='click->kubik-modal#closeModal'>
8
+ </div>
359
9
  <div class='kubik-modal-element-window'>
360
- <div data-kubik-modal-target='modalHeader' class='h4 kubik-modal-title-bar'>Test header</div>
361
- <turbo-frame id='media_library_frame' class='kubik-modal-element-content' data-kubik-modal-target='modalFrame'>
10
+ <div data-kubik-modal-target='modalHeader' class='h4 kubik-modal-title-bar'></div>
11
+ <turbo-frame id='${frameId}' class='kubik-modal-element-content' data-kubik-modal-target='modalFrame'>
362
12
  </turbo-frame>
363
13
  </div>
364
14
  </div>
365
15
  </template>
366
- `
367
- );
16
+ `;
17
+ }
18
+ class modal_controller_default extends Controller {
19
+ constructor() {
20
+ super(...arguments);
21
+ this.onTurboLoad = () => {
22
+ this._renderDOMElements();
23
+ };
24
+ }
25
+ initialize() {
26
+ document.head.insertAdjacentHTML("beforeend", modalTemplateHtml(DEFAULT_MODAL_FRAME_ID));
368
27
  }
369
28
  connect() {
370
29
  this._renderDOMElements();
@@ -373,6 +32,10 @@ class modal_controller_default extends Controller {
373
32
  this.closeModal();
374
33
  }
375
34
  });
35
+ document.addEventListener("turbo:load", this.onTurboLoad);
36
+ }
37
+ disconnect() {
38
+ document.removeEventListener("turbo:load", this.onTurboLoad);
376
39
  }
377
40
  get modalTemplate() {
378
41
  return this.modalTemplateTarget.innerHTML;
@@ -429,7 +92,12 @@ class modal_controller_default extends Controller {
429
92
  }
430
93
  }
431
94
  openModal(e) {
95
+ this._renderDOMElements();
432
96
  const target = e.currentTarget;
97
+ const frameId = target.dataset.kubikModalFrameId || DEFAULT_MODAL_FRAME_ID;
98
+ if (this.hasModalFrameTarget && this.modalFrameTarget.id !== frameId) {
99
+ this.modalFrameTarget.id = frameId;
100
+ }
433
101
  this.modalSrcValue = target.getAttribute("src");
434
102
  this.modalHeaderValue = target.dataset.kubikModalHeaderText;
435
103
  this.modalActionValue = target.dataset.kubikModalAction;
@@ -469,9 +137,707 @@ modal_controller_default.values = {
469
137
  modalReturnPayload: { type: Object, default: {} },
470
138
  modalReturnController: { type: String, default: "" }
471
139
  };
140
+ const OFFCANVAS_FRAME_ID = "kubik_offcanvas_frame";
141
+ class offcanvas_controller_default extends Controller {
142
+ constructor() {
143
+ super(...arguments);
144
+ this.handleKeydown = (event) => {
145
+ if (event.key === "Escape")
146
+ this.closeOffcanvas();
147
+ };
148
+ this.handleFrameLoad = () => {
149
+ this.clearLoadingState();
150
+ };
151
+ this.handleFrameMissing = () => {
152
+ this.clearLoadingState();
153
+ };
154
+ }
155
+ initialize() {
156
+ document.head.insertAdjacentHTML(
157
+ "beforeend",
158
+ `<template id='kubik-offcanvas-template' data-kubik-offcanvas-target='offcanvasTemplate'>
159
+ <div id='kubik-offcanvas' class='kubik-offcanvas' data-kubik-offcanvas-target='offcanvasContainer' aria-hidden='true'>
160
+ <div class='kubik-offcanvas-backdrop' data-action='click->kubik-offcanvas#closeOffcanvas'></div>
161
+ <div class='kubik-offcanvas-panel kubik-offcanvas-panel--end' data-kubik-offcanvas-target='offcanvasPanel' role='dialog' aria-modal='true'>
162
+ <div class='kubik-offcanvas-header'>
163
+ <div data-kubik-offcanvas-target='offcanvasHeader' class='kubik-offcanvas-title'></div>
164
+ <button type='button' class='kubik-offcanvas-close' aria-label='Close' data-action='click->kubik-offcanvas#closeOffcanvas'>
165
+ <span class='material-symbols-outlined material-icon'>close</span>
166
+ </button>
167
+ </div>
168
+ <div class='kubik-offcanvas-body'>
169
+ <turbo-frame id='${OFFCANVAS_FRAME_ID}' class='kubik-offcanvas-content' data-kubik-offcanvas-target='offcanvasFrame'></turbo-frame>
170
+ </div>
171
+ </div>
172
+ </div>
173
+ </template>`
174
+ );
175
+ }
176
+ connect() {
177
+ this._renderDOMElements();
178
+ document.addEventListener("keydown", this.handleKeydown);
179
+ if (this.hasOffcanvasFrameTarget) {
180
+ this.offcanvasFrameTarget.addEventListener("turbo:frame-load", this.handleFrameLoad);
181
+ this.offcanvasFrameTarget.addEventListener("turbo:frame-missing", this.handleFrameMissing);
182
+ }
183
+ }
184
+ disconnect() {
185
+ document.removeEventListener("keydown", this.handleKeydown);
186
+ if (this.hasOffcanvasFrameTarget) {
187
+ this.offcanvasFrameTarget.removeEventListener("turbo:frame-load", this.handleFrameLoad);
188
+ this.offcanvasFrameTarget.removeEventListener("turbo:frame-missing", this.handleFrameMissing);
189
+ }
190
+ }
191
+ get offcanvasTemplate() {
192
+ return this.offcanvasTemplateTarget.innerHTML;
193
+ }
194
+ offcanvasStatusValueChanged() {
195
+ if (!this.hasOffcanvasContainerTarget)
196
+ return;
197
+ const open = this.offcanvasStatusValue === "opened";
198
+ this.offcanvasContainerTarget.classList.toggle("kubik-offcanvas--open", open);
199
+ this.offcanvasContainerTarget.setAttribute("aria-hidden", open ? "false" : "true");
200
+ document.body.classList.toggle("kubik-offcanvas-open", open);
201
+ if (this.hasOffcanvasPanelTarget) {
202
+ this.offcanvasPanelTarget.classList.remove(
203
+ "kubik-offcanvas-panel--start",
204
+ "kubik-offcanvas-panel--end"
205
+ );
206
+ const position = this.offcanvasPositionValue === "start" ? "start" : "end";
207
+ this.offcanvasPanelTarget.classList.add(`kubik-offcanvas-panel--${position}`);
208
+ this.offcanvasPanelTarget.classList.remove(
209
+ "kubik-offcanvas-panel--tone-white",
210
+ "kubik-offcanvas-panel--tone-grey"
211
+ );
212
+ const tone = this.offcanvasToneValue === "white" ? "white" : "grey";
213
+ this.offcanvasPanelTarget.classList.add(`kubik-offcanvas-panel--tone-${tone}`);
214
+ }
215
+ if (!open)
216
+ this.clearOffcanvasContent();
217
+ }
218
+ offcanvasSrcValueChanged() {
219
+ if (!this.hasOffcanvasFrameTarget)
220
+ return;
221
+ if (this.offcanvasSrcValue === "") {
222
+ this.offcanvasFrameTarget.removeAttribute("src");
223
+ this.offcanvasFrameTarget.innerHTML = "";
224
+ return;
225
+ }
226
+ this.showLoadingState();
227
+ this.offcanvasFrameTarget.setAttribute("src", this.offcanvasSrcValue);
228
+ }
229
+ offcanvasHeaderValueChanged() {
230
+ if (this.hasOffcanvasHeaderTarget) {
231
+ this.offcanvasHeaderTarget.textContent = this.offcanvasHeaderValue;
232
+ }
233
+ }
234
+ openOffcanvas(event) {
235
+ const target = event.currentTarget;
236
+ const src = target.getAttribute("src") || target.getAttribute("href") || target.dataset.kubikOffcanvasSrc || "";
237
+ this.offcanvasPositionValue = target.dataset.kubikOffcanvasPosition || this.offcanvasPositionValue;
238
+ this.offcanvasHeaderValue = target.dataset.kubikOffcanvasHeaderText || "";
239
+ this.offcanvasToneValue = target.dataset.kubikOffcanvasTone || "grey";
240
+ this.offcanvasSrcValue = src;
241
+ this.offcanvasStatusValue = "opened";
242
+ }
243
+ closeOffcanvas() {
244
+ this.offcanvasStatusValue = "closed";
245
+ this.offcanvasSrcValue = "";
246
+ this.offcanvasHeaderValue = "";
247
+ this.offcanvasToneValue = "grey";
248
+ }
249
+ offcanvasFrameTargetDisconnected() {
250
+ if (this.offcanvasStatusValue === "opened")
251
+ this.closeOffcanvas();
252
+ }
253
+ showLoadingState() {
254
+ if (!this.hasOffcanvasFrameTarget)
255
+ return;
256
+ this.offcanvasFrameTarget.innerHTML = `
257
+ <div class="kubik-offcanvas-loading" aria-live="polite" role="status">
258
+ <span class="material-symbols-outlined material-icon kubik-offcanvas-loading__spinner">progress_activity</span>
259
+ <span class="kubik-offcanvas-loading__text">Loading\u2026</span>
260
+ </div>
261
+ `;
262
+ }
263
+ clearLoadingState() {
264
+ var _a;
265
+ const loading = (_a = this.offcanvasFrameTarget) == null ? void 0 : _a.querySelector(".kubik-offcanvas-loading");
266
+ if (loading)
267
+ loading.remove();
268
+ }
269
+ clearOffcanvasContent() {
270
+ if (!this.hasOffcanvasFrameTarget)
271
+ return;
272
+ this.offcanvasFrameTarget.removeAttribute("src");
273
+ this.offcanvasFrameTarget.innerHTML = "";
274
+ }
275
+ _renderDOMElements() {
276
+ if (!document.getElementById("kubik-offcanvas")) {
277
+ document.body.insertAdjacentHTML("beforeend", this.offcanvasTemplate);
278
+ }
279
+ }
280
+ }
281
+ offcanvas_controller_default.targets = [
282
+ "offcanvasTemplate",
283
+ "offcanvasContainer",
284
+ "offcanvasPanel",
285
+ "offcanvasFrame",
286
+ "offcanvasHeader"
287
+ ];
288
+ offcanvas_controller_default.values = {
289
+ offcanvasHeader: { type: String, default: "" },
290
+ offcanvasStatus: { type: String, default: "closed" },
291
+ offcanvasSrc: { type: String, default: "" },
292
+ offcanvasPosition: { type: String, default: "end" },
293
+ offcanvasTone: { type: String, default: "grey" }
294
+ };
295
+ class typeahead_controller_default extends Controller {
296
+ constructor() {
297
+ super(...arguments);
298
+ this.debounceTimer = null;
299
+ this.fetchAbort = null;
300
+ this.filteredOptions = [];
301
+ this.resultElements = [];
302
+ this.onResultsMouseDownHandler = (event) => this.onResultsMouseDown(event);
303
+ }
304
+ connect() {
305
+ this.resultsListTarget.addEventListener("mousedown", this.onResultsMouseDownHandler);
306
+ this.inputTarget.setAttribute("role", "combobox");
307
+ this.inputTarget.setAttribute("aria-autocomplete", "list");
308
+ this.inputTarget.setAttribute("aria-expanded", "false");
309
+ this.close();
310
+ }
311
+ disconnect() {
312
+ this.resultsListTarget.removeEventListener("mousedown", this.onResultsMouseDownHandler);
313
+ this.clearDebounce();
314
+ this.abortFetch();
315
+ }
316
+ onInput() {
317
+ this.clearDebounce();
318
+ if (this.debounceMsValue <= 0) {
319
+ this.refreshResults();
320
+ return;
321
+ }
322
+ this.debounceTimer = setTimeout(() => this.refreshResults(), this.debounceMsValue);
323
+ }
324
+ onFocus() {
325
+ if (this.queryMeetsMinLength() && this.resultElements.length > 0) {
326
+ this.open();
327
+ }
328
+ }
329
+ excludeValuesValueChanged() {
330
+ if (this.queryMeetsMinLength()) {
331
+ this.refreshResults();
332
+ }
333
+ }
334
+ onBlur() {
335
+ window.setTimeout(() => {
336
+ if (!this.element.contains(document.activeElement)) {
337
+ this.close();
338
+ }
339
+ }, 150);
340
+ }
341
+ keydown(event) {
342
+ switch (event.key) {
343
+ case "ArrowDown":
344
+ if (this.resultElements.length === 0 && this.queryMeetsMinLength()) {
345
+ this.refreshResults();
346
+ }
347
+ if (this.resultElements.length > 0) {
348
+ event.preventDefault();
349
+ this.moveActive(1);
350
+ }
351
+ break;
352
+ case "ArrowUp":
353
+ if (this.resultElements.length > 0) {
354
+ event.preventDefault();
355
+ this.moveActive(-1);
356
+ }
357
+ break;
358
+ case "Enter":
359
+ if (!Number.isNaN(this.resultActiveValue) && this.resultElements[this.resultActiveValue]) {
360
+ event.preventDefault();
361
+ this.selectResult(this.resultElements[this.resultActiveValue]);
362
+ }
363
+ break;
364
+ case "Escape":
365
+ event.preventDefault();
366
+ this.close();
367
+ break;
368
+ }
369
+ }
370
+ resultActiveValueChanged() {
371
+ this.resultElements.forEach((result) => {
372
+ if (this.hasActiveResultClass)
373
+ result.classList.remove(this.activeResultClass);
374
+ });
375
+ if (!Number.isNaN(this.resultActiveValue) && this.resultElements[this.resultActiveValue]) {
376
+ if (this.hasActiveResultClass) {
377
+ this.resultElements[this.resultActiveValue].classList.add(this.activeResultClass);
378
+ }
379
+ this.inputTarget.setAttribute("aria-activedescendant", this.resultElements[this.resultActiveValue].id);
380
+ } else {
381
+ this.inputTarget.removeAttribute("aria-activedescendant");
382
+ }
383
+ }
384
+ onResultsMouseDown(event) {
385
+ const target = event.target.closest(".kubik-interface-typeahead__option");
386
+ if (!target)
387
+ return;
388
+ event.preventDefault();
389
+ this.selectResult(target);
390
+ }
391
+ refreshResults() {
392
+ if (!this.queryMeetsMinLength()) {
393
+ this.renderResults([]);
394
+ return;
395
+ }
396
+ const query = this.inputTarget.value.trim();
397
+ if (this.srcValue) {
398
+ this.fetchRemote(query);
399
+ } else {
400
+ this.filteredOptions = this.filterStaticOptions(query);
401
+ this.renderResults(this.filteredOptions);
402
+ }
403
+ }
404
+ filterStaticOptions(query) {
405
+ const normalized = query.toLowerCase();
406
+ return this.withoutExcluded(
407
+ this.normalizeOptions(this.optionsValue).filter((option) => option.label.toLowerCase().includes(normalized))
408
+ ).slice(0, this.maxResultsValue);
409
+ }
410
+ normalizeOptions(raw) {
411
+ return raw.map((entry) => {
412
+ if (typeof entry === "string") {
413
+ return { label: entry, value: entry };
414
+ }
415
+ if (entry && typeof entry === "object") {
416
+ const object = entry;
417
+ const label = object.label || object.name || object.value || "";
418
+ const value = object.value || object.label || object.name || "";
419
+ return { label: String(label), value: String(value) };
420
+ }
421
+ return { label: "", value: "" };
422
+ }).filter((option) => option.label !== "");
423
+ }
424
+ withoutExcluded(options) {
425
+ if (this.excludeValuesValue.length === 0)
426
+ return options;
427
+ const excluded = new Set(
428
+ this.excludeValuesValue.map((value) => value.toLowerCase().trim()).filter((value) => value !== "")
429
+ );
430
+ return options.filter((option) => {
431
+ const value = option.value.toLowerCase().trim();
432
+ const label = option.label.toLowerCase().trim();
433
+ return !excluded.has(value) && !excluded.has(label);
434
+ });
435
+ }
436
+ fetchRemote(query) {
437
+ this.abortFetch();
438
+ this.fetchAbort = new AbortController();
439
+ const url = new URL(this.srcValue, window.location.origin);
440
+ url.searchParams.set(this.paramNameValue, query);
441
+ if (this.hasFeedbackTarget) {
442
+ this.feedbackTarget.textContent = "Loading...";
443
+ }
444
+ fetch(url.toString(), {
445
+ headers: { Accept: "application/json" },
446
+ signal: this.fetchAbort.signal
447
+ }).then((response) => response.json()).then((payload) => {
448
+ const list = Array.isArray(payload) ? payload : [];
449
+ this.filteredOptions = this.withoutExcluded(this.normalizeOptions(list)).slice(0, this.maxResultsValue);
450
+ this.renderResults(this.filteredOptions);
451
+ if (this.hasFeedbackTarget) {
452
+ this.feedbackTarget.textContent = "";
453
+ }
454
+ }).catch(() => {
455
+ if (this.hasFeedbackTarget) {
456
+ this.feedbackTarget.textContent = "";
457
+ }
458
+ this.renderResults([]);
459
+ });
460
+ }
461
+ renderResults(options) {
462
+ this.resultsListTarget.innerHTML = "";
463
+ this.resultElements = [];
464
+ this.resultActiveValue = NaN;
465
+ options.forEach((option, index) => {
466
+ const item = document.createElement("li");
467
+ item.id = `${this.inputTarget.id || "typeahead"}_option_${index}`;
468
+ item.className = "kubik-interface-typeahead__option";
469
+ item.dataset.index = String(index);
470
+ item.dataset.value = option.value;
471
+ item.dataset.label = option.label;
472
+ item.setAttribute("role", "option");
473
+ item.textContent = option.label;
474
+ item.addEventListener("mouseover", () => {
475
+ this.resultActiveValue = index;
476
+ });
477
+ item.addEventListener("mouseout", () => {
478
+ this.resultActiveValue = NaN;
479
+ });
480
+ this.resultsListTarget.appendChild(item);
481
+ this.resultElements.push(item);
482
+ });
483
+ if (options.length > 0) {
484
+ this.open();
485
+ } else {
486
+ this.close();
487
+ }
488
+ }
489
+ selectResult(element) {
490
+ const value = element.dataset.value || "";
491
+ const label = element.dataset.label || value;
492
+ this.inputTarget.value = "";
493
+ this.close();
494
+ this.element.dispatchEvent(new CustomEvent("kubik-typeahead:select", {
495
+ bubbles: true,
496
+ detail: { value, label }
497
+ }));
498
+ }
499
+ moveActive(direction) {
500
+ if (this.resultElements.length === 0)
501
+ return;
502
+ if (Number.isNaN(this.resultActiveValue)) {
503
+ this.resultActiveValue = direction > 0 ? 0 : this.resultElements.length - 1;
504
+ return;
505
+ }
506
+ const next = this.resultActiveValue + direction;
507
+ if (next < 0) {
508
+ this.resultActiveValue = this.resultElements.length - 1;
509
+ } else if (next >= this.resultElements.length) {
510
+ this.resultActiveValue = 0;
511
+ } else {
512
+ this.resultActiveValue = next;
513
+ }
514
+ }
515
+ open() {
516
+ if (this.hasOpenClass)
517
+ this.element.classList.add(this.openClass);
518
+ this.element.classList.add("kubik-interface-typeahead--open");
519
+ this.inputTarget.setAttribute("aria-expanded", "true");
520
+ }
521
+ close() {
522
+ if (this.hasOpenClass)
523
+ this.element.classList.remove(this.openClass);
524
+ this.element.classList.remove("kubik-interface-typeahead--open");
525
+ this.inputTarget.setAttribute("aria-expanded", "false");
526
+ this.resultActiveValue = NaN;
527
+ this.resultsListTarget.innerHTML = "";
528
+ this.resultElements = [];
529
+ }
530
+ queryMeetsMinLength() {
531
+ return this.inputTarget.value.trim().length >= this.minLengthValue;
532
+ }
533
+ clearDebounce() {
534
+ if (this.debounceTimer) {
535
+ clearTimeout(this.debounceTimer);
536
+ this.debounceTimer = null;
537
+ }
538
+ }
539
+ abortFetch() {
540
+ if (this.fetchAbort) {
541
+ this.fetchAbort.abort();
542
+ this.fetchAbort = null;
543
+ }
544
+ }
545
+ }
546
+ typeahead_controller_default.targets = ["input", "resultsList", "feedback"];
547
+ typeahead_controller_default.classes = ["activeResult", "open"];
548
+ typeahead_controller_default.values = {
549
+ src: { type: String, default: "" },
550
+ options: { type: Array, default: [] },
551
+ minLength: { type: Number, default: 1 },
552
+ debounceMs: { type: Number, default: 200 },
553
+ maxResults: { type: Number, default: 20 },
554
+ paramName: { type: String, default: "q" },
555
+ excludeValues: { type: Array, default: [] },
556
+ resultActive: { type: Number, default: NaN }
557
+ };
558
+ class token_input_controller_default extends Controller {
559
+ constructor() {
560
+ super(...arguments);
561
+ this.tokens = [];
562
+ this.autosubmitTimer = null;
563
+ this.enhanced = false;
564
+ this.onReplaceTags = (event) => {
565
+ const detail = event.detail;
566
+ if (!(detail == null ? void 0 : detail.tags))
567
+ return;
568
+ this.tokens = this.expandTagList(detail.tags);
569
+ this.renderChips();
570
+ this.syncHiddenFields();
571
+ this.syncTypeaheadExcludeValues();
572
+ };
573
+ }
574
+ syncTypeaheadExcludeValues() {
575
+ if (this.typeaheadOutletElements.length === 0)
576
+ return;
577
+ const payload = JSON.stringify(this.tokens);
578
+ this.typeaheadOutletElements.forEach((element) => {
579
+ element.dataset.kubikTypeaheadExcludeValuesValue = payload;
580
+ });
581
+ }
582
+ connect() {
583
+ this.enhanced = true;
584
+ this.tokens = this.parseInitialValue();
585
+ if (this.hasFallbackInputTarget) {
586
+ this.fallbackInputTarget.classList.add("kubik-interface-token-input__fallback--hidden");
587
+ this.fallbackInputTarget.removeAttribute("name");
588
+ }
589
+ this.renderChips();
590
+ this.syncHiddenFields(false);
591
+ this.syncTypeaheadExcludeValues();
592
+ this.element.addEventListener("kubik-token-input:replace", this.onReplaceTags);
593
+ }
594
+ disconnect() {
595
+ this.element.removeEventListener("kubik-token-input:replace", this.onReplaceTags);
596
+ if (this.autosubmitTimer)
597
+ clearTimeout(this.autosubmitTimer);
598
+ }
599
+ addFromTypeahead(event) {
600
+ const detail = event.detail;
601
+ if (!(detail == null ? void 0 : detail.value))
602
+ return;
603
+ this.addToken(detail.value);
604
+ this.queryInputTarget.value = "";
605
+ this.queryInputTarget.focus();
606
+ }
607
+ queryKeydown(event) {
608
+ if (event.key === "Backspace" && this.queryInputTarget.value === "" && this.tokens.length > 0) {
609
+ this.removeToken(this.tokens.length - 1);
610
+ event.preventDefault();
611
+ return;
612
+ }
613
+ if (event.key === "Enter" && this.allowCreateValue) {
614
+ const value = this.queryInputTarget.value.trim();
615
+ if (value !== "") {
616
+ event.preventDefault();
617
+ event.stopPropagation();
618
+ this.addToken(value);
619
+ this.queryInputTarget.value = "";
620
+ }
621
+ }
622
+ }
623
+ removeChip(event) {
624
+ const button = event.currentTarget;
625
+ const index = parseInt(button.dataset.index || "-1", 10);
626
+ if (index >= 0) {
627
+ this.removeToken(index);
628
+ }
629
+ }
630
+ addToken(raw) {
631
+ const parts = raw.split(/[,;]+/).map((part) => part.trim()).filter((part) => part !== "");
632
+ parts.forEach((value) => this.addSingleToken(value));
633
+ }
634
+ expandTagList(raw) {
635
+ if (raw == null)
636
+ return [];
637
+ let values = [];
638
+ if (Array.isArray(raw)) {
639
+ values = raw;
640
+ } else if (typeof raw === "string") {
641
+ const trimmed = raw.trim();
642
+ if (trimmed.startsWith("[")) {
643
+ try {
644
+ const parsed = JSON.parse(trimmed);
645
+ values = Array.isArray(parsed) ? parsed : [raw];
646
+ } catch {
647
+ values = [raw];
648
+ }
649
+ } else {
650
+ values = [raw];
651
+ }
652
+ } else {
653
+ return [];
654
+ }
655
+ return values.reduce((acc, entry) => {
656
+ return acc.concat(
657
+ String(entry).split(/[,;]+/).map((part) => part.trim()).filter((part) => part !== "")
658
+ );
659
+ }, []);
660
+ }
661
+ addSingleToken(value) {
662
+ if (value === "")
663
+ return;
664
+ if (this.deduplicateValue && this.tokens.some((token) => token.toLowerCase() === value.toLowerCase())) {
665
+ return;
666
+ }
667
+ if (this.multiselectValue) {
668
+ this.tokens.push(value);
669
+ } else {
670
+ this.tokens = [value];
671
+ }
672
+ this.renderChips();
673
+ this.syncHiddenFields();
674
+ this.syncTypeaheadExcludeValues();
675
+ }
676
+ removeToken(index) {
677
+ this.tokens.splice(index, 1);
678
+ this.renderChips();
679
+ this.syncHiddenFields();
680
+ this.syncTypeaheadExcludeValues();
681
+ }
682
+ parseInitialValue() {
683
+ const raw = this.initialRawValue();
684
+ if (raw === "")
685
+ return [];
686
+ return raw.split(",").map((part) => part.trim()).filter((part) => part !== "");
687
+ }
688
+ initialRawValue() {
689
+ if (this.hasHiddenInputTarget && this.hiddenInputTarget.value) {
690
+ return this.hiddenInputTarget.value;
691
+ }
692
+ if (this.hasFallbackInputTarget) {
693
+ return this.fallbackInputTarget.value;
694
+ }
695
+ return "";
696
+ }
697
+ renderChips() {
698
+ this.chipListTarget.innerHTML = "";
699
+ this.tokens.forEach((token, index) => {
700
+ const chip = document.createElement("span");
701
+ chip.className = "kubik-interface-token-input__chip";
702
+ chip.textContent = token;
703
+ const remove = document.createElement("button");
704
+ remove.type = "button";
705
+ remove.className = "kubik-interface-token-input__chip-remove";
706
+ remove.dataset.index = String(index);
707
+ remove.setAttribute("aria-label", `Remove ${token}`);
708
+ remove.setAttribute("data-action", "click->kubik-token-input#removeChip");
709
+ remove.innerHTML = '<span class="material-symbols-outlined material-icon">close</span>';
710
+ chip.appendChild(remove);
711
+ this.chipListTarget.appendChild(chip);
712
+ });
713
+ }
714
+ syncHiddenFields(autosubmit = true) {
715
+ if (this.valueFormatValue === "array") {
716
+ this.syncArrayHiddenFields();
717
+ } else {
718
+ this.syncStringHiddenField();
719
+ }
720
+ if (autosubmit) {
721
+ this.maybeAutosubmitForm();
722
+ }
723
+ }
724
+ maybeAutosubmitForm() {
725
+ if (!this.autosubmitValue)
726
+ return;
727
+ const delay = this.autosubmitDebounceMsValue;
728
+ if (delay > 0) {
729
+ if (this.autosubmitTimer)
730
+ clearTimeout(this.autosubmitTimer);
731
+ this.autosubmitTimer = setTimeout(() => this.requestFormSubmit(), delay);
732
+ return;
733
+ }
734
+ this.requestFormSubmit();
735
+ }
736
+ requestFormSubmit() {
737
+ const form = this.element.closest("form");
738
+ if (form && typeof form.requestSubmit === "function") {
739
+ form.requestSubmit();
740
+ }
741
+ }
742
+ syncStringHiddenField() {
743
+ const value = this.tokens.join(this.separatorValue);
744
+ if (this.hasHiddenInputTarget) {
745
+ this.hiddenInputTarget.value = value;
746
+ }
747
+ }
748
+ syncArrayHiddenFields() {
749
+ if (!this.hasHiddenArrayContainerTarget)
750
+ return;
751
+ const container = this.hiddenArrayContainerTarget;
752
+ const baseName = container.dataset.fieldName || "";
753
+ container.innerHTML = "";
754
+ this.tokens.forEach((token) => {
755
+ const input = document.createElement("input");
756
+ input.type = "hidden";
757
+ input.name = baseName;
758
+ input.value = token;
759
+ container.appendChild(input);
760
+ });
761
+ }
762
+ }
763
+ token_input_controller_default.targets = [
764
+ "fallbackInput",
765
+ "hiddenInput",
766
+ "hiddenArrayContainer",
767
+ "chipList",
768
+ "queryInput"
769
+ ];
770
+ token_input_controller_default.outlets = ["typeahead"];
771
+ token_input_controller_default.values = {
772
+ multiselect: { type: Boolean, default: true },
773
+ valueFormat: { type: String, default: "string" },
774
+ separator: { type: String, default: ", " },
775
+ allowCreate: { type: Boolean, default: true },
776
+ deduplicate: { type: Boolean, default: true },
777
+ autosubmit: { type: Boolean, default: false },
778
+ autosubmitDebounceMs: { type: Number, default: 0 }
779
+ };
780
+ class debounced_form_submit_controller_default extends Controller {
781
+ constructor() {
782
+ super(...arguments);
783
+ this.timer = null;
784
+ }
785
+ schedule() {
786
+ if (this.timer)
787
+ clearTimeout(this.timer);
788
+ this.timer = setTimeout(() => this.submit(), this.delayValue);
789
+ }
790
+ disconnect() {
791
+ if (this.timer)
792
+ clearTimeout(this.timer);
793
+ }
794
+ submit() {
795
+ const form = this.element.closest("form");
796
+ if (form && typeof form.requestSubmit === "function") {
797
+ form.requestSubmit();
798
+ }
799
+ }
800
+ }
801
+ debounced_form_submit_controller_default.values = {
802
+ delay: { type: Number, default: 400 }
803
+ };
804
+ class filter_tags_section_controller_default extends Controller {
805
+ connect() {
806
+ this.syncDisabled();
807
+ }
808
+ syncDisabled() {
809
+ const disabled = this.untaggedTarget.checked;
810
+ this.element.classList.toggle("kubik-interface-filters__field--tags-filter-disabled", disabled);
811
+ }
812
+ }
813
+ filter_tags_section_controller_default.targets = ["section", "untagged"];
814
+ const KUBIK_INTERFACE_STIMULUS_MANIFEST = [
815
+ "kubik-modal",
816
+ "kubik-offcanvas",
817
+ "kubik-typeahead",
818
+ "kubik-token-input",
819
+ "kubik-debounced-form-submit",
820
+ "kubik-filter-tags-section"
821
+ ];
822
+ function registerKubikInterfaceStimulusControllers(application) {
823
+ application.register("kubik-modal", modal_controller_default);
824
+ application.register("kubik-offcanvas", offcanvas_controller_default);
825
+ application.register("kubik-typeahead", typeahead_controller_default);
826
+ application.register("kubik-token-input", token_input_controller_default);
827
+ application.register("kubik-debounced-form-submit", debounced_form_submit_controller_default);
828
+ application.register("kubik-filter-tags-section", filter_tags_section_controller_default);
829
+ }
830
+ const registerInterfaceElementControllers = function() {
831
+ const existing = document.documentElement.getAttribute("data-controller") || "";
832
+ const controllers = /* @__PURE__ */ new Set([
833
+ ...existing.split(/\s+/).filter(Boolean),
834
+ "kubik-modal",
835
+ "kubik-offcanvas"
836
+ ]);
837
+ document.documentElement.setAttribute("data-controller", [...controllers].join(" "));
838
+ };
472
839
  const modalInit = function() {
473
- document.addEventListener("DOMContentLoaded", function() {
474
- document.documentElement.setAttribute("data-controller", "kubik-modal");
475
- });
840
+ document.addEventListener("DOMContentLoaded", registerInterfaceElementControllers);
476
841
  };
477
- export { modal_controller_default as ModalController, modalInit };
842
+ const offcanvasInit = modalInit;
843
+ export { debounced_form_submit_controller_default as DebouncedFormSubmitController, filter_tags_section_controller_default as FilterTagsSectionController, KUBIK_INTERFACE_STIMULUS_MANIFEST, modal_controller_default as ModalController, offcanvas_controller_default as OffcanvasController, token_input_controller_default as TokenInputController, typeahead_controller_default as TypeaheadController, modalInit, offcanvasInit, registerKubikInterfaceStimulusControllers };
@@ -1,12 +1,33 @@
1
- (function(i,l){typeof exports=="object"&&typeof module!="undefined"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(i=typeof globalThis!="undefined"?globalThis:i||self,l(i["kubik-modal"]={}))})(this,function(i){"use strict";function l(e){return e.replace(/(?:[_-])([a-z0-9])/g,(t,r)=>r.toUpperCase())}function f(e){return e.charAt(0).toUpperCase()+e.slice(1)}function V(e){return e.replace(/([A-Z])/g,(t,r)=>`-${r.toLowerCase()}`)}function g(e,t){const r=h(e);return Array.from(r.reduce((n,a)=>(S(a,t).forEach(o=>n.add(o)),n),new Set))}function C(e,t){return h(e).reduce((n,a)=>(n.push(...j(a,t)),n),[])}function h(e){const t=[];for(;e;)t.push(e),e=Object.getPrototypeOf(e);return t.reverse()}function S(e,t){const r=e[t];return Array.isArray(r)?r:[]}function j(e,t){const r=e[t];return r?Object.keys(r).map(n=>[n,r[n]]):[]}(()=>{function e(r){function n(){return Reflect.construct(r,arguments,new.target)}return n.prototype=Object.create(r.prototype,{constructor:{value:n}}),Reflect.setPrototypeOf(n,r),n}function t(){const n=e(function(){this.a.call(this)});return n.prototype.a=function(){},new n}try{return t(),e}catch{return n=>class extends n{}}})();function w(e){return g(e,"classes").reduce((r,n)=>Object.assign(r,A(n)),{})}function A(e){return{[`${e}Class`]:{get(){const{classes:t}=this;if(t.has(e))return t.get(e);{const r=t.getAttributeName(e);throw new Error(`Missing attribute "${r}"`)}}},[`${e}Classes`]:{get(){return this.classes.getAll(e)}},[`has${f(e)}Class`]:{get(){return this.classes.has(e)}}}}function O(e){return g(e,"targets").reduce((r,n)=>Object.assign(r,M(n)),{})}function M(e){return{[`${e}Target`]:{get(){const t=this.targets.find(e);if(t)return t;throw new Error(`Missing target element "${e}" for "${this.identifier}" controller`)}},[`${e}Targets`]:{get(){return this.targets.findAll(e)}},[`has${f(e)}Target`]:{get(){return this.targets.has(e)}}}}function v(e){const t=C(e,"values"),r={valueDescriptorMap:{get(){return t.reduce((n,a)=>{const o=b(a,this.identifier),d=this.data.getAttributeNameForKey(o.key);return Object.assign(n,{[d]:o})},{})}}};return t.reduce((n,a)=>Object.assign(n,$(a)),r)}function $(e,t){const r=b(e,t),{key:n,name:a,reader:o,writer:d}=r;return{[a]:{get(){const s=this.data.get(n);return s!==null?o(s):r.defaultValue},set(s){s===void 0?this.data.delete(n):this.data.set(n,d(s))}},[`has${f(a)}`]:{get(){return this.data.has(n)||r.hasCustomDefaultValue}}}}function b([e,t],r){return E({controller:r,token:e,typeDefinition:t})}function m(e){switch(e){case Array:return"array";case Boolean:return"boolean";case Number:return"number";case Object:return"object";case String:return"string"}}function u(e){switch(typeof e){case"boolean":return"boolean";case"number":return"number";case"string":return"string"}if(Array.isArray(e))return"array";if(Object.prototype.toString.call(e)==="[object Object]")return"object"}function D(e){const t=m(e.typeObject.type);if(!t)return;const r=u(e.typeObject.default);if(t!==r){const n=e.controller?`${e.controller}.${e.token}`:e.token;throw new Error(`The specified default value for the Stimulus Value "${n}" must match the defined type "${t}". The provided default value of "${e.typeObject.default}" is of type "${r}".`)}return t}function _(e){const t=D({controller:e.controller,token:e.token,typeObject:e.typeDefinition}),r=u(e.typeDefinition),n=m(e.typeDefinition),a=t||r||n;if(a)return a;const o=e.controller?`${e.controller}.${e.typeDefinition}`:e.token;throw new Error(`Unknown value type "${o}" for "${e.token}" value`)}function P(e){const t=m(e);if(t)return F[t];const r=e.default;return r!==void 0?r:e}function E(e){const t=`${V(e.token)}-value`,r=_(e);return{type:r,key:t,name:l(t),get defaultValue(){return P(e.typeDefinition)},get hasCustomDefaultValue(){return u(e.typeDefinition)!==void 0},reader:R[r],writer:y[r]||y.default}}const F={get array(){return[]},boolean:!1,number:0,get object(){return{}},string:""},R={array(e){const t=JSON.parse(e);if(!Array.isArray(t))throw new TypeError(`expected value of type "array" but instead got value "${e}" of type "${u(t)}"`);return t},boolean(e){return!(e=="0"||String(e).toLowerCase()=="false")},number(e){return Number(e)},object(e){const t=JSON.parse(e);if(t===null||typeof t!="object"||Array.isArray(t))throw new TypeError(`expected value of type "object" but instead got value "${e}" of type "${u(t)}"`);return t},string(e){return e}},y={default:H,array:k,object:k};function k(e){return JSON.stringify(e)}function H(e){return`${e}`}class c{constructor(t){this.context=t}static get shouldLoad(){return!0}get application(){return this.context.application}get scope(){return this.context.scope}get element(){return this.scope.element}get identifier(){return this.scope.identifier}get targets(){return this.scope.targets}get classes(){return this.scope.classes}get data(){return this.scope.data}initialize(){}connect(){}disconnect(){}dispatch(t,{target:r=this.element,detail:n={},prefix:a=this.identifier,bubbles:o=!0,cancelable:d=!0}={}){const s=a?`${a}:${t}`:t,T=new CustomEvent(s,{detail:n,bubbles:o,cancelable:d});return r.dispatchEvent(T),T}}c.blessings=[w,O,v],c.targets=[],c.values={};class p extends c{initialize(){document.head.insertAdjacentHTML("beforeend",`<template id='kubik-modal-template' data-kubik-modal-target='modalTemplate'>
2
- <div id='kubik-modal' class='kubik-modal-element' data-kubik-modal-target='modalContainer'>
3
- <div class='kubik-modal-background' data-action='click->kubik-modal#closeModal'>
4
- </div>
1
+ (function(i,r){typeof exports=="object"&&typeof module!="undefined"?r(exports,require("@hotwired/stimulus")):typeof define=="function"&&define.amd?define(["exports","@hotwired/stimulus"],r):(i=typeof globalThis!="undefined"?globalThis:i||self,r(i["kubik-modal"]={},i.Stimulus))})(this,function(i,r){"use strict";const h="kubik_modal_frame";function v(n=h){return`
2
+ <template id='kubik-modal-template' data-kubik-modal-target='modalTemplate'>
3
+ <div id='kubik-modal' data-turbo-permanent class='kubik-modal-element' data-kubik-modal-target='modalContainer'>
4
+ <div class='kubik-modal-background' data-action='click->kubik-modal#closeModal'>
5
+ </div>
5
6
  <div class='kubik-modal-element-window'>
6
- <div data-kubik-modal-target='modalHeader' class='h4 kubik-modal-title-bar'>Test header</div>
7
- <turbo-frame id='media_library_frame' class='kubik-modal-element-content' data-kubik-modal-target='modalFrame'>
7
+ <div data-kubik-modal-target='modalHeader' class='h4 kubik-modal-title-bar'></div>
8
+ <turbo-frame id='${n}' class='kubik-modal-element-content' data-kubik-modal-target='modalFrame'>
8
9
  </turbo-frame>
9
10
  </div>
10
11
  </div>
11
12
  </template>
12
- `)}connect(){this._renderDOMElements(),document.addEventListener("keydown",t=>{t.keyCode===27&&this.closeModal()})}get modalTemplate(){return this.modalTemplateTarget.innerHTML}selectModal(t){const r=t.currentTarget;if(this.modalActionValue==="return"){const[n,a]=this.modalReturnControllerValue.split("#");this.application.getControllerForElementAndIdentifier(document.getElementById(a),n).receiveModalReturn({payload:{kubik_media_upload_id:parseInt(r.dataset.selectedKubikMediaUploadId),id:parseInt(r.dataset.selectedKubikMediaUploadId),thumb:r.dataset.selectedThumb,additional_information:r.dataset.selectedAdditionalInfo},return_payload:this.modalReturnPayloadValue}),this.closeModal()}}modalStatusValueChanged(){this.hasModalContainerTarget&&(this.modalStatusValue==="opened"?this.modalContainerTarget.classList.add("kubik-modal-element__open"):this.modalContainerTarget.classList.remove("kubik-modal-element__open"))}modalSrcValueChanged(){this.hasModalFrameTarget&&(this.modalSrcValue===""?(this.modalFrameTarget.setAttribute("src",this.modalSrcValue),this.modalFrameTarget.innerHTML=""):this.modalFrameTarget.setAttribute("src",this.modalSrcValue))}modalHeaderValueChanged(){this.hasModalHeaderTarget&&(this.modalHeaderTarget.innerText=this.modalHeaderValue)}openModal(t){const r=t.currentTarget;this.modalSrcValue=r.getAttribute("src"),this.modalHeaderValue=r.dataset.kubikModalHeaderText,this.modalActionValue=r.dataset.kubikModalAction,this.modalReturnControllerValue=r.dataset.kubikModalReturnController,r.dataset.kubikModalReturnPayload&&(this.modalReturnPayloadValue=JSON.parse(r.dataset.kubikModalReturnPayload)),this.modalStatusValue="opened"}closeModal(){this.modalStatusValue="closed",this.modalSrcValue="",this.modalHeaderValue="",this.modalActionValue="",this.modalReturnControllerValue="",this.modalReturnPayloadValue={}}_renderDOMElements(){document.getElementById("kubik-modal")||document.body.insertAdjacentHTML("beforeend",this.modalTemplate)}}p.targets=["modalTemplate","modalContainer","modalFrame","modalHeader"],p.values={modalHeader:{type:String,default:""},modalStatus:{type:String,default:"closed"},modalSrc:{type:String,default:""},modalAction:{type:String,default:""},modalReturnPayload:{type:Object,default:{}},modalReturnController:{type:String,default:""}};const x=function(){document.addEventListener("DOMContentLoaded",function(){document.documentElement.setAttribute("data-controller","kubik-modal")})};i.ModalController=p,i.modalInit=x,Object.defineProperties(i,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
13
+ `}class d extends r.Controller{constructor(){super(...arguments),this.onTurboLoad=()=>{this._renderDOMElements()}}initialize(){document.head.insertAdjacentHTML("beforeend",v(h))}connect(){this._renderDOMElements(),document.addEventListener("keydown",e=>{e.keyCode===27&&this.closeModal()}),document.addEventListener("turbo:load",this.onTurboLoad)}disconnect(){document.removeEventListener("turbo:load",this.onTurboLoad)}get modalTemplate(){return this.modalTemplateTarget.innerHTML}selectModal(e){const t=e.currentTarget;if(this.modalActionValue==="return"){const[a,s]=this.modalReturnControllerValue.split("#");this.application.getControllerForElementAndIdentifier(document.getElementById(s),a).receiveModalReturn({payload:{kubik_media_upload_id:parseInt(t.dataset.selectedKubikMediaUploadId),id:parseInt(t.dataset.selectedKubikMediaUploadId),thumb:t.dataset.selectedThumb,additional_information:t.dataset.selectedAdditionalInfo},return_payload:this.modalReturnPayloadValue}),this.closeModal()}}modalStatusValueChanged(){this.hasModalContainerTarget&&(this.modalStatusValue==="opened"?this.modalContainerTarget.classList.add("kubik-modal-element__open"):this.modalContainerTarget.classList.remove("kubik-modal-element__open"))}modalSrcValueChanged(){this.hasModalFrameTarget&&(this.modalSrcValue===""?(this.modalFrameTarget.setAttribute("src",this.modalSrcValue),this.modalFrameTarget.innerHTML=""):this.modalFrameTarget.setAttribute("src",this.modalSrcValue))}modalHeaderValueChanged(){this.hasModalHeaderTarget&&(this.modalHeaderTarget.innerText=this.modalHeaderValue)}openModal(e){this._renderDOMElements();const t=e.currentTarget,a=t.dataset.kubikModalFrameId||h;this.hasModalFrameTarget&&this.modalFrameTarget.id!==a&&(this.modalFrameTarget.id=a),this.modalSrcValue=t.getAttribute("src"),this.modalHeaderValue=t.dataset.kubikModalHeaderText,this.modalActionValue=t.dataset.kubikModalAction,this.modalReturnControllerValue=t.dataset.kubikModalReturnController,t.dataset.kubikModalReturnPayload&&(this.modalReturnPayloadValue=JSON.parse(t.dataset.kubikModalReturnPayload)),this.modalStatusValue="opened"}closeModal(){this.modalStatusValue="closed",this.modalSrcValue="",this.modalHeaderValue="",this.modalActionValue="",this.modalReturnControllerValue="",this.modalReturnPayloadValue={}}_renderDOMElements(){document.getElementById("kubik-modal")||document.body.insertAdjacentHTML("beforeend",this.modalTemplate)}}d.targets=["modalTemplate","modalContainer","modalFrame","modalHeader"],d.values={modalHeader:{type:String,default:""},modalStatus:{type:String,default:"closed"},modalSrc:{type:String,default:""},modalAction:{type:String,default:""},modalReturnPayload:{type:Object,default:{}},modalReturnController:{type:String,default:""}};const p="kubik_offcanvas_frame";class c extends r.Controller{constructor(){super(...arguments),this.handleKeydown=e=>{e.key==="Escape"&&this.closeOffcanvas()},this.handleFrameLoad=()=>{this.clearLoadingState()},this.handleFrameMissing=()=>{this.clearLoadingState()}}initialize(){document.head.insertAdjacentHTML("beforeend",`<template id='kubik-offcanvas-template' data-kubik-offcanvas-target='offcanvasTemplate'>
14
+ <div id='kubik-offcanvas' class='kubik-offcanvas' data-kubik-offcanvas-target='offcanvasContainer' aria-hidden='true'>
15
+ <div class='kubik-offcanvas-backdrop' data-action='click->kubik-offcanvas#closeOffcanvas'></div>
16
+ <div class='kubik-offcanvas-panel kubik-offcanvas-panel--end' data-kubik-offcanvas-target='offcanvasPanel' role='dialog' aria-modal='true'>
17
+ <div class='kubik-offcanvas-header'>
18
+ <div data-kubik-offcanvas-target='offcanvasHeader' class='kubik-offcanvas-title'></div>
19
+ <button type='button' class='kubik-offcanvas-close' aria-label='Close' data-action='click->kubik-offcanvas#closeOffcanvas'>
20
+ <span class='material-symbols-outlined material-icon'>close</span>
21
+ </button>
22
+ </div>
23
+ <div class='kubik-offcanvas-body'>
24
+ <turbo-frame id='${p}' class='kubik-offcanvas-content' data-kubik-offcanvas-target='offcanvasFrame'></turbo-frame>
25
+ </div>
26
+ </div>
27
+ </div>
28
+ </template>`)}connect(){this._renderDOMElements(),document.addEventListener("keydown",this.handleKeydown),this.hasOffcanvasFrameTarget&&(this.offcanvasFrameTarget.addEventListener("turbo:frame-load",this.handleFrameLoad),this.offcanvasFrameTarget.addEventListener("turbo:frame-missing",this.handleFrameMissing))}disconnect(){document.removeEventListener("keydown",this.handleKeydown),this.hasOffcanvasFrameTarget&&(this.offcanvasFrameTarget.removeEventListener("turbo:frame-load",this.handleFrameLoad),this.offcanvasFrameTarget.removeEventListener("turbo:frame-missing",this.handleFrameMissing))}get offcanvasTemplate(){return this.offcanvasTemplateTarget.innerHTML}offcanvasStatusValueChanged(){if(!this.hasOffcanvasContainerTarget)return;const e=this.offcanvasStatusValue==="opened";if(this.offcanvasContainerTarget.classList.toggle("kubik-offcanvas--open",e),this.offcanvasContainerTarget.setAttribute("aria-hidden",e?"false":"true"),document.body.classList.toggle("kubik-offcanvas-open",e),this.hasOffcanvasPanelTarget){this.offcanvasPanelTarget.classList.remove("kubik-offcanvas-panel--start","kubik-offcanvas-panel--end");const t=this.offcanvasPositionValue==="start"?"start":"end";this.offcanvasPanelTarget.classList.add(`kubik-offcanvas-panel--${t}`),this.offcanvasPanelTarget.classList.remove("kubik-offcanvas-panel--tone-white","kubik-offcanvas-panel--tone-grey");const a=this.offcanvasToneValue==="white"?"white":"grey";this.offcanvasPanelTarget.classList.add(`kubik-offcanvas-panel--tone-${a}`)}e||this.clearOffcanvasContent()}offcanvasSrcValueChanged(){if(!!this.hasOffcanvasFrameTarget){if(this.offcanvasSrcValue===""){this.offcanvasFrameTarget.removeAttribute("src"),this.offcanvasFrameTarget.innerHTML="";return}this.showLoadingState(),this.offcanvasFrameTarget.setAttribute("src",this.offcanvasSrcValue)}}offcanvasHeaderValueChanged(){this.hasOffcanvasHeaderTarget&&(this.offcanvasHeaderTarget.textContent=this.offcanvasHeaderValue)}openOffcanvas(e){const t=e.currentTarget,a=t.getAttribute("src")||t.getAttribute("href")||t.dataset.kubikOffcanvasSrc||"";this.offcanvasPositionValue=t.dataset.kubikOffcanvasPosition||this.offcanvasPositionValue,this.offcanvasHeaderValue=t.dataset.kubikOffcanvasHeaderText||"",this.offcanvasToneValue=t.dataset.kubikOffcanvasTone||"grey",this.offcanvasSrcValue=a,this.offcanvasStatusValue="opened"}closeOffcanvas(){this.offcanvasStatusValue="closed",this.offcanvasSrcValue="",this.offcanvasHeaderValue="",this.offcanvasToneValue="grey"}offcanvasFrameTargetDisconnected(){this.offcanvasStatusValue==="opened"&&this.closeOffcanvas()}showLoadingState(){!this.hasOffcanvasFrameTarget||(this.offcanvasFrameTarget.innerHTML=`
29
+ <div class="kubik-offcanvas-loading" aria-live="polite" role="status">
30
+ <span class="material-symbols-outlined material-icon kubik-offcanvas-loading__spinner">progress_activity</span>
31
+ <span class="kubik-offcanvas-loading__text">Loading\u2026</span>
32
+ </div>
33
+ `)}clearLoadingState(){var t;const e=(t=this.offcanvasFrameTarget)==null?void 0:t.querySelector(".kubik-offcanvas-loading");e&&e.remove()}clearOffcanvasContent(){!this.hasOffcanvasFrameTarget||(this.offcanvasFrameTarget.removeAttribute("src"),this.offcanvasFrameTarget.innerHTML="")}_renderDOMElements(){document.getElementById("kubik-offcanvas")||document.body.insertAdjacentHTML("beforeend",this.offcanvasTemplate)}}c.targets=["offcanvasTemplate","offcanvasContainer","offcanvasPanel","offcanvasFrame","offcanvasHeader"],c.values={offcanvasHeader:{type:String,default:""},offcanvasStatus:{type:String,default:"closed"},offcanvasSrc:{type:String,default:""},offcanvasPosition:{type:String,default:"end"},offcanvasTone:{type:String,default:"grey"}};class o extends r.Controller{constructor(){super(...arguments),this.debounceTimer=null,this.fetchAbort=null,this.filteredOptions=[],this.resultElements=[],this.onResultsMouseDownHandler=e=>this.onResultsMouseDown(e)}connect(){this.resultsListTarget.addEventListener("mousedown",this.onResultsMouseDownHandler),this.inputTarget.setAttribute("role","combobox"),this.inputTarget.setAttribute("aria-autocomplete","list"),this.inputTarget.setAttribute("aria-expanded","false"),this.close()}disconnect(){this.resultsListTarget.removeEventListener("mousedown",this.onResultsMouseDownHandler),this.clearDebounce(),this.abortFetch()}onInput(){if(this.clearDebounce(),this.debounceMsValue<=0){this.refreshResults();return}this.debounceTimer=setTimeout(()=>this.refreshResults(),this.debounceMsValue)}onFocus(){this.queryMeetsMinLength()&&this.resultElements.length>0&&this.open()}excludeValuesValueChanged(){this.queryMeetsMinLength()&&this.refreshResults()}onBlur(){window.setTimeout(()=>{this.element.contains(document.activeElement)||this.close()},150)}keydown(e){switch(e.key){case"ArrowDown":this.resultElements.length===0&&this.queryMeetsMinLength()&&this.refreshResults(),this.resultElements.length>0&&(e.preventDefault(),this.moveActive(1));break;case"ArrowUp":this.resultElements.length>0&&(e.preventDefault(),this.moveActive(-1));break;case"Enter":!Number.isNaN(this.resultActiveValue)&&this.resultElements[this.resultActiveValue]&&(e.preventDefault(),this.selectResult(this.resultElements[this.resultActiveValue]));break;case"Escape":e.preventDefault(),this.close();break}}resultActiveValueChanged(){this.resultElements.forEach(e=>{this.hasActiveResultClass&&e.classList.remove(this.activeResultClass)}),!Number.isNaN(this.resultActiveValue)&&this.resultElements[this.resultActiveValue]?(this.hasActiveResultClass&&this.resultElements[this.resultActiveValue].classList.add(this.activeResultClass),this.inputTarget.setAttribute("aria-activedescendant",this.resultElements[this.resultActiveValue].id)):this.inputTarget.removeAttribute("aria-activedescendant")}onResultsMouseDown(e){const t=e.target.closest(".kubik-interface-typeahead__option");!t||(e.preventDefault(),this.selectResult(t))}refreshResults(){if(!this.queryMeetsMinLength()){this.renderResults([]);return}const e=this.inputTarget.value.trim();this.srcValue?this.fetchRemote(e):(this.filteredOptions=this.filterStaticOptions(e),this.renderResults(this.filteredOptions))}filterStaticOptions(e){const t=e.toLowerCase();return this.withoutExcluded(this.normalizeOptions(this.optionsValue).filter(a=>a.label.toLowerCase().includes(t))).slice(0,this.maxResultsValue)}normalizeOptions(e){return e.map(t=>{if(typeof t=="string")return{label:t,value:t};if(t&&typeof t=="object"){const a=t,s=a.label||a.name||a.value||"",l=a.value||a.label||a.name||"";return{label:String(s),value:String(l)}}return{label:"",value:""}}).filter(t=>t.label!=="")}withoutExcluded(e){if(this.excludeValuesValue.length===0)return e;const t=new Set(this.excludeValuesValue.map(a=>a.toLowerCase().trim()).filter(a=>a!==""));return e.filter(a=>{const s=a.value.toLowerCase().trim(),l=a.label.toLowerCase().trim();return!t.has(s)&&!t.has(l)})}fetchRemote(e){this.abortFetch(),this.fetchAbort=new AbortController;const t=new URL(this.srcValue,window.location.origin);t.searchParams.set(this.paramNameValue,e),this.hasFeedbackTarget&&(this.feedbackTarget.textContent="Loading..."),fetch(t.toString(),{headers:{Accept:"application/json"},signal:this.fetchAbort.signal}).then(a=>a.json()).then(a=>{const s=Array.isArray(a)?a:[];this.filteredOptions=this.withoutExcluded(this.normalizeOptions(s)).slice(0,this.maxResultsValue),this.renderResults(this.filteredOptions),this.hasFeedbackTarget&&(this.feedbackTarget.textContent="")}).catch(()=>{this.hasFeedbackTarget&&(this.feedbackTarget.textContent=""),this.renderResults([])})}renderResults(e){this.resultsListTarget.innerHTML="",this.resultElements=[],this.resultActiveValue=NaN,e.forEach((t,a)=>{const s=document.createElement("li");s.id=`${this.inputTarget.id||"typeahead"}_option_${a}`,s.className="kubik-interface-typeahead__option",s.dataset.index=String(a),s.dataset.value=t.value,s.dataset.label=t.label,s.setAttribute("role","option"),s.textContent=t.label,s.addEventListener("mouseover",()=>{this.resultActiveValue=a}),s.addEventListener("mouseout",()=>{this.resultActiveValue=NaN}),this.resultsListTarget.appendChild(s),this.resultElements.push(s)}),e.length>0?this.open():this.close()}selectResult(e){const t=e.dataset.value||"",a=e.dataset.label||t;this.inputTarget.value="",this.close(),this.element.dispatchEvent(new CustomEvent("kubik-typeahead:select",{bubbles:!0,detail:{value:t,label:a}}))}moveActive(e){if(this.resultElements.length===0)return;if(Number.isNaN(this.resultActiveValue)){this.resultActiveValue=e>0?0:this.resultElements.length-1;return}const t=this.resultActiveValue+e;t<0?this.resultActiveValue=this.resultElements.length-1:t>=this.resultElements.length?this.resultActiveValue=0:this.resultActiveValue=t}open(){this.hasOpenClass&&this.element.classList.add(this.openClass),this.element.classList.add("kubik-interface-typeahead--open"),this.inputTarget.setAttribute("aria-expanded","true")}close(){this.hasOpenClass&&this.element.classList.remove(this.openClass),this.element.classList.remove("kubik-interface-typeahead--open"),this.inputTarget.setAttribute("aria-expanded","false"),this.resultActiveValue=NaN,this.resultsListTarget.innerHTML="",this.resultElements=[]}queryMeetsMinLength(){return this.inputTarget.value.trim().length>=this.minLengthValue}clearDebounce(){this.debounceTimer&&(clearTimeout(this.debounceTimer),this.debounceTimer=null)}abortFetch(){this.fetchAbort&&(this.fetchAbort.abort(),this.fetchAbort=null)}}o.targets=["input","resultsList","feedback"],o.classes=["activeResult","open"],o.values={src:{type:String,default:""},options:{type:Array,default:[]},minLength:{type:Number,default:1},debounceMs:{type:Number,default:200},maxResults:{type:Number,default:20},paramName:{type:String,default:"q"},excludeValues:{type:Array,default:[]},resultActive:{type:Number,default:NaN}};class u extends r.Controller{constructor(){super(...arguments),this.tokens=[],this.autosubmitTimer=null,this.enhanced=!1,this.onReplaceTags=e=>{const t=e.detail;!(t!=null&&t.tags)||(this.tokens=this.expandTagList(t.tags),this.renderChips(),this.syncHiddenFields(),this.syncTypeaheadExcludeValues())}}syncTypeaheadExcludeValues(){if(this.typeaheadOutletElements.length===0)return;const e=JSON.stringify(this.tokens);this.typeaheadOutletElements.forEach(t=>{t.dataset.kubikTypeaheadExcludeValuesValue=e})}connect(){this.enhanced=!0,this.tokens=this.parseInitialValue(),this.hasFallbackInputTarget&&(this.fallbackInputTarget.classList.add("kubik-interface-token-input__fallback--hidden"),this.fallbackInputTarget.removeAttribute("name")),this.renderChips(),this.syncHiddenFields(!1),this.syncTypeaheadExcludeValues(),this.element.addEventListener("kubik-token-input:replace",this.onReplaceTags)}disconnect(){this.element.removeEventListener("kubik-token-input:replace",this.onReplaceTags),this.autosubmitTimer&&clearTimeout(this.autosubmitTimer)}addFromTypeahead(e){const t=e.detail;!(t!=null&&t.value)||(this.addToken(t.value),this.queryInputTarget.value="",this.queryInputTarget.focus())}queryKeydown(e){if(e.key==="Backspace"&&this.queryInputTarget.value===""&&this.tokens.length>0){this.removeToken(this.tokens.length-1),e.preventDefault();return}if(e.key==="Enter"&&this.allowCreateValue){const t=this.queryInputTarget.value.trim();t!==""&&(e.preventDefault(),e.stopPropagation(),this.addToken(t),this.queryInputTarget.value="")}}removeChip(e){const t=e.currentTarget,a=parseInt(t.dataset.index||"-1",10);a>=0&&this.removeToken(a)}addToken(e){e.split(/[,;]+/).map(a=>a.trim()).filter(a=>a!=="").forEach(a=>this.addSingleToken(a))}expandTagList(e){if(e==null)return[];let t=[];if(Array.isArray(e))t=e;else if(typeof e=="string"){const a=e.trim();if(a.startsWith("["))try{const s=JSON.parse(a);t=Array.isArray(s)?s:[e]}catch{t=[e]}else t=[e]}else return[];return t.reduce((a,s)=>a.concat(String(s).split(/[,;]+/).map(l=>l.trim()).filter(l=>l!=="")),[])}addSingleToken(e){e!==""&&(this.deduplicateValue&&this.tokens.some(t=>t.toLowerCase()===e.toLowerCase())||(this.multiselectValue?this.tokens.push(e):this.tokens=[e],this.renderChips(),this.syncHiddenFields(),this.syncTypeaheadExcludeValues()))}removeToken(e){this.tokens.splice(e,1),this.renderChips(),this.syncHiddenFields(),this.syncTypeaheadExcludeValues()}parseInitialValue(){const e=this.initialRawValue();return e===""?[]:e.split(",").map(t=>t.trim()).filter(t=>t!=="")}initialRawValue(){return this.hasHiddenInputTarget&&this.hiddenInputTarget.value?this.hiddenInputTarget.value:this.hasFallbackInputTarget?this.fallbackInputTarget.value:""}renderChips(){this.chipListTarget.innerHTML="",this.tokens.forEach((e,t)=>{const a=document.createElement("span");a.className="kubik-interface-token-input__chip",a.textContent=e;const s=document.createElement("button");s.type="button",s.className="kubik-interface-token-input__chip-remove",s.dataset.index=String(t),s.setAttribute("aria-label",`Remove ${e}`),s.setAttribute("data-action","click->kubik-token-input#removeChip"),s.innerHTML='<span class="material-symbols-outlined material-icon">close</span>',a.appendChild(s),this.chipListTarget.appendChild(a)})}syncHiddenFields(e=!0){this.valueFormatValue==="array"?this.syncArrayHiddenFields():this.syncStringHiddenField(),e&&this.maybeAutosubmitForm()}maybeAutosubmitForm(){if(!this.autosubmitValue)return;const e=this.autosubmitDebounceMsValue;if(e>0){this.autosubmitTimer&&clearTimeout(this.autosubmitTimer),this.autosubmitTimer=setTimeout(()=>this.requestFormSubmit(),e);return}this.requestFormSubmit()}requestFormSubmit(){const e=this.element.closest("form");e&&typeof e.requestSubmit=="function"&&e.requestSubmit()}syncStringHiddenField(){const e=this.tokens.join(this.separatorValue);this.hasHiddenInputTarget&&(this.hiddenInputTarget.value=e)}syncArrayHiddenFields(){if(!this.hasHiddenArrayContainerTarget)return;const e=this.hiddenArrayContainerTarget,t=e.dataset.fieldName||"";e.innerHTML="",this.tokens.forEach(a=>{const s=document.createElement("input");s.type="hidden",s.name=t,s.value=a,e.appendChild(s)})}}u.targets=["fallbackInput","hiddenInput","hiddenArrayContainer","chipList","queryInput"],u.outlets=["typeahead"],u.values={multiselect:{type:Boolean,default:!0},valueFormat:{type:String,default:"string"},separator:{type:String,default:", "},allowCreate:{type:Boolean,default:!0},deduplicate:{type:Boolean,default:!0},autosubmit:{type:Boolean,default:!1},autosubmitDebounceMs:{type:Number,default:0}};class f extends r.Controller{constructor(){super(...arguments),this.timer=null}schedule(){this.timer&&clearTimeout(this.timer),this.timer=setTimeout(()=>this.submit(),this.delayValue)}disconnect(){this.timer&&clearTimeout(this.timer)}submit(){const e=this.element.closest("form");e&&typeof e.requestSubmit=="function"&&e.requestSubmit()}}f.values={delay:{type:Number,default:400}};class m extends r.Controller{connect(){this.syncDisabled()}syncDisabled(){const e=this.untaggedTarget.checked;this.element.classList.toggle("kubik-interface-filters__field--tags-filter-disabled",e)}}m.targets=["section","untagged"];const g=["kubik-modal","kubik-offcanvas","kubik-typeahead","kubik-token-input","kubik-debounced-form-submit","kubik-filter-tags-section"];function k(n){n.register("kubik-modal",d),n.register("kubik-offcanvas",c),n.register("kubik-typeahead",o),n.register("kubik-token-input",u),n.register("kubik-debounced-form-submit",f),n.register("kubik-filter-tags-section",m)}const T=function(){const n=document.documentElement.getAttribute("data-controller")||"",e=new Set([...n.split(/\s+/).filter(Boolean),"kubik-modal","kubik-offcanvas"]);document.documentElement.setAttribute("data-controller",[...e].join(" "))},b=function(){document.addEventListener("DOMContentLoaded",T)},y=b;i.DebouncedFormSubmitController=f,i.FilterTagsSectionController=m,i.KUBIK_INTERFACE_STIMULUS_MANIFEST=g,i.ModalController=d,i.OffcanvasController=c,i.TokenInputController=u,i.TypeaheadController=o,i.modalInit=b,i.offcanvasInit=y,i.registerKubikInterfaceStimulusControllers=k,Object.defineProperties(i,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubik-cms/interface_elements",
3
- "version": "0.1.11",
3
+ "version": "0.1.14",
4
4
  "license": "MIT",
5
5
  "author": "Primate Inc.",
6
6
  "contributors": [
@@ -10,7 +10,6 @@
10
10
  "url": "https://github.com/kubik-cms/kubik_interface_elements/issues"
11
11
  },
12
12
  "homepage": "https://github.com/kubik-cms/kubik_interface_elements",
13
- "private": false,
14
13
  "repository": {
15
14
  "type": "git",
16
15
  "url": "git://github.com/kubik-cms/kubik_interface_elements.git"