bord 0.5.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 (59) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +193 -0
  4. data/Rakefile +9 -0
  5. data/app/assets/javascripts/bord/application.js +2361 -0
  6. data/app/assets/javascripts/bord/attract.js +319 -0
  7. data/app/assets/javascripts/bord/attractive.js +1642 -0
  8. data/app/assets/javascripts/bord/entry.js +67 -0
  9. data/app/assets/javascripts/bord/request.js +314 -0
  10. data/app/assets/javascripts/bord/runtime/addons/response.js +51 -0
  11. data/app/assets/javascripts/bord/runtime/addons/template.js +120 -0
  12. data/app/assets/javascripts/bord/runtime/debug.js +18 -0
  13. data/app/assets/stylesheets/bord/application.css +736 -0
  14. data/app/controllers/bord/actions_controller.rb +29 -0
  15. data/app/controllers/bord/application_controller.rb +23 -0
  16. data/app/controllers/bord/pages_controller.rb +13 -0
  17. data/app/controllers/bord/records_controller.rb +14 -0
  18. data/app/controllers/bord/widgets_controller.rb +18 -0
  19. data/app/helpers/bord/application_helper.rb +4 -0
  20. data/app/jobs/bord/application_job.rb +4 -0
  21. data/app/models/bord/action.rb +8 -0
  22. data/app/models/bord/action_parameters.rb +19 -0
  23. data/app/models/bord/allowed_actions.rb +65 -0
  24. data/app/models/bord/application_record.rb +5 -0
  25. data/app/models/bord/attract_actions.rb +101 -0
  26. data/app/models/bord/category.rb +18 -0
  27. data/app/models/bord/dashboard.rb +25 -0
  28. data/app/models/bord/entry.rb +98 -0
  29. data/app/models/bord/page/decorator.rb +33 -0
  30. data/app/models/bord/page/record_decorator.rb +44 -0
  31. data/app/models/bord/page.rb +82 -0
  32. data/app/models/bord/widget/decorator.rb +69 -0
  33. data/app/models/bord/widget.rb +40 -0
  34. data/app/models/concerns/bord/conditionable.rb +8 -0
  35. data/app/views/bord/pages/show.html.erb +9 -0
  36. data/app/views/bord/records/show.html.erb +13 -0
  37. data/app/views/bord/shared/_templates.html.erb +75 -0
  38. data/app/views/bord/widgets/_action.html.erb +7 -0
  39. data/app/views/bord/widgets/_widget.html.erb +25 -0
  40. data/app/views/bord/widgets/index.html.erb +17 -0
  41. data/app/views/layouts/bord/application.html.erb +38 -0
  42. data/config/routes.rb +11 -0
  43. data/lib/bord/configuration.rb +60 -0
  44. data/lib/bord/engine.rb +11 -0
  45. data/lib/bord/loader.rb +8 -0
  46. data/lib/bord/options.rb +17 -0
  47. data/lib/bord/presets/action_mailbox.json +20 -0
  48. data/lib/bord/presets/active_storage.json +20 -0
  49. data/lib/bord/presets/devise.json +1 -0
  50. data/lib/bord/presets/good_job.json +25 -0
  51. data/lib/bord/presets/sidekiq.json +28 -0
  52. data/lib/bord/presets/solid_queue.json +12 -0
  53. data/lib/bord/presets/stripe.json +30 -0
  54. data/lib/bord/presets/user.json +22 -0
  55. data/lib/bord/version.rb +3 -0
  56. data/lib/bord.rb +71 -0
  57. data/lib/generators/bord/install_generator.rb +16 -0
  58. data/lib/generators/bord/presets_generator.rb +62 -0
  59. metadata +116 -0
@@ -0,0 +1,2361 @@
1
+ (() => {
2
+ // attractive.js
3
+ var Hooks = class {
4
+ #before = /* @__PURE__ */ new Set();
5
+ #after = /* @__PURE__ */ new Set();
6
+ #error = /* @__PURE__ */ new Set();
7
+ addBefore(callback) {
8
+ this.#before.add(callback);
9
+ return this;
10
+ }
11
+ addAfter(callback) {
12
+ this.#after.add(callback);
13
+ return this;
14
+ }
15
+ addError(callback) {
16
+ this.#error.add(callback);
17
+ return this;
18
+ }
19
+ removeBefore(callback) {
20
+ this.#before.delete(callback);
21
+ return this;
22
+ }
23
+ removeAfter(callback) {
24
+ this.#after.delete(callback);
25
+ return this;
26
+ }
27
+ removeError(callback) {
28
+ this.#error.delete(callback);
29
+ return this;
30
+ }
31
+ runBefore(context) {
32
+ for (const callback of this.#before) if (callback(context) === false) return false;
33
+ }
34
+ runAfter(context) {
35
+ for (const callback of this.#after) callback(context);
36
+ }
37
+ runError(context) {
38
+ for (const callback of this.#error) callback(context);
39
+ }
40
+ };
41
+ var Registry = class {
42
+ #actions = /* @__PURE__ */ new Map();
43
+ #gates = /* @__PURE__ */ new Map();
44
+ #triggers = /* @__PURE__ */ new Map();
45
+ #eventModifiers = /* @__PURE__ */ new Map();
46
+ #activeActions = null;
47
+ addAction(name, action, group = null) {
48
+ this.#actions.set(name, {
49
+ action,
50
+ group
51
+ });
52
+ }
53
+ getAction(name) {
54
+ const entry = this.#actions.get(name);
55
+ return entry ? entry.action : void 0;
56
+ }
57
+ hasAction(name) {
58
+ return this.#actions.has(name);
59
+ }
60
+ setActiveActions(actionNames) {
61
+ this.#activeActions = actionNames;
62
+ }
63
+ isAllowed(actionName) {
64
+ if (!this.#activeActions) return true;
65
+ return this.#activeActions.has(actionName);
66
+ }
67
+ addGate(name, gate) {
68
+ this.#gates.set(name, gate);
69
+ }
70
+ getGate(name) {
71
+ return this.#gates.get(name);
72
+ }
73
+ hasGate(name) {
74
+ return this.#gates.has(name);
75
+ }
76
+ addTrigger(name, trigger) {
77
+ this.#triggers.set(name, trigger);
78
+ }
79
+ getTrigger(name) {
80
+ return this.#triggers.get(name);
81
+ }
82
+ hasTrigger(name) {
83
+ return this.#triggers.has(name);
84
+ }
85
+ addEventModifier(name, eventModifier) {
86
+ this.#eventModifiers.set(name, eventModifier);
87
+ }
88
+ getEventModifier(name) {
89
+ return this.#eventModifiers.get(name);
90
+ }
91
+ };
92
+ var RESERVED = /* @__PURE__ */ new Set(["@target", "@targets"]);
93
+ function actionAttributes(element) {
94
+ if (!element || !element.attributes) return false;
95
+ for (const attribute of element.attributes) {
96
+ if (RESERVED.has(attribute.name)) continue;
97
+ if (attribute.name.startsWith("@")) return true;
98
+ }
99
+ return false;
100
+ }
101
+ function getActionAttributes({ on: element }) {
102
+ const attributes = [];
103
+ for (const attribute of element.attributes) {
104
+ if (RESERVED.has(attribute.name)) continue;
105
+ if (attribute.name.startsWith("@")) attributes.push(parseAttribute(attribute.name, attribute.value));
106
+ }
107
+ return attributes;
108
+ }
109
+ function parseAttribute(name, value) {
110
+ if (name === "@action" || name === "@") return {
111
+ event: null,
112
+ modifiers: [],
113
+ value
114
+ };
115
+ const parts = name.slice(1).split(".");
116
+ return {
117
+ event: parts[0],
118
+ modifiers: parts.slice(1).flatMap((part) => part.split("+")),
119
+ value
120
+ };
121
+ }
122
+ function getTargetValue(element) {
123
+ return element.getAttribute("@target");
124
+ }
125
+ function getTargetsValue(element) {
126
+ return element.getAttribute("@targets");
127
+ }
128
+ var Evaluate = class {
129
+ #registry;
130
+ constructor(registry) {
131
+ this.#registry = registry;
132
+ }
133
+ async run(action, { for: event, on: element, using: defaultEventType, triggeredBy: directive, state }, { execute }) {
134
+ if (action.startsWith("js:")) return await execute(action, { with: {
135
+ on: element,
136
+ for: event,
137
+ triggeredBy: directive || null,
138
+ state
139
+ } });
140
+ if (action.includes(":")) action = this.#stripDirectives({
141
+ from: action,
142
+ for: event,
143
+ on: element
144
+ });
145
+ if (action === void 0) return;
146
+ return await execute(action, { with: {
147
+ on: element,
148
+ for: event,
149
+ triggeredBy: directive || null,
150
+ state
151
+ } });
152
+ }
153
+ #stripDirectives({ from: action, for: event, on: element }) {
154
+ const [base, ...directives] = action.split(":");
155
+ if (!directives.filter((name) => !(this.#registry.hasTrigger(name) && event.type === name)).every((name) => this.#passes(name, {
156
+ for: event,
157
+ on: element
158
+ }))) return;
159
+ return base;
160
+ }
161
+ #passes(name, { for: event, on: element }) {
162
+ const gated = this.#registry.getGate(name);
163
+ if (!gated) return event.type === name;
164
+ return gated(element, { event }) !== false;
165
+ }
166
+ };
167
+ var Debug = class {
168
+ static enabled = false;
169
+ static prefix = "\u{1F9F2} ";
170
+ static log(...args) {
171
+ if (this.enabled) console.log(this.prefix, ...args);
172
+ }
173
+ static warn(...args) {
174
+ if (this.enabled) console.warn(this.prefix, ...args);
175
+ }
176
+ static error(...args) {
177
+ if (this.enabled) console.error(this.prefix, ...args);
178
+ }
179
+ };
180
+ var Execute = class {
181
+ #registry;
182
+ #hooks;
183
+ #onError;
184
+ #getTargetValue;
185
+ #getTargetsValue;
186
+ constructor(registry, hooks, onError, getTargetValue2, getTargetsValue2) {
187
+ this.#registry = registry;
188
+ this.#hooks = hooks;
189
+ this.#onError = onError;
190
+ this.#getTargetValue = getTargetValue2;
191
+ this.#getTargetsValue = getTargetsValue2;
192
+ }
193
+ async run(action, { with: { on: element, for: event, triggeredBy: directive, state } }) {
194
+ const resolved = this.#resolve({ from: action });
195
+ if (resolved === void 0) return;
196
+ const { name, value } = resolved;
197
+ const target = this.#getTargetValue(element);
198
+ const targets = this.#getTargetsValue(element);
199
+ const hookContext = this.#hookContext({
200
+ name,
201
+ value,
202
+ on: element,
203
+ for: event,
204
+ target,
205
+ targets
206
+ });
207
+ const actionContext = this.#actionContext({
208
+ name,
209
+ value,
210
+ on: element,
211
+ for: event,
212
+ target,
213
+ targets,
214
+ triggeredBy: directive,
215
+ state
216
+ });
217
+ if (this.#hooks?.runBefore(hookContext) === false) {
218
+ event?.preventDefault();
219
+ return false;
220
+ }
221
+ const startTime = performance.now();
222
+ const result = await this.#invoke({
223
+ name,
224
+ on: element,
225
+ context: actionContext
226
+ });
227
+ const elapsed = performance.now() - startTime;
228
+ this.#hooks?.runAfter({
229
+ ...hookContext,
230
+ result
231
+ });
232
+ this.#log({
233
+ name,
234
+ on: element,
235
+ for: event,
236
+ elapsed,
237
+ target
238
+ });
239
+ if (result === false && event) event.preventDefault();
240
+ return result;
241
+ }
242
+ #resolve({ from: action }) {
243
+ if (action.startsWith("js:")) return {
244
+ name: "js",
245
+ value: action.slice(3)
246
+ };
247
+ const parts = action.split("#");
248
+ const [possibleAction, fallbackAction, fallbackValue] = parts;
249
+ const name = this.#registry.hasAction(possibleAction) ? possibleAction : this.#registry.hasAction(fallbackAction) ? fallbackAction : action;
250
+ if (!this.#registry.isAllowed(name)) return;
251
+ if (typeof this.#registry.getAction(name) !== "function") return;
252
+ return {
253
+ name,
254
+ value: this.#registry.hasAction(possibleAction) ? parts.slice(1).join("#") : fallbackValue ?? null
255
+ };
256
+ }
257
+ #hookContext({ name, value, on: element, for: event, target, targets }) {
258
+ return {
259
+ name,
260
+ element,
261
+ options: {
262
+ value,
263
+ target,
264
+ targets
265
+ },
266
+ event: event || null
267
+ };
268
+ }
269
+ #actionContext({ name, value, on: element, for: event, target, targets, triggeredBy: directive, state }) {
270
+ return {
271
+ value,
272
+ target,
273
+ targets,
274
+ event: event || null,
275
+ actionName: name,
276
+ triggeredBy: directive || null,
277
+ state,
278
+ dataset: element.dataset
279
+ };
280
+ }
281
+ async #invoke({ name, on: element, context }) {
282
+ try {
283
+ const Action2 = this.#registry.getAction(name);
284
+ if (typeof Action2 === "function" && Action2.prototype?.run) {
285
+ const instance = new Action2(element, context);
286
+ instance.element = element;
287
+ instance.options = context;
288
+ return await instance.run();
289
+ }
290
+ return await Action2(element, context);
291
+ } catch (error) {
292
+ this.#reportError({
293
+ name,
294
+ on: element,
295
+ error
296
+ });
297
+ }
298
+ }
299
+ #reportError({ name: actionName, on: element, error }) {
300
+ const targetId = element.id || this.#getTargetValue(element) || "";
301
+ const message = `${actionName} on ${element.tagName.toLowerCase()}#${targetId}: ${error.message}`;
302
+ Debug.error(message);
303
+ if (this.#hooks) this.#hooks.runError({
304
+ name: actionName,
305
+ element,
306
+ error
307
+ });
308
+ if (this.#onError) this.#onError(error, message, {
309
+ actionName,
310
+ element
311
+ });
312
+ }
313
+ #log({ name, on: element, for: event, elapsed, target }) {
314
+ const targetId = element.id || target || "";
315
+ const ref = targetId ? `#${targetId}` : "";
316
+ const tag = element.tagName.toLowerCase();
317
+ Debug.log(`${name} \u2192 ${tag}${ref} (${elapsed.toFixed(2)}ms) [${event?.type}]`);
318
+ }
319
+ };
320
+ var Events = class {
321
+ #evaluate;
322
+ #execute;
323
+ constructor(registry, hooks, onError) {
324
+ this.#evaluate = new Evaluate(registry);
325
+ this.#execute = new Execute(registry, hooks, onError, (element) => getTargetValue(element), (element) => getTargetsValue(element));
326
+ }
327
+ async process(event, { on: element, using: defaultEventType, triggeredBy: directive, with: actionValue, state }) {
328
+ if (!element || !actionValue) return;
329
+ for (const action of this.#splitActions(actionValue)) if (await this.#evaluate.run(action, {
330
+ for: event,
331
+ on: element,
332
+ using: defaultEventType,
333
+ triggeredBy: directive,
334
+ state
335
+ }, { execute: (action2, context) => this.#execute.run(action2, context) }) === false) return false;
336
+ }
337
+ #splitActions(action) {
338
+ if (action.startsWith("js:")) return [action];
339
+ return action.split(" ").filter((action2) => action2);
340
+ }
341
+ };
342
+ var EventTypes = class {
343
+ getDefault({ from: element }) {
344
+ const tagName = element.tagName.toLowerCase();
345
+ const isInput = tagName === "input";
346
+ const inputType = isInput ? element.type || "text" : null;
347
+ return isInput ? this.#defaultEvents.input[inputType] || this.#defaultEvents.input.default : this.#defaultEvents[tagName] || this.#defaultEvents.default;
348
+ }
349
+ #defaultEvents = {
350
+ a: "click",
351
+ button: "click",
352
+ input: {
353
+ checkbox: "change",
354
+ radio: "change",
355
+ submit: "click",
356
+ button: "click",
357
+ reset: "click",
358
+ default: "input"
359
+ },
360
+ select: "change",
361
+ textarea: "input",
362
+ form: "submit",
363
+ default: "click"
364
+ };
365
+ };
366
+ var Triggers = class {
367
+ #registry;
368
+ constructor(registry) {
369
+ this.#registry = registry;
370
+ }
371
+ setup({ for: directive, on: element, trigger: run, argument = null }) {
372
+ const trigger = this.#registry.getTrigger(directive);
373
+ if (!trigger) return false;
374
+ trigger(element, run, argument);
375
+ return true;
376
+ }
377
+ };
378
+ var ElementLifecycleHooks = class {
379
+ #added = /* @__PURE__ */ new Set();
380
+ #removed = /* @__PURE__ */ new Set();
381
+ #beforeRemove = /* @__PURE__ */ new Set();
382
+ #targetAdded = /* @__PURE__ */ new Map();
383
+ #targetRemoved = /* @__PURE__ */ new Map();
384
+ onAdded(callback) {
385
+ this.#added.add(callback);
386
+ return this;
387
+ }
388
+ onRemoved(callback) {
389
+ this.#removed.add(callback);
390
+ return this;
391
+ }
392
+ onBeforeRemove(callback) {
393
+ this.#beforeRemove.add(callback);
394
+ return this;
395
+ }
396
+ onTargetAdded(id, callback) {
397
+ if (!this.#targetAdded.has(id)) this.#targetAdded.set(id, /* @__PURE__ */ new Set());
398
+ this.#targetAdded.get(id).add(callback);
399
+ return this;
400
+ }
401
+ onTargetRemoved(id, callback) {
402
+ if (!this.#targetRemoved.has(id)) this.#targetRemoved.set(id, /* @__PURE__ */ new Set());
403
+ this.#targetRemoved.get(id).add(callback);
404
+ return this;
405
+ }
406
+ hasTarget(id) {
407
+ return this.#targetAdded.has(id) || this.#targetRemoved.has(id);
408
+ }
409
+ notifyAdded(element) {
410
+ this.#added.forEach((fn) => fn(element));
411
+ }
412
+ notifyRemoved(element) {
413
+ this.#removed.forEach((fn) => fn(element));
414
+ }
415
+ notifyBeforeRemove(element) {
416
+ this.#beforeRemove.forEach((fn) => fn(element));
417
+ }
418
+ notifyTargetAdded(element) {
419
+ this.#targetAdded.get(element.id)?.forEach((fn) => fn(element));
420
+ }
421
+ notifyTargetRemoved(element) {
422
+ this.#targetRemoved.get(element.id)?.forEach((fn) => fn(element));
423
+ }
424
+ clear() {
425
+ this.#added.clear();
426
+ this.#removed.clear();
427
+ this.#beforeRemove.clear();
428
+ this.#targetAdded.clear();
429
+ this.#targetRemoved.clear();
430
+ }
431
+ };
432
+ var EventSubscriptions = class {
433
+ #subscriptions = /* @__PURE__ */ new Map();
434
+ #scope = document;
435
+ setScope(scope) {
436
+ this.#scope = scope;
437
+ }
438
+ add(type, callback) {
439
+ if (!this.#subscriptions.has(type)) {
440
+ const listener = (event) => {
441
+ this.#subscriptions.get(type).subscriptions.forEach((fn) => fn(event));
442
+ };
443
+ this.#scope.addEventListener(type, listener);
444
+ this.#subscriptions.set(type, {
445
+ listener,
446
+ subscriptions: /* @__PURE__ */ new Set()
447
+ });
448
+ }
449
+ this.#subscriptions.get(type).subscriptions.add(callback);
450
+ return this;
451
+ }
452
+ removeAll() {
453
+ this.#subscriptions.forEach(({ listener }, type) => {
454
+ this.#scope.removeEventListener(type, listener);
455
+ });
456
+ this.#subscriptions.clear();
457
+ }
458
+ };
459
+ var AttributePrefixes = class {
460
+ #prefixes = /* @__PURE__ */ new Set();
461
+ add(prefix) {
462
+ this.#prefixes.add(prefix);
463
+ return this;
464
+ }
465
+ matches(element) {
466
+ if (actionAttributes(element)) return true;
467
+ return Array.from(this.#prefixes).some((prefix) => Array.from(element.attributes).some((attribute) => attribute.name.startsWith(prefix)));
468
+ }
469
+ clear() {
470
+ this.#prefixes.clear();
471
+ }
472
+ };
473
+ var debounce = () => {
474
+ let timeoutId;
475
+ return (callback, delay3) => {
476
+ clearTimeout(timeoutId);
477
+ timeoutId = setTimeout(callback, delay3);
478
+ };
479
+ };
480
+ var SCOPE_PROPERTY = "__attractiveScope";
481
+ function registerScope(root) {
482
+ if (root && root.nodeType === 1 && !root[SCOPE_PROPERTY]) Object.defineProperty(root, SCOPE_PROPERTY, {
483
+ value: true,
484
+ configurable: true
485
+ });
486
+ }
487
+ function unregisterScope(root) {
488
+ if (root && root.nodeType === 1 && root[SCOPE_PROPERTY]) delete root[SCOPE_PROPERTY];
489
+ }
490
+ function insideNestedScope(element, scope) {
491
+ let node = element;
492
+ while (node && node.nodeType === 1 && node !== scope) {
493
+ if (node[SCOPE_PROPERTY]) return true;
494
+ node = node.parentElement;
495
+ }
496
+ return false;
497
+ }
498
+ function scopeOf(element) {
499
+ let node = element;
500
+ while (node && node.nodeType === 1) {
501
+ if (node[SCOPE_PROPERTY]) return node;
502
+ node = node.parentElement;
503
+ }
504
+ return document;
505
+ }
506
+ var debounceTimers = /* @__PURE__ */ new WeakMap();
507
+ var Actions = class Actions2 {
508
+ static #nonBubblingEvents = /* @__PURE__ */ new Set([
509
+ "mouseenter",
510
+ "mouseleave",
511
+ "focus",
512
+ "blur",
513
+ "load",
514
+ "error",
515
+ "unload",
516
+ "resize",
517
+ "scroll"
518
+ ]);
519
+ #registry;
520
+ #events;
521
+ #eventTypes;
522
+ #triggers;
523
+ #listeners;
524
+ #element;
525
+ #scope;
526
+ constructor(registry, events, eventTypes, triggers, listeners, element) {
527
+ this.#registry = registry;
528
+ this.#events = events;
529
+ this.#eventTypes = eventTypes;
530
+ this.#triggers = triggers;
531
+ this.#listeners = listeners;
532
+ this.#element = element;
533
+ this.#scope = element;
534
+ }
535
+ prepare(element) {
536
+ const attributes = getActionAttributes({ on: element });
537
+ if (attributes.length === 0) return;
538
+ this.#registerDirectListeners({
539
+ on: element,
540
+ from: attributes
541
+ });
542
+ this.#registerDelegationListeners({
543
+ on: element,
544
+ from: attributes
545
+ });
546
+ this.#setupDirectiveTriggers({
547
+ on: element,
548
+ from: attributes
549
+ });
550
+ }
551
+ process(event, context = null) {
552
+ const element = context ? context.element : this.#actionElement(event.target);
553
+ if (!element) return;
554
+ if (!this.#scope.contains(element)) return;
555
+ if (insideNestedScope(element, this.#scope)) return;
556
+ this.#debounced(() => this.#execute({
557
+ event,
558
+ with: context,
559
+ on: element
560
+ }), element);
561
+ }
562
+ #registerDirectListeners({ on: element, from: attributes }) {
563
+ for (const { event: eventName, modifiers, value } of attributes) {
564
+ const eventType = eventName || this.#defaultEventType({ for: element });
565
+ if (modifiers.includes("window") || modifiers.includes("document")) {
566
+ const target = modifiers.includes("window") ? window : document;
567
+ this.#listeners.addTargetedEventListener({
568
+ for: eventType,
569
+ on: target,
570
+ element
571
+ });
572
+ continue;
573
+ }
574
+ if (Actions2.#nonBubblingEvents.has(eventType)) element.addEventListener(eventType, (event) => {
575
+ if (insideNestedScope(element, this.#scope)) return;
576
+ this.#events.process(event, {
577
+ on: element,
578
+ using: this.#defaultEventType({ for: element }),
579
+ with: value
580
+ });
581
+ });
582
+ }
583
+ }
584
+ #registerDelegationListeners({ on: element, from: attributes }) {
585
+ const eventTypes = /* @__PURE__ */ new Set();
586
+ for (const { event: eventName, modifiers } of attributes) {
587
+ if (modifiers.includes("window") || modifiers.includes("document")) continue;
588
+ const eventType = eventName || this.#defaultEventType({ for: element });
589
+ if (Actions2.#nonBubblingEvents.has(eventType)) continue;
590
+ eventTypes.add(eventType);
591
+ }
592
+ eventTypes.forEach((eventType) => {
593
+ this.#listeners.addEventListeners({
594
+ for: eventType,
595
+ on: this.#element
596
+ });
597
+ });
598
+ }
599
+ #setupDirectiveTriggers({ on: element, from: attributes }) {
600
+ const directives = [...new Set(attributes.filter(({ value }) => !value.startsWith("js:")).flatMap(({ value }) => value.split(" ").filter((name) => name.includes(":")).flatMap((name) => name.split(":").slice(1))))];
601
+ const defaultEventType = this.#defaultEventType({ for: element });
602
+ directives.forEach((name) => {
603
+ this.#triggers.setup({
604
+ for: name,
605
+ on: element,
606
+ trigger: (state) => {
607
+ this.#debounced(() => {
608
+ attributes.forEach(({ value: actionValue }) => {
609
+ this.#events.process({ type: name }, {
610
+ on: element,
611
+ using: defaultEventType,
612
+ triggeredBy: name,
613
+ with: actionValue,
614
+ state
615
+ });
616
+ });
617
+ }, element);
618
+ }
619
+ });
620
+ });
621
+ }
622
+ #debounced(run, element) {
623
+ const delay3 = this.#debounceDelay(element);
624
+ if (delay3 > 0) {
625
+ let timer = debounceTimers.get(element);
626
+ if (!timer) {
627
+ timer = debounce();
628
+ debounceTimers.set(element, timer);
629
+ }
630
+ timer(run, delay3);
631
+ return;
632
+ }
633
+ run();
634
+ }
635
+ #debounceDelay(element) {
636
+ return parseInt(element.dataset.debounce ?? element.dataset.formDebounce ?? element.dataset.requestDebounce ?? 0);
637
+ }
638
+ #execute({ event, with: context, on: element }) {
639
+ if (!this.#scope.contains(element)) return;
640
+ if (insideNestedScope(element, this.#scope)) return;
641
+ const defaultEventType = context ? context.eventType : this.#defaultEventType({ for: element });
642
+ const attributes = getActionAttributes({ on: element });
643
+ for (const { event: eventName, modifiers, value } of attributes) {
644
+ if ((eventName !== null ? eventName : defaultEventType) !== event.type) continue;
645
+ if (this.#blockedByEventModifiers({
646
+ for: event,
647
+ on: element,
648
+ modifiers
649
+ })) continue;
650
+ this.#events.process(event, {
651
+ on: element,
652
+ using: defaultEventType,
653
+ with: value
654
+ });
655
+ }
656
+ }
657
+ #blockedByEventModifiers({ for: event, on: element, modifiers }) {
658
+ return modifiers.some((name) => {
659
+ const eventModifier = this.#registry.getEventModifier(name);
660
+ if (eventModifier) return eventModifier(event, element) === false;
661
+ if (event.key === void 0) return false;
662
+ return event.key.toLowerCase() !== name.toLowerCase();
663
+ });
664
+ }
665
+ #defaultEventType({ for: element }) {
666
+ return this.#eventTypes.getDefault({ from: element });
667
+ }
668
+ #actionElement(element) {
669
+ while (element) {
670
+ if (actionAttributes(element)) return element;
671
+ element = element.parentElement;
672
+ }
673
+ return null;
674
+ }
675
+ };
676
+ var EventListeners = class {
677
+ #eventListeners = /* @__PURE__ */ new Map();
678
+ #elementListeners = /* @__PURE__ */ new WeakMap();
679
+ #targetedEventListeners = /* @__PURE__ */ new Map();
680
+ #targetedEvents = /* @__PURE__ */ new Map();
681
+ #process;
682
+ constructor(process) {
683
+ this.#process = process;
684
+ }
685
+ addEventListeners({ for: eventType, on: element }) {
686
+ if (this.#eventListeners.has(eventType)) return;
687
+ const processEvent = (event) => this.#process(event);
688
+ element.addEventListener(eventType, processEvent);
689
+ Debug.log("Added event listener for", eventType, "to", element);
690
+ this.#eventListeners.set(eventType, {
691
+ listener: processEvent,
692
+ element
693
+ });
694
+ }
695
+ addTargetedEventListener({ for: eventType, on: target, element }) {
696
+ const key = `${target === window ? "window" : "document"}:${eventType}`;
697
+ if (!this.#elementListeners.has(element)) this.#elementListeners.set(element, /* @__PURE__ */ new Set());
698
+ this.#elementListeners.get(element).add(key);
699
+ if (!this.#targetedEvents.has(key)) this.#targetedEvents.set(key, /* @__PURE__ */ new Set());
700
+ this.#targetedEvents.get(key).add(element);
701
+ if (!this.#targetedEventListeners.has(key)) {
702
+ const processElements = (event) => {
703
+ const elements = this.#targetedEvents.get(key);
704
+ if (!elements) return;
705
+ elements.forEach((element2) => {
706
+ this.#process(event, {
707
+ element: element2,
708
+ eventType
709
+ });
710
+ });
711
+ };
712
+ target.addEventListener(eventType, processElements);
713
+ this.#targetedEventListeners.set(key, processElements);
714
+ }
715
+ }
716
+ cleanup(element) {
717
+ const keys = this.#elementListeners.get(element);
718
+ if (!keys) return;
719
+ keys.forEach((key) => {
720
+ const events = this.#targetedEvents.get(key);
721
+ if (events) {
722
+ events.delete(element);
723
+ if (events.size === 0) {
724
+ const [targetName, eventType] = key.split(":");
725
+ const listener = this.#targetedEventListeners.get(key);
726
+ (targetName === "window" ? window : document).removeEventListener(eventType, listener);
727
+ this.#targetedEventListeners.delete(key);
728
+ this.#targetedEvents.delete(key);
729
+ }
730
+ }
731
+ });
732
+ this.#elementListeners.delete(element);
733
+ }
734
+ removeAll() {
735
+ for (const [eventType, { listener, element }] of this.#eventListeners) element.removeEventListener(eventType, listener);
736
+ this.#eventListeners.clear();
737
+ for (const [key, listener] of this.#targetedEventListeners) {
738
+ const [targetName, eventType] = key.split(":");
739
+ (targetName === "window" ? window : document).removeEventListener(eventType, listener);
740
+ }
741
+ this.#targetedEventListeners.clear();
742
+ this.#targetedEvents.clear();
743
+ this.#elementListeners = /* @__PURE__ */ new WeakMap();
744
+ }
745
+ };
746
+ var ELEMENT_NODE = typeof Node !== "undefined" && Node.ELEMENT_NODE || 1;
747
+ var ATTRIBUTE_PREFIX = "@";
748
+ var RESERVED_ATTRIBUTES = /* @__PURE__ */ new Set(["@target", "@targets"]);
749
+ var Observer = class {
750
+ #prepare;
751
+ #cleanup;
752
+ #beforeCleanup;
753
+ #observer;
754
+ #scope;
755
+ constructor(prepare, cleanup = null, scope = document.documentElement, beforeCleanup = null) {
756
+ this.#prepare = prepare;
757
+ this.#cleanup = cleanup;
758
+ this.#beforeCleanup = beforeCleanup;
759
+ this.#scope = scope;
760
+ }
761
+ start(action) {
762
+ if (!window.MutationObserver) return;
763
+ this.#observer = new MutationObserver((mutations) => {
764
+ const added = /* @__PURE__ */ new Set();
765
+ const removed = /* @__PURE__ */ new Set();
766
+ const changed = /* @__PURE__ */ new Set();
767
+ for (const mutation of mutations) {
768
+ if (mutation.type === "childList") {
769
+ this.#processChildMutation(mutation, {
770
+ for: action,
771
+ elements: {
772
+ added,
773
+ removed
774
+ }
775
+ });
776
+ continue;
777
+ }
778
+ if (mutation.type === "attributes" && mutation.attributeName.startsWith(ATTRIBUTE_PREFIX) && !RESERVED_ATTRIBUTES.has(mutation.attributeName)) changed.add(mutation.target);
779
+ }
780
+ added.forEach((element) => {
781
+ Debug.log("Element added:", element.tagName.toLowerCase(), "#" + (element.id || element.dataset.target || ""));
782
+ this.#prepare(element);
783
+ });
784
+ if (this.#beforeCleanup || this.#cleanup) removed.forEach((element) => {
785
+ Debug.log("Element removed:", element.tagName.toLowerCase(), "#" + (element.id || ""));
786
+ this.#beforeCleanup?.(element);
787
+ this.#cleanup?.(element);
788
+ });
789
+ if (this.#cleanup) changed.forEach((element) => {
790
+ if (removed.has(element)) return;
791
+ Debug.log("Attribute changed:", element.tagName.toLowerCase(), "#" + (element.id || ""));
792
+ this.#cleanup(element);
793
+ if (action(element)) this.#prepare(element);
794
+ });
795
+ });
796
+ this.#observer.observe(this.#scope, {
797
+ childList: true,
798
+ subtree: true,
799
+ attributes: true
800
+ });
801
+ return this;
802
+ }
803
+ stop() {
804
+ if (this.#observer) this.#observer.disconnect();
805
+ return this;
806
+ }
807
+ #processChildMutation(mutation, { for: action, elements: { added, removed } }) {
808
+ mutation.addedNodes.forEach((node) => {
809
+ this.#processNode(node, {
810
+ for: action,
811
+ and: added
812
+ });
813
+ });
814
+ mutation.removedNodes.forEach((node) => {
815
+ this.#processNode(node, {
816
+ for: action,
817
+ and: removed
818
+ });
819
+ });
820
+ }
821
+ #processNode(node, { for: action, and: elements }) {
822
+ if (node.nodeType !== ELEMENT_NODE) return;
823
+ if (action(node)) elements.add(node);
824
+ if (!node.querySelectorAll) return;
825
+ node.querySelectorAll("*").forEach((element) => {
826
+ if (action(element)) elements.add(element);
827
+ });
828
+ }
829
+ };
830
+ var Activation = class {
831
+ #registry;
832
+ #scope;
833
+ #events;
834
+ #eventTypes;
835
+ #triggers;
836
+ #listeners;
837
+ #elementLifecycle;
838
+ #subscriptions;
839
+ #attributePrefixes;
840
+ #owner;
841
+ #actions;
842
+ #observe;
843
+ #initialized = false;
844
+ constructor(dependencies) {
845
+ this.#registry = dependencies.registry;
846
+ this.#events = dependencies.events;
847
+ this.#eventTypes = dependencies.eventTypes;
848
+ this.#triggers = dependencies.triggers;
849
+ this.#elementLifecycle = dependencies.elementLifecycle;
850
+ this.#subscriptions = dependencies.subscriptions;
851
+ this.#attributePrefixes = dependencies.attributePrefixes;
852
+ this.#owner = dependencies.owner;
853
+ this.#listeners = new EventListeners((event, context) => this.#actions?.process(event, context));
854
+ }
855
+ get active() {
856
+ return this.#initialized;
857
+ }
858
+ activate(options = {}) {
859
+ const { on = document, debug = false, extendWith = [], addActions = {}, addGates = {}, addTriggers = {} } = options;
860
+ Debug.enabled = debug;
861
+ if (!on) {
862
+ Debug.error("scope element not found: activate() requires a valid DOM element");
863
+ return this;
864
+ }
865
+ if (this.#initialized) return this;
866
+ for (const [name, action] of Object.entries(addActions)) this.#registry.addAction(name, action);
867
+ for (const [name, action] of Object.entries(addGates)) this.#registry.addGate(name, action);
868
+ for (const [name, action] of Object.entries(addTriggers)) this.#registry.addTrigger(name, action);
869
+ this.#scope = on;
870
+ registerScope(on);
871
+ this.#subscriptions.setScope(on);
872
+ this.#actions = new Actions(this.#registry, this.#events, this.#eventTypes, this.#triggers, this.#listeners, on);
873
+ this.#observe = new Observer((element) => {
874
+ this.#elementLifecycle.notifyAdded(element);
875
+ this.#elementLifecycle.notifyTargetAdded(element);
876
+ this.#actions.prepare(element);
877
+ }, (element) => {
878
+ this.#listeners.cleanup(element);
879
+ this.#elementLifecycle.notifyRemoved(element);
880
+ this.#elementLifecycle.notifyTargetRemoved(element);
881
+ }, on, (element) => {
882
+ this.#elementLifecycle.notifyBeforeRemove(element);
883
+ });
884
+ const elements = [on, ...on.querySelectorAll("*")];
885
+ const actionElements = [];
886
+ for (const element of elements) if (this.#shouldPrepare(element)) actionElements.push(element);
887
+ for (const extension2 of extendWith) extension2({
888
+ instance: this.#owner,
889
+ registry: this.#registry
890
+ });
891
+ actionElements.forEach((element) => {
892
+ this.#elementLifecycle.notifyAdded(element);
893
+ this.#elementLifecycle.notifyTargetAdded(element);
894
+ });
895
+ actionElements.forEach((element) => {
896
+ this.#actions.prepare(element);
897
+ });
898
+ this.#observe.start((element) => this.#shouldPrepare(element));
899
+ this.#initialized = true;
900
+ if (Debug.enabled) Debug.log(`active \u2014 ${actionElements.length} element${actionElements.length === 1 ? "" : "s"} with actions`);
901
+ return this;
902
+ }
903
+ deactivate() {
904
+ if (!this.#initialized) return this;
905
+ unregisterScope(this.#scope);
906
+ this.#listeners.removeAll();
907
+ if (this.#observe) this.#observe.stop();
908
+ this.#subscriptions.removeAll();
909
+ this.#elementLifecycle.clear();
910
+ this.#attributePrefixes.clear();
911
+ this.#initialized = false;
912
+ Debug.log("deactivated");
913
+ return this;
914
+ }
915
+ notifyExistingTargets(id) {
916
+ if (!this.#scope) return this;
917
+ this.#scope.querySelectorAll(`[id="${id}"]`).forEach((element) => {
918
+ this.#elementLifecycle.notifyTargetAdded(element);
919
+ });
920
+ return this;
921
+ }
922
+ #shouldPrepare(element) {
923
+ return (this.#attributePrefixes.matches(element) || this.#elementLifecycle.hasTarget(element.id)) && !insideNestedScope(element, this.#scope);
924
+ }
925
+ };
926
+ function defaultEventModifier(registry) {
927
+ registry.addEventModifier("window", () => true);
928
+ registry.addEventModifier("document", () => true);
929
+ }
930
+ var Attractive = class Attractive2 {
931
+ #registry = new Registry();
932
+ #events;
933
+ #eventTypes;
934
+ #triggers;
935
+ #activation;
936
+ #hooks = new Hooks();
937
+ #elementLifecycle = new ElementLifecycleHooks();
938
+ #subscriptions = new EventSubscriptions();
939
+ #attributePrefixes = new AttributePrefixes();
940
+ static activate(options = {}) {
941
+ const instance = new this(options);
942
+ instance.activate(options);
943
+ return instance;
944
+ }
945
+ /**
946
+ * Returns whether debug logging is enabled.
947
+ *
948
+ * @returns {boolean} — current debug state
949
+ */
950
+ static get debug() {
951
+ return Debug.enabled;
952
+ }
953
+ /**
954
+ * Toggle debug logging on or off.
955
+ *
956
+ * @param {boolean} value — true to enable debug output
957
+ */
958
+ static set debug(value) {
959
+ Debug.enabled = value;
960
+ }
961
+ get debug() {
962
+ return Debug.enabled;
963
+ }
964
+ set debug(value) {
965
+ Debug.enabled = value;
966
+ }
967
+ /**
968
+ * Returns whether the instance is currently active.
969
+ *
970
+ * @returns {boolean} — true if activate() has been called and deactivate() has not
971
+ */
972
+ get active() {
973
+ return this.#activation.active;
974
+ }
975
+ static onError(error, message) {
976
+ console.warn(`[attractive] ${message}`, error);
977
+ if (typeof window.onerror === "function") window.onerror(message, null, null, null, error);
978
+ }
979
+ constructor() {
980
+ this.#events = new Events(this.#registry, this.#hooks, (error, message, detail) => Attractive2.onError(error, message, detail));
981
+ this.#eventTypes = new EventTypes();
982
+ this.#triggers = new Triggers(this.#registry);
983
+ defaultEventModifier(this.#registry);
984
+ this.#activation = new Activation({
985
+ registry: this.#registry,
986
+ events: this.#events,
987
+ eventTypes: this.#eventTypes,
988
+ triggers: this.#triggers,
989
+ elementLifecycle: this.#elementLifecycle,
990
+ subscriptions: this.#subscriptions,
991
+ attributePrefixes: this.#attributePrefixes,
992
+ owner: this
993
+ });
994
+ }
995
+ /**
996
+ * Activates the Attractive instance on the given scope.
997
+ *
998
+ * @param {Object} [options] — activation options
999
+ * @param {HTMLElement|Document} [options.on=document] — root element to observe
1000
+ * @param {boolean} [options.debug=false] — enable debug logging
1001
+ * @returns {Attractive} — the instance for chaining
1002
+ */
1003
+ activate(options = {}) {
1004
+ this.#activation.activate(options);
1005
+ return this;
1006
+ }
1007
+ /**
1008
+ * Restricts available actions to the given names.
1009
+ *
1010
+ * @param {string[]} [actionNames] — action names to enable (all enabled if empty)
1011
+ * @returns {Attractive} — the instance for chaining
1012
+ */
1013
+ withActions(actionNames = []) {
1014
+ Debug.log("Initializing with actions", actionNames);
1015
+ if (actionNames.length > 0) this.#registry.setActiveActions(new Set(actionNames));
1016
+ return this;
1017
+ }
1018
+ /**
1019
+ * Registers a callback that runs before each action.
1020
+ * Return false to cancel the action.
1021
+ *
1022
+ * @param {Function} callback — receives { name, element, options, event }
1023
+ * @returns {Attractive} — the instance for chaining
1024
+ */
1025
+ beforeAction(callback) {
1026
+ this.#hooks.addBefore(callback);
1027
+ return this;
1028
+ }
1029
+ /**
1030
+ * Registers a callback that runs after each successful action.
1031
+ *
1032
+ * @param {Function} callback — receives { name, element, options, event, result }
1033
+ * @returns {Attractive} — the instance for chaining
1034
+ */
1035
+ afterAction(callback) {
1036
+ this.#hooks.addAfter(callback);
1037
+ return this;
1038
+ }
1039
+ /**
1040
+ * Registers a callback that runs when an action throws an error.
1041
+ *
1042
+ * @param {Function} callback — receives { name, element, options, event, error }
1043
+ * @returns {Attractive} — the instance for chaining
1044
+ */
1045
+ onError(callback) {
1046
+ this.#hooks.addError(callback);
1047
+ return this;
1048
+ }
1049
+ /**
1050
+ * Deactivates the instance, removing all event listeners and observer.
1051
+ *
1052
+ * @returns {Attractive} — the instance for chaining
1053
+ */
1054
+ deactivate() {
1055
+ this.#activation.deactivate();
1056
+ return this;
1057
+ }
1058
+ /**
1059
+ * Deactivates and reactivates the instance with optional new options.
1060
+ *
1061
+ * @param {Object} [options] — same options as activate()
1062
+ * @returns {Attractive} — the instance for chaining
1063
+ */
1064
+ restart(options = {}) {
1065
+ this.deactivate();
1066
+ return this.activate(options);
1067
+ }
1068
+ onElementAdded(callback) {
1069
+ this.#elementLifecycle.onAdded(callback);
1070
+ return this;
1071
+ }
1072
+ onElementRemoved(callback) {
1073
+ this.#elementLifecycle.onRemoved(callback);
1074
+ return this;
1075
+ }
1076
+ onBeforeElementRemoved(callback) {
1077
+ this.#elementLifecycle.onBeforeRemove(callback);
1078
+ return this;
1079
+ }
1080
+ onTargetConnected(id, callback) {
1081
+ this.#elementLifecycle.onTargetAdded(id, callback);
1082
+ this.#activation.notifyExistingTargets(id);
1083
+ return this;
1084
+ }
1085
+ onTargetDisconnected(id, callback) {
1086
+ this.#elementLifecycle.onTargetRemoved(id, callback);
1087
+ return this;
1088
+ }
1089
+ addEventListener(type, callback) {
1090
+ this.#subscriptions.add(type, callback);
1091
+ return this;
1092
+ }
1093
+ observeAttribute(prefix) {
1094
+ this.#attributePrefixes.add(prefix);
1095
+ return this;
1096
+ }
1097
+ };
1098
+ var ActionBase = class {
1099
+ static actionFor(method) {
1100
+ return (element, options = {}) => {
1101
+ return new this(element, options)[method]();
1102
+ };
1103
+ }
1104
+ constructor(element, options = {}) {
1105
+ if (!element) throw new Error("Current element is required");
1106
+ this.element = element;
1107
+ this.target = options.target;
1108
+ this.targetsSelector = options.targets;
1109
+ this.options = options;
1110
+ }
1111
+ get targets() {
1112
+ const scope = scopeOf(this.element);
1113
+ if (this.targetsSelector) return Array.from(scope.querySelectorAll(this.targetsSelector));
1114
+ if (this.target) {
1115
+ const target = scope.querySelector(`[id="${this.target}"]`);
1116
+ if (!target) Debug.warn(`Target "#${this.target}" not found`);
1117
+ return target ? [target] : [];
1118
+ }
1119
+ return [this.element];
1120
+ }
1121
+ cycledValue(currentValue, nextValues) {
1122
+ const values = Array.isArray(nextValues) ? nextValues : nextValues.split(",").map((value) => value.trim());
1123
+ return values[(values.indexOf(currentValue) + 1) % values.length];
1124
+ }
1125
+ };
1126
+ var Action = class extends ActionBase {
1127
+ get value() {
1128
+ return this.options.value;
1129
+ }
1130
+ get dataset() {
1131
+ return this.element.dataset;
1132
+ }
1133
+ dispatchEvent(name, detail = {}) {
1134
+ this.element.dispatchEvent(new CustomEvent(name, {
1135
+ bubbles: true,
1136
+ detail
1137
+ }));
1138
+ }
1139
+ };
1140
+ var sanitize = (value) => {
1141
+ return value?.split(",").map((className) => className.trim()).filter(Boolean) ?? [];
1142
+ };
1143
+ var Class = class extends ActionBase {
1144
+ constructor(element, options = {}) {
1145
+ super(element, options);
1146
+ this.value = sanitize(options.value);
1147
+ }
1148
+ toggle() {
1149
+ if (!this.value) return;
1150
+ this.targets.forEach((target) => this.#toggleClasses({ forEach: target }));
1151
+ }
1152
+ cycle() {
1153
+ if (!this.value || this.value.length === 0) return;
1154
+ this.targets.forEach((target) => this.#cycleClasses(target));
1155
+ }
1156
+ add() {
1157
+ if (!this.value) return;
1158
+ this.targets.forEach((target) => target.classList.add(...this.value));
1159
+ }
1160
+ set() {
1161
+ const key = this.element.dataset.store;
1162
+ if (key) {
1163
+ const value = globalThis.$store?.get(key);
1164
+ if (value === void 0) return;
1165
+ this.targets.forEach((target) => target.classList.toggle(...this.value, !!value));
1166
+ return;
1167
+ }
1168
+ if (!this.value) return;
1169
+ this.targets.forEach((target) => {
1170
+ target.className = "";
1171
+ target.classList.add(...this.value);
1172
+ });
1173
+ }
1174
+ remove() {
1175
+ if (!this.value) return;
1176
+ this.targets.forEach((target) => target.classList.remove(...this.value));
1177
+ }
1178
+ #toggleClasses({ forEach: target }) {
1179
+ this.value.forEach((className) => target.classList.toggle(className));
1180
+ }
1181
+ #cycleClasses(target) {
1182
+ const currentClass = this.value.find((className) => target.classList.contains(className)) || "";
1183
+ const nextClass = this.cycledValue(currentClass, this.value);
1184
+ target.classList.remove(...this.value);
1185
+ target.classList.add(nextClass);
1186
+ }
1187
+ };
1188
+ var actions$9 = {
1189
+ toggleClass: Class.actionFor("toggle"),
1190
+ cycleClass: Class.actionFor("cycle"),
1191
+ addClass: Class.actionFor("add"),
1192
+ setClass: Class.actionFor("set"),
1193
+ removeClass: Class.actionFor("remove")
1194
+ };
1195
+ var delay = () => {
1196
+ let timeoutId;
1197
+ return (callback, delay3) => {
1198
+ clearTimeout(timeoutId);
1199
+ timeoutId = setTimeout(callback, delay3);
1200
+ };
1201
+ };
1202
+ var clearFeedback$1 = delay();
1203
+ var Clipboard = class extends ActionBase {
1204
+ constructor(element, options = {}) {
1205
+ super(element, options);
1206
+ this.value = options.value;
1207
+ }
1208
+ async copy() {
1209
+ const textToCopy = this.value || (this.targets[0]?.value ?? this.targets[0]?.textContent);
1210
+ if (textToCopy === void 0) return;
1211
+ try {
1212
+ await navigator.clipboard.writeText(textToCopy);
1213
+ this.#setFeedback(true);
1214
+ } catch (error) {
1215
+ this.#setFeedback(false);
1216
+ }
1217
+ }
1218
+ #setFeedback(succeeded) {
1219
+ const delay3 = parseInt(this.element.dataset.copyFeedback);
1220
+ this.targets.forEach((target) => target.setAttribute(this.#attributeName, succeeded));
1221
+ if (!delay3) return;
1222
+ clearFeedback$1(() => this.targets.forEach((target) => target.removeAttribute(this.#attributeName)), delay3);
1223
+ }
1224
+ get #attributeName() {
1225
+ return "data-copy-success";
1226
+ }
1227
+ };
1228
+ var actions$8 = { copy: Clipboard.actionFor("copy") };
1229
+ var clearFeedback = delay();
1230
+ var Confirm = class extends ActionBase {
1231
+ confirm() {
1232
+ const message = this.element.dataset.confirmMessage || "Are you sure?";
1233
+ const confirmed = window.confirm(message);
1234
+ this.#setFeedback(confirmed);
1235
+ return confirmed;
1236
+ }
1237
+ #setFeedback(confirmed) {
1238
+ this.element.setAttribute("data-confirm-success", confirmed);
1239
+ const duration = this.element.dataset.confirmFeedback;
1240
+ if (!duration) return;
1241
+ clearFeedback(() => this.element.removeAttribute("data-confirm-success"), parseInt(duration));
1242
+ }
1243
+ };
1244
+ var actions$7 = { confirm: Confirm.actionFor("confirm") };
1245
+ var attributeOperations = {
1246
+ get(element, name) {
1247
+ return element.getAttribute(name);
1248
+ },
1249
+ set(element, name, value) {
1250
+ element.setAttribute(name, value);
1251
+ },
1252
+ has(element, name) {
1253
+ return element.hasAttribute(name);
1254
+ },
1255
+ remove(element, name) {
1256
+ element.removeAttribute(name);
1257
+ }
1258
+ };
1259
+ var dataAttributeOperations = {
1260
+ get(element, name) {
1261
+ return element.dataset[name];
1262
+ },
1263
+ set(element, name, value) {
1264
+ element.dataset[name] = value;
1265
+ },
1266
+ has(element, name) {
1267
+ return name in element.dataset;
1268
+ },
1269
+ remove(element, name) {
1270
+ delete element.dataset[name];
1271
+ }
1272
+ };
1273
+ var DOMAttribute = class extends ActionBase {
1274
+ constructor(element, options = {}) {
1275
+ super(element, options);
1276
+ const [attribute, value] = options.value.split("=");
1277
+ this.attribute = attribute;
1278
+ this.value = value;
1279
+ }
1280
+ toggle() {
1281
+ if (!this.attribute) return;
1282
+ this.targets.forEach((target) => this.operations.has(target, this.attribute) ? this.operations.remove(target, this.attribute) : this.operations.set(target, this.attribute, this.value || ""));
1283
+ }
1284
+ cycle() {
1285
+ if (!this.value) return;
1286
+ this.targets.forEach((target) => this.#cycleAttribute(target));
1287
+ }
1288
+ add() {
1289
+ if (!this.attribute) return;
1290
+ this.targets.forEach((target) => this.operations.set(target, this.attribute, this.value || ""));
1291
+ }
1292
+ set() {
1293
+ const key = this.element.dataset.store;
1294
+ if (key) {
1295
+ const value = globalThis.$store?.get(key);
1296
+ if (value === void 0) return;
1297
+ this.targets.forEach((target) => value ? this.operations.set(target, this.attribute, this.value || "") : this.operations.remove(target, this.attribute));
1298
+ return;
1299
+ }
1300
+ return this.add();
1301
+ }
1302
+ remove() {
1303
+ if (!this.attribute) return;
1304
+ this.targets.forEach((target) => this.operations.remove(target, this.attribute));
1305
+ }
1306
+ #cycleAttribute(target) {
1307
+ const currentValue = this.operations.get(target, this.attribute);
1308
+ const nextValue = this.cycledValue(currentValue, this.value);
1309
+ this.operations.set(target, this.attribute, nextValue);
1310
+ }
1311
+ };
1312
+ var Attribute = class extends DOMAttribute {
1313
+ get operations() {
1314
+ return attributeOperations;
1315
+ }
1316
+ };
1317
+ var DataAttribute = class extends DOMAttribute {
1318
+ get operations() {
1319
+ return dataAttributeOperations;
1320
+ }
1321
+ };
1322
+ var toggleAttribute = Attribute.actionFor("toggle");
1323
+ var cycleAttribute = Attribute.actionFor("cycle");
1324
+ var addAttribute = Attribute.actionFor("add");
1325
+ var setAttribute = Attribute.actionFor("set");
1326
+ var removeAttribute = Attribute.actionFor("remove");
1327
+ var toggleDataAttribute = DataAttribute.actionFor("toggle");
1328
+ var cycleDataAttribute = DataAttribute.actionFor("cycle");
1329
+ var addDataAttribute = DataAttribute.actionFor("add");
1330
+ var setDataAttribute = DataAttribute.actionFor("set");
1331
+ var removeDataAttribute = DataAttribute.actionFor("remove");
1332
+ var attributeActions = {
1333
+ toggleAttribute,
1334
+ cycleAttribute,
1335
+ addAttribute,
1336
+ setAttribute,
1337
+ removeAttribute
1338
+ };
1339
+ var dataAttributeActions = {
1340
+ toggleDataAttribute,
1341
+ cycleDataAttribute,
1342
+ addDataAttribute,
1343
+ setDataAttribute,
1344
+ removeDataAttribute
1345
+ };
1346
+ var Dialog = class extends ActionBase {
1347
+ open() {
1348
+ this.targets.forEach((target) => target instanceof HTMLDialogElement && target.show());
1349
+ }
1350
+ openModal() {
1351
+ this.targets.forEach((target) => target instanceof HTMLDialogElement && target.showModal());
1352
+ }
1353
+ close() {
1354
+ this.targets.forEach((target) => target instanceof HTMLDialogElement && target.close());
1355
+ }
1356
+ };
1357
+ var actions$6 = {
1358
+ open: Dialog.actionFor("open"),
1359
+ openModal: Dialog.actionFor("openModal"),
1360
+ close: Dialog.actionFor("close")
1361
+ };
1362
+ var Focus = class extends ActionBase {
1363
+ focus() {
1364
+ this.targets.forEach((target) => {
1365
+ if (typeof target.focus === "function") target.focus();
1366
+ });
1367
+ }
1368
+ };
1369
+ var actions$5 = { focus: Focus.actionFor("focus") };
1370
+ var Form = class extends ActionBase {
1371
+ requestSubmit() {
1372
+ this.targets.forEach((target) => {
1373
+ const form = target instanceof HTMLFormElement ? target : target.form || null;
1374
+ if (form) form.requestSubmit();
1375
+ });
1376
+ }
1377
+ reset() {
1378
+ this.targets.forEach((target) => target instanceof HTMLFormElement && target.reset());
1379
+ }
1380
+ };
1381
+ var actions$4 = {
1382
+ submit: Form.actionFor("requestSubmit"),
1383
+ reset: Form.actionFor("reset")
1384
+ };
1385
+ var Reload = class extends ActionBase {
1386
+ reload() {
1387
+ this.targets.forEach((target) => {
1388
+ if (this.#reloadable(target)) target.reload();
1389
+ });
1390
+ }
1391
+ get targets() {
1392
+ if (this.target === "window") return [window.location];
1393
+ return super.targets;
1394
+ }
1395
+ #reloadable(target) {
1396
+ return typeof target.reload === "function";
1397
+ }
1398
+ };
1399
+ var reload = Reload.actionFor("reload");
1400
+ var actions$3 = {
1401
+ reload,
1402
+ refresh: reload
1403
+ };
1404
+ var ScrollTo = class extends ActionBase {
1405
+ constructor(element, options = {}) {
1406
+ super(element, options);
1407
+ const validBehaviors = [
1408
+ "auto",
1409
+ "instant",
1410
+ "smooth"
1411
+ ];
1412
+ const behavior = options.value;
1413
+ this.behavior = validBehaviors.includes(behavior) ? behavior : "auto";
1414
+ }
1415
+ scroll() {
1416
+ this.targets[0]?.scrollIntoView({ behavior: this.behavior });
1417
+ }
1418
+ };
1419
+ var actions$2 = { scrollTo: ScrollTo.actionFor("scroll") };
1420
+ var Style = class extends ActionBase {
1421
+ constructor(element, options = {}) {
1422
+ super(element, options);
1423
+ const [prop, value] = (options.value || "").split("=");
1424
+ this.styleProperty = prop;
1425
+ this.styleValue = value;
1426
+ }
1427
+ set() {
1428
+ if (!this.styleProperty) return;
1429
+ this.targets.forEach((target) => target.style.setProperty(this.styleProperty, this.styleValue || ""));
1430
+ }
1431
+ remove() {
1432
+ if (!this.styleProperty) return;
1433
+ this.targets.forEach((target) => target.style.removeProperty(this.styleProperty));
1434
+ }
1435
+ cycle() {
1436
+ if (!this.styleValue) return;
1437
+ this.targets.forEach((target) => {
1438
+ const current = target.style.getPropertyValue(this.styleProperty);
1439
+ const next = this.cycledValue(current, this.styleValue);
1440
+ target.style.setProperty(this.styleProperty, next);
1441
+ });
1442
+ }
1443
+ toggle() {
1444
+ if (!this.styleProperty) return;
1445
+ this.targets.forEach((target) => {
1446
+ if (target.style.getPropertyValue(this.styleProperty) !== "") target.style.removeProperty(this.styleProperty);
1447
+ else target.style.setProperty(this.styleProperty, this.styleValue || "");
1448
+ });
1449
+ }
1450
+ };
1451
+ var actions = {
1452
+ attribute: attributeActions,
1453
+ class: actions$9,
1454
+ clipboard: actions$8,
1455
+ confirm: actions$7,
1456
+ dataAttribute: dataAttributeActions,
1457
+ dialog: actions$6,
1458
+ focus: actions$5,
1459
+ form: actions$4,
1460
+ reload: actions$3,
1461
+ scrollTo: actions$2,
1462
+ style: {
1463
+ setStyle: Style.actionFor("set"),
1464
+ removeStyle: Style.actionFor("remove"),
1465
+ cycleStyle: Style.actionFor("cycle"),
1466
+ toggleStyle: Style.actionFor("toggle")
1467
+ }
1468
+ };
1469
+ var availableActions = (groups = []) => {
1470
+ if (groups.length === 0) return Object.values(actions).reduce((all, group) => ({
1471
+ ...all,
1472
+ ...group
1473
+ }), {});
1474
+ return groups.reduce((selectedActions, group) => {
1475
+ const groupActions = actions[group];
1476
+ if (!groupActions) {
1477
+ console.warn(`Action "${group}" not found`);
1478
+ return selectedActions;
1479
+ }
1480
+ return {
1481
+ ...selectedActions,
1482
+ ...groupActions
1483
+ };
1484
+ }, {});
1485
+ };
1486
+ var actions_default = availableActions([]);
1487
+ var onceTracker = /* @__PURE__ */ new WeakSet();
1488
+ var intersectionObservers = /* @__PURE__ */ new WeakMap();
1489
+ var whenIntersecting = (check) => (element, trigger) => {
1490
+ let observers = intersectionObservers.get(element);
1491
+ if (!observers) {
1492
+ observers = /* @__PURE__ */ new Map();
1493
+ intersectionObservers.set(element, observers);
1494
+ }
1495
+ observers.get(check)?.disconnect();
1496
+ const observer = new IntersectionObserver((entries) => {
1497
+ if (check(entries)) trigger();
1498
+ });
1499
+ observers.set(check, observer);
1500
+ observer.observe(element);
1501
+ };
1502
+ var builtinTriggers = {
1503
+ mounted: (_, trigger) => {
1504
+ queueMicrotask(trigger);
1505
+ },
1506
+ now: (_, trigger) => {
1507
+ trigger();
1508
+ },
1509
+ whenVisible: whenIntersecting((entries) => entries.some((entry) => entry.isIntersecting)),
1510
+ whenInView: whenIntersecting((entries) => entries[0].isIntersecting)
1511
+ };
1512
+ var builtinGates = {
1513
+ whenOutside: (element, { event }) => {
1514
+ if (typeof element.checkVisibility === "function" && !element.checkVisibility()) return false;
1515
+ return !element.contains(event.target);
1516
+ },
1517
+ once: (element) => {
1518
+ if (onceTracker.has(element)) return false;
1519
+ onceTracker.add(element);
1520
+ return true;
1521
+ },
1522
+ preventDefault: (element, { event }) => {
1523
+ event.preventDefault();
1524
+ return true;
1525
+ },
1526
+ stopPropagation: (element, { event }) => {
1527
+ event.stopPropagation();
1528
+ return true;
1529
+ }
1530
+ };
1531
+ var allBuiltinActions = actions_default;
1532
+ Attractive.activate = function(options = {}) {
1533
+ const attractive = new this(options);
1534
+ attractive.activate({
1535
+ ...options,
1536
+ addActions: {
1537
+ ...allBuiltinActions,
1538
+ ...options.addActions
1539
+ },
1540
+ addGates: {
1541
+ ...builtinGates,
1542
+ ...options.addGates
1543
+ },
1544
+ addTriggers: {
1545
+ ...builtinTriggers,
1546
+ ...options.addTriggers
1547
+ }
1548
+ });
1549
+ return attractive;
1550
+ };
1551
+ if (typeof document !== "undefined" && typeof window !== "undefined" && (document.currentScript ?? document.querySelector('script[src*="attractive"][activate]'))?.hasAttribute("activate")) {
1552
+ window.Attractive = Attractive;
1553
+ document.readyState === "loading" ? document.addEventListener("DOMContentLoaded", () => Attractive.activate()) : Attractive.activate();
1554
+ }
1555
+ var src_default = Attractive;
1556
+
1557
+ // attract.js
1558
+ var Debug2 = class {
1559
+ static enabled = false;
1560
+ static prefix = "\u{1F9F2} ";
1561
+ static log(...args) {
1562
+ if (this.enabled) console.log(this.prefix, ...args);
1563
+ }
1564
+ static warn(...args) {
1565
+ if (this.enabled) console.warn(this.prefix, ...args);
1566
+ }
1567
+ static error(...args) {
1568
+ if (this.enabled) console.error(this.prefix, ...args);
1569
+ }
1570
+ };
1571
+ var Template = class {
1572
+ constructor(templateId) {
1573
+ this.source = templateId ? document.getElementById(templateId) : null;
1574
+ if (templateId && !this.source) Debug2.warn(`Attract: template "#${templateId}" not found`);
1575
+ }
1576
+ render({ with: data, target, targets: selector, position }) {
1577
+ const targetElements = this.#targets({
1578
+ target,
1579
+ targets: selector
1580
+ });
1581
+ if (!targetElements.length) return [];
1582
+ if (position === "remove") {
1583
+ targetElements.forEach((element) => element.remove());
1584
+ return [];
1585
+ }
1586
+ if (!this.source) return [];
1587
+ const items = Array.isArray(data) ? data : [data];
1588
+ const results = [];
1589
+ targetElements.forEach((targetElement) => {
1590
+ items.forEach((item) => results.push(this.#renderIn({
1591
+ target: targetElement,
1592
+ item,
1593
+ position
1594
+ })));
1595
+ });
1596
+ return results;
1597
+ }
1598
+ #targets({ target, targets: selector }) {
1599
+ if (selector) return Array.from(document.querySelectorAll(selector));
1600
+ if (target) {
1601
+ const element = document.getElementById(target);
1602
+ return element ? [element] : [];
1603
+ }
1604
+ return [];
1605
+ }
1606
+ #renderIn({ target, item, position }) {
1607
+ const template = this.source.content.cloneNode(true).firstElementChild;
1608
+ this.#snapshot({
1609
+ template,
1610
+ with: item
1611
+ });
1612
+ this.#insert({
1613
+ template,
1614
+ target,
1615
+ at: position
1616
+ });
1617
+ return template;
1618
+ }
1619
+ #snapshot({ template, with: data }) {
1620
+ if (!data) return;
1621
+ for (const [key, value] of Object.entries(data)) {
1622
+ const elements = [];
1623
+ if (template.getAttribute("attract-field") === key) elements.push(template);
1624
+ elements.push(...template.querySelectorAll(`[attract-field="${key}"]`));
1625
+ for (const element of elements) this.#setValue(element, value);
1626
+ }
1627
+ }
1628
+ #setValue(element, value) {
1629
+ const tag = element.tagName;
1630
+ const type = (element.getAttribute("type") || "").toLowerCase();
1631
+ if (type === "checkbox" || type === "radio" || tag === "OPTION") {
1632
+ if (typeof value === "boolean") if (tag === "OPTION") element.selected = value;
1633
+ else element.checked = value;
1634
+ else element.value = value ?? "";
1635
+ return;
1636
+ }
1637
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
1638
+ element.value = value ?? "";
1639
+ return;
1640
+ }
1641
+ element.textContent = value ?? "";
1642
+ }
1643
+ #insert({ template, target, at: position }) {
1644
+ if (position === "append") target.append(template);
1645
+ else if (position === "prepend") target.prepend(template);
1646
+ else if (position === "replace") target.replaceWith(template);
1647
+ else if (position === "before") target.before(template);
1648
+ else if (position === "after") target.after(template);
1649
+ }
1650
+ };
1651
+ function positionAction(position) {
1652
+ return (element, { value, target, targets, dataset }) => {
1653
+ const templateId = value || dataset?.template || dataset?.attractTemplate;
1654
+ if (!templateId) return;
1655
+ new Template(templateId).render({
1656
+ target: target || dataset?.attractTarget,
1657
+ targets,
1658
+ position
1659
+ });
1660
+ };
1661
+ }
1662
+ var append = positionAction("append");
1663
+ var prepend = positionAction("prepend");
1664
+ var replace = positionAction("replace");
1665
+ var before = positionAction("before");
1666
+ var after = positionAction("after");
1667
+ function remove(element, { target, targets }) {
1668
+ if (target || targets) {
1669
+ new Template(null).render({
1670
+ target,
1671
+ targets,
1672
+ position: "remove",
1673
+ with: {}
1674
+ });
1675
+ return;
1676
+ }
1677
+ element?.remove();
1678
+ }
1679
+ var csrf = {
1680
+ header: null,
1681
+ token: null
1682
+ };
1683
+ function respond(json, { registry }) {
1684
+ const actions2 = Array.isArray(json) ? json : json.actions ? json.actions : [json];
1685
+ for (const item of actions2) {
1686
+ const [name, ...rest] = item.action.split("#");
1687
+ const value = rest.join("#");
1688
+ if (item.template) {
1689
+ if (!item.data) Debug2.warn(`Response: "template" without "data"`);
1690
+ else new Template(item.template).render({
1691
+ with: item.data,
1692
+ target: item.target,
1693
+ targets: item.targets,
1694
+ position: name
1695
+ });
1696
+ continue;
1697
+ }
1698
+ const action = registry.getAction(name);
1699
+ if (!action) {
1700
+ Debug2.warn(`Response: unknown action "${name}"`);
1701
+ continue;
1702
+ }
1703
+ action(item.target ? document.getElementById(item.target) : item.targets ? document.querySelector(item.targets) : null, {
1704
+ value: value || item.value || null,
1705
+ target: item.target,
1706
+ targets: item.targets,
1707
+ dataset: {},
1708
+ data: item.data ?? null
1709
+ });
1710
+ }
1711
+ }
1712
+ var Form2 = class {
1713
+ #optimisticElements = [];
1714
+ constructor({ form, registry }) {
1715
+ this.form = form;
1716
+ this.registry = registry;
1717
+ }
1718
+ submit() {
1719
+ const send = (event) => this.#send(event);
1720
+ this.form.addEventListener("submit", send);
1721
+ return () => this.form.removeEventListener("submit", send);
1722
+ }
1723
+ async #send(event) {
1724
+ event.preventDefault();
1725
+ const action = this.form.getAttribute("action");
1726
+ const method = (this.form.querySelector('input[name="_method"]')?.value || this.form.getAttribute("method") || "post").toUpperCase();
1727
+ if (!action) return;
1728
+ const body = this.#data();
1729
+ this.#render(body);
1730
+ this.#busy();
1731
+ try {
1732
+ const request = await this.#fetch({
1733
+ action,
1734
+ method,
1735
+ body
1736
+ });
1737
+ if (!request) {
1738
+ this.#clear({ error: true });
1739
+ this.#removeOptimistic();
1740
+ return;
1741
+ }
1742
+ this.#clear(request.ok ? { success: true } : { error: true });
1743
+ if (request.json.errors) {
1744
+ this.#validity({ errors: request.json.errors });
1745
+ this.#removeOptimistic();
1746
+ return;
1747
+ }
1748
+ this.#actions(request.json);
1749
+ } catch {
1750
+ this.#clear({ error: true });
1751
+ this.#removeOptimistic();
1752
+ }
1753
+ }
1754
+ #data() {
1755
+ const formData = new FormData(this.form);
1756
+ const body = {};
1757
+ for (const [key, value] of formData.entries()) {
1758
+ if (key === "_method") continue;
1759
+ body[key] = value;
1760
+ }
1761
+ return body;
1762
+ }
1763
+ #render(body) {
1764
+ const templateId = this.form.dataset.template || this.form.dataset.attractTemplate || null;
1765
+ const target = this.form.dataset.attractTarget || this.form.getAttribute("@target") || null;
1766
+ const position = this.form.dataset.attractPosition || "append";
1767
+ if (templateId && target && Object.keys(body).length > 0) this.#optimisticElements = new Template(templateId).render({
1768
+ target,
1769
+ position,
1770
+ with: body
1771
+ });
1772
+ }
1773
+ #removeOptimistic() {
1774
+ for (const element of this.#optimisticElements) element.remove();
1775
+ this.#optimisticElements = [];
1776
+ }
1777
+ #busy() {
1778
+ this.form.removeAttribute("data-attract-busy");
1779
+ this.form.removeAttribute("data-attract-success");
1780
+ this.form.removeAttribute("data-attract-error");
1781
+ this.form.setAttribute("data-attract-busy", "");
1782
+ }
1783
+ async #fetch({ action, method, body }) {
1784
+ const headers = {
1785
+ "Content-Type": "application/json",
1786
+ Accept: "application/vnd.attract+json",
1787
+ Attract: "true"
1788
+ };
1789
+ if (csrf.token) headers[csrf.header] = typeof csrf.token === "function" ? csrf.token() : csrf.token;
1790
+ const response = await fetch(action, {
1791
+ method,
1792
+ headers,
1793
+ body: method === "GET" ? void 0 : JSON.stringify(body)
1794
+ });
1795
+ if (!response.headers.get("content-type")?.includes("json")) return null;
1796
+ let json;
1797
+ try {
1798
+ json = await response.json();
1799
+ } catch {
1800
+ return null;
1801
+ }
1802
+ return {
1803
+ ok: response.ok,
1804
+ json
1805
+ };
1806
+ }
1807
+ #clear({ success, error }) {
1808
+ this.form.removeAttribute("data-attract-busy");
1809
+ if (success) this.form.setAttribute("data-attract-success", "true");
1810
+ if (error) this.form.setAttribute("data-attract-error", "true");
1811
+ }
1812
+ #validity({ errors }) {
1813
+ for (const [name, message] of Object.entries(errors)) {
1814
+ const field = this.form.elements[name];
1815
+ if (field) {
1816
+ field.setCustomValidity(message);
1817
+ field.addEventListener("input", () => field.setCustomValidity(""), { once: true });
1818
+ }
1819
+ }
1820
+ this.form.reportValidity();
1821
+ }
1822
+ #actions(json) {
1823
+ respond(json, { registry: this.registry });
1824
+ }
1825
+ };
1826
+ var forms = /* @__PURE__ */ new WeakMap();
1827
+ function attract({ instance, registry }) {
1828
+ registry.addAction("append", append);
1829
+ registry.addAction("prepend", prepend);
1830
+ registry.addAction("replace", replace);
1831
+ registry.addAction("before", before);
1832
+ registry.addAction("after", after);
1833
+ registry.addAction("remove", remove);
1834
+ instance.onElementAdded((element) => {
1835
+ const attract2 = element.getAttribute("@attract");
1836
+ if (element.tagName === "FORM" && attract2 !== null) {
1837
+ if (forms.has(element)) return;
1838
+ const cleanup = new Form2({
1839
+ form: element,
1840
+ registry
1841
+ }).submit();
1842
+ forms.set(element, cleanup);
1843
+ return;
1844
+ }
1845
+ if (attract2 !== null) element.querySelectorAll("form").forEach((form) => {
1846
+ if (forms.has(form)) return;
1847
+ const cleanup = new Form2({
1848
+ form,
1849
+ registry
1850
+ }).submit();
1851
+ forms.set(form, cleanup);
1852
+ });
1853
+ });
1854
+ instance.onElementRemoved((element) => {
1855
+ const cleanup = forms.get(element);
1856
+ if (cleanup) {
1857
+ cleanup();
1858
+ forms.delete(element);
1859
+ }
1860
+ });
1861
+ }
1862
+
1863
+ // request.js
1864
+ var Debug3 = class {
1865
+ static enabled = false;
1866
+ static prefix = "\u{1F9F2} ";
1867
+ static log(...args) {
1868
+ if (this.enabled) console.log(this.prefix, ...args);
1869
+ }
1870
+ static warn(...args) {
1871
+ if (this.enabled) console.warn(this.prefix, ...args);
1872
+ }
1873
+ static error(...args) {
1874
+ if (this.enabled) console.error(this.prefix, ...args);
1875
+ }
1876
+ };
1877
+ var SCOPE_PROPERTY2 = "__attractiveScope";
1878
+ function scopeOf2(element) {
1879
+ let node = element;
1880
+ while (node && node.nodeType === 1) {
1881
+ if (node[SCOPE_PROPERTY2]) return node;
1882
+ node = node.parentElement;
1883
+ }
1884
+ return document;
1885
+ }
1886
+ var ActionBase2 = class {
1887
+ static actionFor(method) {
1888
+ return (element, options = {}) => {
1889
+ return new this(element, options)[method]();
1890
+ };
1891
+ }
1892
+ constructor(element, options = {}) {
1893
+ if (!element) throw new Error("Current element is required");
1894
+ this.element = element;
1895
+ this.target = options.target;
1896
+ this.targetsSelector = options.targets;
1897
+ this.options = options;
1898
+ }
1899
+ get targets() {
1900
+ const scope = scopeOf2(this.element);
1901
+ if (this.targetsSelector) return Array.from(scope.querySelectorAll(this.targetsSelector));
1902
+ if (this.target) {
1903
+ const target = scope.querySelector(`[id="${this.target}"]`);
1904
+ if (!target) Debug3.warn(`Target "#${this.target}" not found`);
1905
+ return target ? [target] : [];
1906
+ }
1907
+ return [this.element];
1908
+ }
1909
+ cycledValue(currentValue, nextValues) {
1910
+ const values = Array.isArray(nextValues) ? nextValues : nextValues.split(",").map((value) => value.trim());
1911
+ return values[(values.indexOf(currentValue) + 1) % values.length];
1912
+ }
1913
+ };
1914
+ var csrf2 = {
1915
+ header: null,
1916
+ token: null
1917
+ };
1918
+ var delay2 = () => {
1919
+ let timeoutId;
1920
+ return (callback, delay3) => {
1921
+ clearTimeout(timeoutId);
1922
+ timeoutId = setTimeout(callback, delay3);
1923
+ };
1924
+ };
1925
+ var clearFeedback2 = delay2();
1926
+ var requests = /* @__PURE__ */ new WeakMap();
1927
+ var activeRequests = {
1928
+ get({ on: element }) {
1929
+ return requests.get(element);
1930
+ },
1931
+ set({ on: element, with: controller }) {
1932
+ requests.set(element, controller);
1933
+ },
1934
+ delete({ on: element }) {
1935
+ requests.delete(element);
1936
+ }
1937
+ };
1938
+ function setFeedback(state, { on: element, for: targets }) {
1939
+ const duration = element.dataset.requestFeedback;
1940
+ targets.forEach((target) => {
1941
+ if (state === "busy") {
1942
+ target.setAttribute("data-request-busy", "true");
1943
+ target.removeAttribute("data-request-success");
1944
+ } else {
1945
+ target.removeAttribute("data-request-busy");
1946
+ target.setAttribute("data-request-success", state === "success");
1947
+ }
1948
+ });
1949
+ if (!duration || state === "busy") return;
1950
+ clearFeedback2(() => {
1951
+ targets.forEach((target) => target.removeAttribute("data-request-success"));
1952
+ }, parseInt(duration));
1953
+ }
1954
+ function crossingOrigin({ for: url }) {
1955
+ try {
1956
+ return new URL(url, window.location.href).origin !== window.location.origin;
1957
+ } catch {
1958
+ Debug3.error("Invalid URL:", url);
1959
+ return false;
1960
+ }
1961
+ }
1962
+ var Get = class {
1963
+ #element;
1964
+ #url;
1965
+ #targets;
1966
+ #onJSON;
1967
+ constructor(element, url, targets, onJSON) {
1968
+ this.#element = element;
1969
+ this.#url = url;
1970
+ this.#targets = targets;
1971
+ this.#onJSON = onJSON;
1972
+ }
1973
+ async execute() {
1974
+ if (!this.#url) {
1975
+ Debug3.warn("No URL provided in the action value");
1976
+ return;
1977
+ }
1978
+ this.#warnCrossOrigin();
1979
+ const controller = this.#start();
1980
+ try {
1981
+ const response = await this.#fetch(controller);
1982
+ await this.#process(response);
1983
+ this.#succeed();
1984
+ return response;
1985
+ } catch (error) {
1986
+ this.#fail(error);
1987
+ }
1988
+ }
1989
+ #warnCrossOrigin() {
1990
+ if (crossingOrigin({ for: this.#url })) Debug3.warn(`Cross-origin request to: ${this.#url}. Missing the correct CORS headers.`);
1991
+ }
1992
+ #start() {
1993
+ const previous = activeRequests.get({ on: this.#element });
1994
+ if (previous) previous.abort();
1995
+ const controller = new AbortController();
1996
+ activeRequests.set({
1997
+ on: this.#element,
1998
+ with: controller
1999
+ });
2000
+ setFeedback("busy", {
2001
+ on: this.#element,
2002
+ for: this.#targets
2003
+ });
2004
+ return controller;
2005
+ }
2006
+ #fetch(controller) {
2007
+ return fetch(this.#url, {
2008
+ method: "GET",
2009
+ signal: controller.signal,
2010
+ headers: {
2011
+ Accept: "application/vnd.attract+json",
2012
+ Attract: "true"
2013
+ }
2014
+ });
2015
+ }
2016
+ async #process(response) {
2017
+ if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
2018
+ if (response.headers.get("content-type")?.includes("json")) {
2019
+ const json = await response.json();
2020
+ if (this.#onJSON) this.#onJSON(json);
2021
+ } else {
2022
+ const html = await response.text();
2023
+ this.#targets.forEach((target) => {
2024
+ target.innerHTML = html;
2025
+ });
2026
+ }
2027
+ }
2028
+ #succeed() {
2029
+ activeRequests.delete({ on: this.#element });
2030
+ setFeedback("success", {
2031
+ on: this.#element,
2032
+ for: this.#targets
2033
+ });
2034
+ }
2035
+ #fail(error) {
2036
+ if (error.name === "AbortError") return;
2037
+ activeRequests.delete({ on: this.#element });
2038
+ setFeedback("error", {
2039
+ on: this.#element,
2040
+ for: this.#targets
2041
+ });
2042
+ throw error;
2043
+ }
2044
+ };
2045
+ var Request = class extends ActionBase2 {
2046
+ constructor(element, options = {}) {
2047
+ super(element, options);
2048
+ this.value = options.value;
2049
+ }
2050
+ async get() {
2051
+ return new Get(this.element, this.value, this.targets, this.options.onJSON).execute();
2052
+ }
2053
+ post() {
2054
+ return this.#fetch("POST");
2055
+ }
2056
+ patch() {
2057
+ return this.#fetch("PATCH");
2058
+ }
2059
+ put() {
2060
+ return this.#fetch("PUT");
2061
+ }
2062
+ #fetch(method) {
2063
+ return this.#executeFetch(method);
2064
+ }
2065
+ #executeFetch(method) {
2066
+ if (!this.value) {
2067
+ Debug3.warn("No URL provided in the action value");
2068
+ return;
2069
+ }
2070
+ if (crossingOrigin({ for: this.value })) Debug3.warn(`Cross-origin request to: ${this.value}. Missing the correct CORS headers.`);
2071
+ const previous = activeRequests.get({ on: this.element });
2072
+ if (previous) previous.abort();
2073
+ const controller = new AbortController();
2074
+ activeRequests.set({
2075
+ on: this.element,
2076
+ with: controller
2077
+ });
2078
+ setFeedback("busy", {
2079
+ on: this.element,
2080
+ for: this.targets
2081
+ });
2082
+ const headers = {
2083
+ "Content-Type": "application/json",
2084
+ Accept: "application/vnd.attract+json",
2085
+ Attract: "true"
2086
+ };
2087
+ if (csrf2.token) headers[csrf2.header] = typeof csrf2.token === "function" ? csrf2.token() : csrf2.token;
2088
+ return fetch(this.value, {
2089
+ method,
2090
+ signal: controller.signal,
2091
+ headers,
2092
+ body: JSON.stringify(this.#body)
2093
+ }).then(async (response) => {
2094
+ if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
2095
+ if (response.headers.get("content-type")?.includes("json") && this.options.onJSON) {
2096
+ const json = await response.json();
2097
+ this.options.onJSON(json);
2098
+ }
2099
+ setFeedback("success", {
2100
+ on: this.element,
2101
+ for: this.targets
2102
+ });
2103
+ activeRequests.delete({ on: this.element });
2104
+ return response;
2105
+ }).catch((error) => {
2106
+ if (error.name === "AbortError") return;
2107
+ activeRequests.delete({ on: this.element });
2108
+ setFeedback("error", {
2109
+ on: this.element,
2110
+ for: this.targets
2111
+ });
2112
+ throw error;
2113
+ });
2114
+ }
2115
+ get #body() {
2116
+ const body = {};
2117
+ const target = this.targets[0];
2118
+ if (target instanceof HTMLFormElement) {
2119
+ const formData = new FormData(target);
2120
+ for (const [key, value] of formData.entries()) body[key] = value;
2121
+ return body;
2122
+ }
2123
+ if (this.#inputField) {
2124
+ const key = this.element.name;
2125
+ body[key] = this.element.value;
2126
+ }
2127
+ return body;
2128
+ }
2129
+ get #inputField() {
2130
+ return this.element instanceof HTMLInputElement || this.element instanceof HTMLSelectElement || this.element instanceof HTMLTextAreaElement && this.element.name;
2131
+ }
2132
+ };
2133
+ function get(element, options) {
2134
+ return new Request(element, {
2135
+ ...options,
2136
+ onJSON: get.onJSON
2137
+ }).get();
2138
+ }
2139
+ get.onJSON = null;
2140
+ function post(element, options) {
2141
+ return new Request(element, {
2142
+ ...options,
2143
+ onJSON: post.onJSON
2144
+ }).post();
2145
+ }
2146
+ post.onJSON = null;
2147
+ function patch(element, options) {
2148
+ return new Request(element, {
2149
+ ...options,
2150
+ onJSON: patch.onJSON
2151
+ }).patch();
2152
+ }
2153
+ patch.onJSON = null;
2154
+ function put(element, options) {
2155
+ return new Request(element, {
2156
+ ...options,
2157
+ onJSON: put.onJSON
2158
+ }).put();
2159
+ }
2160
+ put.onJSON = null;
2161
+
2162
+ // runtime/debug.js
2163
+ var Debug4 = class {
2164
+ static enabled = false;
2165
+ static prefix = "\u{1F9F2} ";
2166
+ static log(...args) {
2167
+ if (this.enabled) console.log(this.prefix, ...args);
2168
+ }
2169
+ static warn(...args) {
2170
+ if (this.enabled) console.warn(this.prefix, ...args);
2171
+ }
2172
+ static error(...args) {
2173
+ if (this.enabled) console.error(this.prefix, ...args);
2174
+ }
2175
+ };
2176
+ var debug_default = Debug4;
2177
+
2178
+ // runtime/addons/template.js
2179
+ var Template2 = class {
2180
+ constructor(templateId) {
2181
+ this.source = templateId ? document.getElementById(templateId) : null;
2182
+ if (templateId && !this.source) {
2183
+ debug_default.warn(`Attract: template "#${templateId}" not found`);
2184
+ }
2185
+ }
2186
+ render({ with: data, target, targets: selector, position }) {
2187
+ const targetElements = this.#targets({ target, targets: selector });
2188
+ if (!targetElements.length) return [];
2189
+ if (position === "remove") {
2190
+ targetElements.forEach((element) => element.remove());
2191
+ return [];
2192
+ }
2193
+ if (!this.source) return [];
2194
+ const items = Array.isArray(data) ? data : [data];
2195
+ const results = [];
2196
+ targetElements.forEach((targetElement) => {
2197
+ items.forEach(
2198
+ (item) => results.push(
2199
+ this.#renderIn({
2200
+ target: targetElement,
2201
+ item,
2202
+ position
2203
+ })
2204
+ )
2205
+ );
2206
+ });
2207
+ return results;
2208
+ }
2209
+ // private
2210
+ #targets({ target, targets: selector }) {
2211
+ if (selector) return Array.from(document.querySelectorAll(selector));
2212
+ if (target) {
2213
+ const element = document.getElementById(target);
2214
+ return element ? [element] : [];
2215
+ }
2216
+ return [];
2217
+ }
2218
+ #renderIn({ target, item, position }) {
2219
+ const template = this.source.content.cloneNode(true).firstElementChild;
2220
+ this.#snapshot({ template, with: item });
2221
+ this.#insert({ template, target, at: position });
2222
+ return template;
2223
+ }
2224
+ #snapshot({ template, with: data }) {
2225
+ if (!data) return;
2226
+ for (const [key, value] of Object.entries(data)) {
2227
+ const elements = [];
2228
+ if (template.getAttribute("attract-field") === key) {
2229
+ elements.push(template);
2230
+ }
2231
+ elements.push(...template.querySelectorAll(`[attract-field="${key}"]`));
2232
+ for (const element of elements) {
2233
+ this.#setValue(element, value);
2234
+ }
2235
+ }
2236
+ }
2237
+ #setValue(element, value) {
2238
+ const tag = element.tagName;
2239
+ const type = (element.getAttribute("type") || "").toLowerCase();
2240
+ if (type === "checkbox" || type === "radio" || tag === "OPTION") {
2241
+ if (typeof value === "boolean") {
2242
+ if (tag === "OPTION") {
2243
+ element.selected = value;
2244
+ } else {
2245
+ element.checked = value;
2246
+ }
2247
+ } else {
2248
+ element.value = value ?? "";
2249
+ }
2250
+ return;
2251
+ }
2252
+ if (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT") {
2253
+ element.value = value ?? "";
2254
+ return;
2255
+ }
2256
+ element.textContent = value ?? "";
2257
+ }
2258
+ #insert({ template, target, at: position }) {
2259
+ if (position === "append") target.append(template);
2260
+ else if (position === "prepend") target.prepend(template);
2261
+ else if (position === "replace") target.replaceWith(template);
2262
+ else if (position === "before") target.before(template);
2263
+ else if (position === "after") target.after(template);
2264
+ }
2265
+ };
2266
+
2267
+ // runtime/addons/response.js
2268
+ function respond2(json, { registry }) {
2269
+ const actions2 = Array.isArray(json) ? json : json.actions ? json.actions : [json];
2270
+ for (const item of actions2) {
2271
+ const [name, ...rest] = item.action.split("#");
2272
+ const value = rest.join("#");
2273
+ if (item.template) {
2274
+ if (!item.data) {
2275
+ debug_default.warn(`Response: "template" without "data"`);
2276
+ } else {
2277
+ new Template2(item.template).render({
2278
+ with: item.data,
2279
+ target: item.target,
2280
+ targets: item.targets,
2281
+ position: name
2282
+ });
2283
+ }
2284
+ continue;
2285
+ }
2286
+ const action = registry.getAction(name);
2287
+ if (!action) {
2288
+ debug_default.warn(`Response: unknown action "${name}"`);
2289
+ continue;
2290
+ }
2291
+ const element = item.target ? document.getElementById(item.target) : item.targets ? document.querySelector(item.targets) : null;
2292
+ action(element, {
2293
+ value: value || item.value || null,
2294
+ target: item.target,
2295
+ targets: item.targets,
2296
+ dataset: {},
2297
+ data: item.data ?? null
2298
+ });
2299
+ }
2300
+ }
2301
+
2302
+ // entry.js
2303
+ var SetAttributes = class extends Action {
2304
+ run() {
2305
+ const { data, target, targets } = this.options;
2306
+ if (!data) return;
2307
+ for (const root of this.#roots({ target, targets })) {
2308
+ this.#setLink({ on: root, with: data });
2309
+ this.#setIcon({ on: root, with: data });
2310
+ this.#setVariant({ on: root, with: data });
2311
+ this.#setConfirm({ on: root, with: data });
2312
+ }
2313
+ }
2314
+ // private
2315
+ #roots({ target, targets }) {
2316
+ if (targets) return Array.from(document.querySelectorAll(targets));
2317
+ if (target) {
2318
+ const element = document.getElementById(target);
2319
+ return element ? [element] : [];
2320
+ }
2321
+ return [];
2322
+ }
2323
+ #setLink({ on, with: data }) {
2324
+ if (!data.href) return;
2325
+ const link = on.matches("[attract-href]") ? on : on.querySelector("[attract-href]");
2326
+ if (link) link.setAttribute("href", data.href);
2327
+ }
2328
+ #setIcon({ on, with: data }) {
2329
+ if (!data.icon) return;
2330
+ const icon = on.querySelector("[attract-icon]");
2331
+ if (icon) icon.innerHTML = data.icon;
2332
+ }
2333
+ #setVariant({ on, with: data }) {
2334
+ if (!data.variant) return;
2335
+ const action = on.matches("[attract-variant]") ? on : on.querySelector("[attract-variant]");
2336
+ if (action) action.classList.add(`action--${data.variant}`);
2337
+ }
2338
+ #setConfirm({ on, with: data }) {
2339
+ if (!data.confirm) return;
2340
+ const form = on.matches("form[attract-confirm]") ? on : on.querySelector("form[attract-confirm]");
2341
+ if (!form || form.dataset.confirmBound) return;
2342
+ form.dataset.confirmBound = "true";
2343
+ form.dataset.confirm = data.confirm;
2344
+ form.addEventListener("submit", (event) => {
2345
+ if (window.confirm(data.confirm)) return;
2346
+ event.preventDefault();
2347
+ event.stopImmediatePropagation();
2348
+ }, true);
2349
+ }
2350
+ };
2351
+
2352
+ // index.js
2353
+ var extension = ({ registry }) => {
2354
+ get.onJSON = (json) => respond2(json, { registry });
2355
+ };
2356
+ var setAttributes = (element, options) => new SetAttributes(element, options).run();
2357
+ src_default.activate({
2358
+ extendWith: [attract, extension],
2359
+ addActions: { get, setAttributes }
2360
+ });
2361
+ })();