@bquery/bquery 1.3.0 → 1.4.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 (71) hide show
  1. package/README.md +527 -501
  2. package/dist/{batch-4LAvfLE7.js → batch-x7b2eZST.js} +2 -2
  3. package/dist/{batch-4LAvfLE7.js.map → batch-x7b2eZST.js.map} +1 -1
  4. package/dist/component.es.mjs +1 -1
  5. package/dist/core/collection.d.ts +19 -3
  6. package/dist/core/collection.d.ts.map +1 -1
  7. package/dist/core/element.d.ts +23 -4
  8. package/dist/core/element.d.ts.map +1 -1
  9. package/dist/core/index.d.ts +1 -0
  10. package/dist/core/index.d.ts.map +1 -1
  11. package/dist/core/utils/function.d.ts +21 -4
  12. package/dist/core/utils/function.d.ts.map +1 -1
  13. package/dist/{core-COenAZjD.js → core-BhpuvPhy.js} +62 -37
  14. package/dist/core-BhpuvPhy.js.map +1 -0
  15. package/dist/core.es.mjs +174 -131
  16. package/dist/core.es.mjs.map +1 -1
  17. package/dist/full.es.mjs +7 -7
  18. package/dist/full.iife.js +2 -2
  19. package/dist/full.iife.js.map +1 -1
  20. package/dist/full.umd.js +2 -2
  21. package/dist/full.umd.js.map +1 -1
  22. package/dist/index.es.mjs +7 -7
  23. package/dist/motion.es.mjs.map +1 -1
  24. package/dist/{persisted-Dz_ryNuC.js → persisted-DHoi3uEs.js} +4 -4
  25. package/dist/{persisted-Dz_ryNuC.js.map → persisted-DHoi3uEs.js.map} +1 -1
  26. package/dist/platform/storage.d.ts.map +1 -1
  27. package/dist/platform.es.mjs +12 -7
  28. package/dist/platform.es.mjs.map +1 -1
  29. package/dist/reactive/core.d.ts +12 -0
  30. package/dist/reactive/core.d.ts.map +1 -1
  31. package/dist/reactive/effect.d.ts.map +1 -1
  32. package/dist/reactive/internals.d.ts +6 -0
  33. package/dist/reactive/internals.d.ts.map +1 -1
  34. package/dist/reactive.es.mjs +6 -6
  35. package/dist/router.es.mjs +1 -1
  36. package/dist/{sanitize-1FBEPAFH.js → sanitize-Cxvxa-DX.js} +50 -39
  37. package/dist/sanitize-Cxvxa-DX.js.map +1 -0
  38. package/dist/security/sanitize-core.d.ts.map +1 -1
  39. package/dist/security.es.mjs +2 -2
  40. package/dist/store.es.mjs +2 -2
  41. package/dist/type-guards-BdKlYYlS.js +32 -0
  42. package/dist/type-guards-BdKlYYlS.js.map +1 -0
  43. package/dist/untrack-DNnnqdlR.js +6 -0
  44. package/dist/{untrack-BuEQKH7_.js.map → untrack-DNnnqdlR.js.map} +1 -1
  45. package/dist/view/evaluate.d.ts.map +1 -1
  46. package/dist/view.es.mjs +157 -151
  47. package/dist/view.es.mjs.map +1 -1
  48. package/dist/{watch-CXyaBC_9.js → watch-DXXv3iAI.js} +3 -3
  49. package/dist/{watch-CXyaBC_9.js.map → watch-DXXv3iAI.js.map} +1 -1
  50. package/package.json +132 -132
  51. package/src/core/collection.ts +628 -588
  52. package/src/core/element.ts +774 -746
  53. package/src/core/index.ts +48 -47
  54. package/src/core/utils/function.ts +151 -110
  55. package/src/motion/animate.ts +113 -113
  56. package/src/motion/flip.ts +176 -176
  57. package/src/motion/scroll.ts +57 -57
  58. package/src/motion/spring.ts +150 -150
  59. package/src/motion/timeline.ts +246 -246
  60. package/src/motion/transition.ts +51 -51
  61. package/src/platform/storage.ts +215 -208
  62. package/src/reactive/core.ts +114 -93
  63. package/src/reactive/effect.ts +54 -43
  64. package/src/reactive/internals.ts +122 -105
  65. package/src/security/sanitize-core.ts +364 -343
  66. package/src/view/evaluate.ts +290 -274
  67. package/dist/core-COenAZjD.js.map +0 -1
  68. package/dist/sanitize-1FBEPAFH.js.map +0 -1
  69. package/dist/type-guards-DRma3-Kc.js +0 -16
  70. package/dist/type-guards-DRma3-Kc.js.map +0 -1
  71. package/dist/untrack-BuEQKH7_.js +0 -6
@@ -1,746 +1,774 @@
1
- import { createElementFromHtml, insertContent, setHtml } from './dom';
2
-
3
- /**
4
- * Wrapper for a single DOM element.
5
- * Provides a chainable, jQuery-like API for DOM manipulation.
6
- *
7
- * This class encapsulates a DOM element and provides methods for:
8
- * - Class manipulation (addClass, removeClass, toggleClass)
9
- * - Attribute and property access (attr, prop, data)
10
- * - Content manipulation (text, html, append, prepend)
11
- * - Style manipulation (css)
12
- * - Event handling (on, off, once, trigger)
13
- * - DOM traversal (find, closest, parent, children, siblings)
14
- *
15
- * All mutating methods return `this` for method chaining.
16
- *
17
- * @example
18
- * ```ts
19
- * $('#button')
20
- * .addClass('active')
21
- * .css({ color: 'blue' })
22
- * .on('click', () => console.log('clicked'));
23
- * ```
24
- */
25
- /** Handler signature for delegated events */
26
- type DelegatedHandler = (event: Event, target: Element) => void;
27
-
28
- export class BQueryElement {
29
- /**
30
- * Stores delegated event handlers for cleanup via undelegate().
31
- * Key format: `${event}:${selector}`
32
- * @internal
33
- */
34
- private readonly delegatedHandlers = new Map<string, Map<DelegatedHandler, EventListener>>();
35
-
36
- /**
37
- * Creates a new BQueryElement wrapper.
38
- * @param element - The DOM element to wrap
39
- */
40
- constructor(private readonly element: Element) {}
41
-
42
- /**
43
- * Exposes the raw DOM element when direct access is needed.
44
- * Use sparingly; prefer the wrapper methods for consistency.
45
- */
46
- get raw(): Element {
47
- return this.element;
48
- }
49
-
50
- /**
51
- * Exposes the underlying DOM element.
52
- * Provided for spec compatibility and read-only access.
53
- */
54
- get node(): Element {
55
- return this.element;
56
- }
57
-
58
- /** Add one or more classes. */
59
- addClass(...classNames: string[]): this {
60
- this.element.classList.add(...classNames);
61
- return this;
62
- }
63
-
64
- /** Remove one or more classes. */
65
- removeClass(...classNames: string[]): this {
66
- this.element.classList.remove(...classNames);
67
- return this;
68
- }
69
-
70
- /** Toggle a class by name. */
71
- toggleClass(className: string, force?: boolean): this {
72
- this.element.classList.toggle(className, force);
73
- return this;
74
- }
75
-
76
- /** Get or set an attribute. */
77
- attr(name: string, value?: string): string | this {
78
- if (value === undefined) {
79
- return this.element.getAttribute(name) ?? '';
80
- }
81
- this.element.setAttribute(name, value);
82
- return this;
83
- }
84
-
85
- /** Remove an attribute. */
86
- removeAttr(name: string): this {
87
- this.element.removeAttribute(name);
88
- return this;
89
- }
90
-
91
- /** Toggle an attribute on/off. */
92
- toggleAttr(name: string, force?: boolean): this {
93
- const hasAttr = this.element.hasAttribute(name);
94
- const shouldAdd = force ?? !hasAttr;
95
- if (shouldAdd) {
96
- this.element.setAttribute(name, '');
97
- } else {
98
- this.element.removeAttribute(name);
99
- }
100
- return this;
101
- }
102
-
103
- /** Get or set a property. */
104
- prop<T extends keyof Element>(name: T, value?: Element[T]): Element[T] | this {
105
- if (value === undefined) {
106
- return this.element[name];
107
- }
108
- this.element[name] = value;
109
- return this;
110
- }
111
-
112
- /** Read or write data attributes in camelCase. */
113
- data(name: string, value?: string): string | this {
114
- const key = name.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
115
- if (value === undefined) {
116
- return this.element.getAttribute(`data-${key}`) ?? '';
117
- }
118
- this.element.setAttribute(`data-${key}`, value);
119
- return this;
120
- }
121
-
122
- /** Get or set text content. */
123
- text(value?: string): string | this {
124
- if (value === undefined) {
125
- return this.element.textContent ?? '';
126
- }
127
- this.element.textContent = value;
128
- return this;
129
- }
130
-
131
- /** Set HTML content using a sanitized string. */
132
- /**
133
- * Sets sanitized HTML content on the element.
134
- * Uses the security module to sanitize input and prevent XSS attacks.
135
- *
136
- * @param value - The HTML string to set (will be sanitized)
137
- * @returns The instance for method chaining
138
- *
139
- * @example
140
- * ```ts
141
- * $('#content').html('<strong>Hello</strong>');
142
- * ```
143
- */
144
- html(value: string): this {
145
- setHtml(this.element, value);
146
- return this;
147
- }
148
-
149
- /**
150
- * Sets HTML content without sanitization.
151
- * Use only when you trust the HTML source completely.
152
- *
153
- * @param value - The raw HTML string to set
154
- * @returns The instance for method chaining
155
- *
156
- * @warning This method bypasses XSS protection. Use with caution.
157
- */
158
- htmlUnsafe(value: string): this {
159
- this.element.innerHTML = value;
160
- return this;
161
- }
162
-
163
- /**
164
- * Gets or sets CSS styles on the element.
165
- *
166
- * @param property - A CSS property name or an object of property-value pairs
167
- * @param value - The value when setting a single property
168
- * @returns The instance for method chaining
169
- *
170
- * @example
171
- * ```ts
172
- * // Single property
173
- * $('#box').css('color', 'red');
174
- *
175
- * // Multiple properties
176
- * $('#box').css({ color: 'red', 'font-size': '16px' });
177
- * ```
178
- */
179
- css(property: string | Record<string, string>, value?: string): this {
180
- if (typeof property === 'string') {
181
- if (value !== undefined) {
182
- (this.element as HTMLElement).style.setProperty(property, value);
183
- }
184
- return this;
185
- }
186
-
187
- for (const [key, val] of Object.entries(property)) {
188
- (this.element as HTMLElement).style.setProperty(key, val);
189
- }
190
- return this;
191
- }
192
-
193
- /**
194
- * Appends HTML or elements to the end of the element.
195
- *
196
- * @param content - HTML string or element(s) to append
197
- * @returns The instance for method chaining
198
- */
199
- append(content: string | Element | Element[]): this {
200
- this.insertContent(content, 'beforeend');
201
- return this;
202
- }
203
-
204
- /**
205
- * Prepends HTML or elements to the beginning of the element.
206
- *
207
- * @param content - HTML string or element(s) to prepend
208
- * @returns The instance for method chaining
209
- */
210
- prepend(content: string | Element | Element[]): this {
211
- this.insertContent(content, 'afterbegin');
212
- return this;
213
- }
214
-
215
- /**
216
- * Inserts content before this element.
217
- *
218
- * @param content - HTML string or element(s) to insert
219
- * @returns The instance for method chaining
220
- */
221
- before(content: string | Element | Element[]): this {
222
- this.insertContent(content, 'beforebegin');
223
- return this;
224
- }
225
-
226
- /**
227
- * Inserts content after this element.
228
- *
229
- * @param content - HTML string or element(s) to insert
230
- * @returns The instance for method chaining
231
- */
232
- after(content: string | Element | Element[]): this {
233
- this.insertContent(content, 'afterend');
234
- return this;
235
- }
236
-
237
- /**
238
- * Wraps the element with the specified wrapper element or tag.
239
- *
240
- * @param wrapper - Tag name string or Element to wrap with
241
- * @returns The instance for method chaining
242
- *
243
- * @example
244
- * ```ts
245
- * $('#content').wrap('div'); // Wraps with <div>
246
- * $('#content').wrap(document.createElement('section'));
247
- * ```
248
- */
249
- wrap(wrapper: string | Element): this {
250
- const wrapperEl = typeof wrapper === 'string' ? document.createElement(wrapper) : wrapper;
251
- this.element.parentNode?.insertBefore(wrapperEl, this.element);
252
- wrapperEl.appendChild(this.element);
253
- return this;
254
- }
255
-
256
- /**
257
- * Removes the parent element, keeping this element in its place.
258
- * Essentially the opposite of wrap().
259
- *
260
- * **Important**: This method only moves the current element out of its parent
261
- * before removing the parent. Any sibling elements will be removed along with
262
- * the parent. For unwrapping multiple siblings, use a collection: `$$(siblings).unwrap()`.
263
- *
264
- * @returns The instance for method chaining
265
- *
266
- * @example
267
- * ```ts
268
- * // Before: <div><span id="text">Hello</span></div>
269
- * $('#text').unwrap();
270
- * // After: <span id="text">Hello</span>
271
- * ```
272
- */
273
- unwrap(): this {
274
- const parent = this.element.parentElement;
275
- if (parent && parent.parentNode) {
276
- parent.parentNode.insertBefore(this.element, parent);
277
- parent.remove();
278
- }
279
- return this;
280
- }
281
-
282
- /**
283
- * Replaces this element with new content.
284
- *
285
- * @param content - HTML string (sanitized) or Element to replace with
286
- * @returns A new BQueryElement wrapping the replacement element
287
- *
288
- * @example
289
- * ```ts
290
- * const newEl = $('#old').replaceWith('<div id="new">Replaced</div>');
291
- * ```
292
- */
293
- replaceWith(content: string | Element): BQueryElement {
294
- const newEl = typeof content === 'string' ? createElementFromHtml(content) : content;
295
- this.element.replaceWith(newEl);
296
- return new BQueryElement(newEl);
297
- }
298
-
299
- /**
300
- * Scrolls the element into view with configurable behavior.
301
- *
302
- * @param options - ScrollIntoView options or boolean for legacy behavior
303
- * @returns The instance for method chaining
304
- *
305
- * @example
306
- * ```ts
307
- * $('#section').scrollTo(); // Smooth scroll
308
- * $('#section').scrollTo({ behavior: 'instant', block: 'start' });
309
- * ```
310
- */
311
- scrollTo(options: ScrollIntoViewOptions | boolean = { behavior: 'smooth' }): this {
312
- this.element.scrollIntoView(options);
313
- return this;
314
- }
315
-
316
- /**
317
- * Removes the element from the DOM.
318
- *
319
- * @returns The instance for method chaining (though element is now detached)
320
- */
321
- remove(): this {
322
- this.element.remove();
323
- return this;
324
- }
325
-
326
- /**
327
- * Clears all child nodes from the element.
328
- *
329
- * @returns The instance for method chaining
330
- */
331
- empty(): this {
332
- this.element.innerHTML = '';
333
- return this;
334
- }
335
-
336
- /**
337
- * Clones the element, optionally with all descendants.
338
- *
339
- * @param deep - If true, clone all descendants (default: true)
340
- * @returns A new BQueryElement wrapping the cloned element
341
- */
342
- clone(deep: boolean = true): BQueryElement {
343
- return new BQueryElement(this.element.cloneNode(deep) as Element);
344
- }
345
-
346
- /**
347
- * Finds all descendant elements matching the selector.
348
- *
349
- * @param selector - CSS selector to match
350
- * @returns Array of matching elements
351
- */
352
- find(selector: string): Element[] {
353
- return Array.from(this.element.querySelectorAll(selector));
354
- }
355
-
356
- /**
357
- * Finds the first descendant element matching the selector.
358
- *
359
- * @param selector - CSS selector to match
360
- * @returns The first matching element or null
361
- */
362
- findOne(selector: string): Element | null {
363
- return this.element.querySelector(selector);
364
- }
365
-
366
- /**
367
- * Finds the closest ancestor matching the selector.
368
- *
369
- * @param selector - CSS selector to match
370
- * @returns The matching ancestor or null
371
- */
372
- closest(selector: string): Element | null {
373
- return this.element.closest(selector);
374
- }
375
-
376
- /**
377
- * Gets the parent element.
378
- *
379
- * @returns The parent element or null
380
- */
381
- parent(): Element | null {
382
- return this.element.parentElement;
383
- }
384
-
385
- /**
386
- * Gets all child elements.
387
- *
388
- * @returns Array of child elements
389
- */
390
- children(): Element[] {
391
- return Array.from(this.element.children);
392
- }
393
-
394
- /**
395
- * Gets all sibling elements.
396
- *
397
- * @returns Array of sibling elements (excluding this element)
398
- */
399
- siblings(): Element[] {
400
- const parent = this.element.parentElement;
401
- if (!parent) return [];
402
- return Array.from(parent.children).filter((child) => child !== this.element);
403
- }
404
-
405
- /**
406
- * Gets the next sibling element.
407
- *
408
- * @returns The next sibling element or null
409
- */
410
- next(): Element | null {
411
- return this.element.nextElementSibling;
412
- }
413
-
414
- /**
415
- * Gets the previous sibling element.
416
- *
417
- * @returns The previous sibling element or null
418
- */
419
- prev(): Element | null {
420
- return this.element.previousElementSibling;
421
- }
422
-
423
- /**
424
- * Adds an event listener.
425
- *
426
- * @param event - Event type to listen for
427
- * @param handler - Event handler function
428
- * @returns The instance for method chaining
429
- */
430
- on(event: string, handler: EventListenerOrEventListenerObject): this {
431
- this.element.addEventListener(event, handler);
432
- return this;
433
- }
434
-
435
- /**
436
- * Adds a one-time event listener that removes itself after firing.
437
- *
438
- * @param event - Event type to listen for
439
- * @param handler - Event handler function
440
- * @returns The instance for method chaining
441
- */
442
- once(event: string, handler: EventListener): this {
443
- this.element.addEventListener(event, handler, { once: true });
444
- return this;
445
- }
446
-
447
- /**
448
- * Removes an event listener.
449
- *
450
- * @param event - Event type
451
- * @param handler - The handler to remove
452
- * @returns The instance for method chaining
453
- */
454
- off(event: string, handler: EventListenerOrEventListenerObject): this {
455
- this.element.removeEventListener(event, handler);
456
- return this;
457
- }
458
-
459
- /**
460
- * Triggers a custom event on the element.
461
- *
462
- * @param event - Event type to trigger
463
- * @param detail - Optional detail data to include with the event
464
- * @returns The instance for method chaining
465
- */
466
- trigger(event: string, detail?: unknown): this {
467
- this.element.dispatchEvent(new CustomEvent(event, { detail, bubbles: true, cancelable: true }));
468
- return this;
469
- }
470
-
471
- /**
472
- * Adds a delegated event listener that only triggers for matching descendants.
473
- * More efficient than adding listeners to many elements individually.
474
- *
475
- * Use `undelegate()` to remove the listener later.
476
- *
477
- * @param event - Event type to listen for
478
- * @param selector - CSS selector to match against event targets
479
- * @param handler - Event handler function, receives the matched element as context
480
- * @returns The instance for method chaining
481
- *
482
- * @example
483
- * ```ts
484
- * // Instead of adding listeners to each button:
485
- * const handler = (e, target) => console.log('Clicked:', target.textContent);
486
- * $('#list').delegate('click', '.item', handler);
487
- *
488
- * // Later, remove the delegated listener:
489
- * $('#list').undelegate('click', '.item', handler);
490
- * ```
491
- */
492
- delegate(
493
- event: string,
494
- selector: string,
495
- handler: (event: Event, target: Element) => void
496
- ): this {
497
- const key = `${event}:${selector}`;
498
- const wrapper: EventListener = (e: Event) => {
499
- const target = (e.target as Element).closest(selector);
500
- if (target && this.element.contains(target)) {
501
- handler(e, target);
502
- }
503
- };
504
-
505
- // Store the wrapper so it can be removed later
506
- if (!this.delegatedHandlers.has(key)) {
507
- this.delegatedHandlers.set(key, new Map());
508
- }
509
- this.delegatedHandlers.get(key)!.set(handler, wrapper);
510
-
511
- this.element.addEventListener(event, wrapper);
512
- return this;
513
- }
514
-
515
- /**
516
- * Removes a delegated event listener previously added with `delegate()`.
517
- *
518
- * @param event - Event type that was registered
519
- * @param selector - CSS selector that was used
520
- * @param handler - The original handler function passed to delegate()
521
- * @returns The instance for method chaining
522
- *
523
- * @example
524
- * ```ts
525
- * const handler = (e, target) => console.log('Clicked:', target.textContent);
526
- * $('#list').delegate('click', '.item', handler);
527
- *
528
- * // Remove the delegated listener:
529
- * $('#list').undelegate('click', '.item', handler);
530
- * ```
531
- */
532
- undelegate(
533
- event: string,
534
- selector: string,
535
- handler: (event: Event, target: Element) => void
536
- ): this {
537
- const key = `${event}:${selector}`;
538
- const handlers = this.delegatedHandlers.get(key);
539
-
540
- if (handlers) {
541
- const wrapper = handlers.get(handler);
542
- if (wrapper) {
543
- this.element.removeEventListener(event, wrapper);
544
- handlers.delete(handler);
545
-
546
- // Clean up empty maps
547
- if (handlers.size === 0) {
548
- this.delegatedHandlers.delete(key);
549
- }
550
- }
551
- }
552
-
553
- return this;
554
- }
555
-
556
- /**
557
- * Checks if the element matches a CSS selector.
558
- *
559
- * @param selector - CSS selector to match against
560
- * @returns True if the element matches the selector
561
- */
562
- matches(selector: string): boolean {
563
- return this.element.matches(selector);
564
- }
565
-
566
- /**
567
- * Checks if the element has a specific class.
568
- *
569
- * @param className - Class name to check
570
- * @returns True if the element has the class
571
- */
572
- hasClass(className: string): boolean {
573
- return this.element.classList.contains(className);
574
- }
575
-
576
- /**
577
- * Shows the element by removing the hidden attribute and setting display.
578
- *
579
- * @param display - Optional display value (default: '')
580
- * @returns The instance for method chaining
581
- */
582
- show(display: string = ''): this {
583
- this.element.removeAttribute('hidden');
584
- (this.element as HTMLElement).style.display = display;
585
- return this;
586
- }
587
-
588
- /**
589
- * Hides the element by setting display to 'none'.
590
- *
591
- * @returns The instance for method chaining
592
- */
593
- hide(): this {
594
- (this.element as HTMLElement).style.display = 'none';
595
- return this;
596
- }
597
-
598
- /**
599
- * Toggles the visibility of the element.
600
- *
601
- * @param force - Optional force show (true) or hide (false)
602
- * @returns The instance for method chaining
603
- */
604
- toggle(force?: boolean): this {
605
- const isHidden = (this.element as HTMLElement).style.display === 'none';
606
- const shouldShow = force ?? isHidden;
607
- return shouldShow ? this.show() : this.hide();
608
- }
609
-
610
- /**
611
- * Focuses the element.
612
- *
613
- * @returns The instance for method chaining
614
- */
615
- focus(): this {
616
- (this.element as HTMLElement).focus();
617
- return this;
618
- }
619
-
620
- /**
621
- * Blurs (unfocuses) the element.
622
- *
623
- * @returns The instance for method chaining
624
- */
625
- blur(): this {
626
- (this.element as HTMLElement).blur();
627
- return this;
628
- }
629
-
630
- /**
631
- * Gets or sets the value of form elements.
632
- *
633
- * @param newValue - Optional value to set
634
- * @returns The current value when getting, or the instance when setting
635
- */
636
- val(newValue?: string): string | this {
637
- const input = this.element as HTMLInputElement;
638
- if (newValue === undefined) {
639
- return input.value ?? '';
640
- }
641
- input.value = newValue;
642
- return this;
643
- }
644
-
645
- /**
646
- * Serializes form data to a plain object.
647
- * Only works on form elements; returns empty object for non-forms.
648
- *
649
- * @returns Object with form field names as keys and values
650
- *
651
- * @example
652
- * ```ts
653
- * // For a form with <input name="email" value="test@example.com">
654
- * const data = $('#myForm').serialize();
655
- * // { email: 'test@example.com' }
656
- * ```
657
- */
658
- serialize(): Record<string, string | string[]> {
659
- const form = this.element as HTMLFormElement;
660
- if (form.tagName.toLowerCase() !== 'form') {
661
- return {};
662
- }
663
-
664
- const result: Record<string, string | string[]> = {};
665
- const formData = new FormData(form);
666
-
667
- for (const [key, value] of formData.entries()) {
668
- if (typeof value !== 'string') continue; // Skip File objects
669
-
670
- if (key in result) {
671
- // Handle multiple values (e.g., checkboxes)
672
- const existing = result[key];
673
- if (Array.isArray(existing)) {
674
- existing.push(value);
675
- } else {
676
- result[key] = [existing, value];
677
- }
678
- } else {
679
- result[key] = value;
680
- }
681
- }
682
-
683
- return result;
684
- }
685
-
686
- /**
687
- * Serializes form data to a URL-encoded query string.
688
- *
689
- * @returns URL-encoded string suitable for form submission
690
- *
691
- * @example
692
- * ```ts
693
- * const queryString = $('#myForm').serializeString();
694
- * // 'email=test%40example.com&name=John'
695
- * ```
696
- */
697
- serializeString(): string {
698
- const form = this.element as HTMLFormElement;
699
- if (form.tagName.toLowerCase() !== 'form') {
700
- return '';
701
- }
702
-
703
- const formData = new FormData(form);
704
- const params = new URLSearchParams();
705
-
706
- for (const [key, value] of formData.entries()) {
707
- if (typeof value === 'string') {
708
- params.append(key, value);
709
- }
710
- }
711
-
712
- return params.toString();
713
- }
714
-
715
- /**
716
- * Gets the bounding client rectangle of the element.
717
- *
718
- * @returns The element's bounding rectangle
719
- */
720
- rect(): DOMRect {
721
- return this.element.getBoundingClientRect();
722
- }
723
-
724
- /**
725
- * Gets the offset dimensions (width, height, top, left).
726
- *
727
- * @returns Object with offset dimensions
728
- */
729
- offset(): { width: number; height: number; top: number; left: number } {
730
- const el = this.element as HTMLElement;
731
- return {
732
- width: el.offsetWidth,
733
- height: el.offsetHeight,
734
- top: el.offsetTop,
735
- left: el.offsetLeft,
736
- };
737
- }
738
-
739
- /**
740
- * Internal method to insert content at a specified position.
741
- * @internal
742
- */
743
- private insertContent(content: string | Element | Element[], position: InsertPosition) {
744
- insertContent(this.element, content, position);
745
- }
746
- }
1
+ import { createElementFromHtml, insertContent, setHtml } from './dom';
2
+
3
+ /**
4
+ * Wrapper for a single DOM element.
5
+ * Provides a chainable, jQuery-like API for DOM manipulation.
6
+ *
7
+ * This class encapsulates a DOM element and provides methods for:
8
+ * - Class manipulation (addClass, removeClass, toggleClass)
9
+ * - Attribute and property access (attr, prop, data)
10
+ * - Content manipulation (text, html, append, prepend)
11
+ * - Style manipulation (css)
12
+ * - Event handling (on, off, once, trigger)
13
+ * - DOM traversal (find, closest, parent, children, siblings)
14
+ *
15
+ * All mutating methods return `this` for method chaining.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * $('#button')
20
+ * .addClass('active')
21
+ * .css({ color: 'blue' })
22
+ * .on('click', () => console.log('clicked'));
23
+ * ```
24
+ */
25
+ /** Handler signature for delegated events */
26
+ type DelegatedHandler = (event: Event, target: Element) => void;
27
+
28
+ export class BQueryElement {
29
+ /**
30
+ * Stores delegated event handlers for cleanup via undelegate().
31
+ * Key format: `${event}:${selector}`
32
+ * @internal
33
+ */
34
+ private readonly delegatedHandlers = new Map<string, Map<DelegatedHandler, EventListener>>();
35
+
36
+ /**
37
+ * Creates a new BQueryElement wrapper.
38
+ * @param element - The DOM element to wrap
39
+ */
40
+ constructor(private readonly element: Element) {}
41
+
42
+ /**
43
+ * Exposes the raw DOM element when direct access is needed.
44
+ * Use sparingly; prefer the wrapper methods for consistency.
45
+ */
46
+ get raw(): Element {
47
+ return this.element;
48
+ }
49
+
50
+ /**
51
+ * Exposes the underlying DOM element.
52
+ * Provided for spec compatibility and read-only access.
53
+ */
54
+ get node(): Element {
55
+ return this.element;
56
+ }
57
+
58
+ /** Add one or more classes. */
59
+ addClass(...classNames: string[]): this {
60
+ this.element.classList.add(...classNames);
61
+ return this;
62
+ }
63
+
64
+ /** Remove one or more classes. */
65
+ removeClass(...classNames: string[]): this {
66
+ this.element.classList.remove(...classNames);
67
+ return this;
68
+ }
69
+
70
+ /** Toggle a class by name. */
71
+ toggleClass(className: string, force?: boolean): this {
72
+ this.element.classList.toggle(className, force);
73
+ return this;
74
+ }
75
+
76
+ /** Get or set an attribute. */
77
+ attr(name: string, value?: string): string | this {
78
+ if (value === undefined) {
79
+ return this.element.getAttribute(name) ?? '';
80
+ }
81
+ this.element.setAttribute(name, value);
82
+ return this;
83
+ }
84
+
85
+ /** Remove an attribute. */
86
+ removeAttr(name: string): this {
87
+ this.element.removeAttribute(name);
88
+ return this;
89
+ }
90
+
91
+ /** Toggle an attribute on/off. */
92
+ toggleAttr(name: string, force?: boolean): this {
93
+ const hasAttr = this.element.hasAttribute(name);
94
+ const shouldAdd = force ?? !hasAttr;
95
+ if (shouldAdd) {
96
+ this.element.setAttribute(name, '');
97
+ } else {
98
+ this.element.removeAttribute(name);
99
+ }
100
+ return this;
101
+ }
102
+
103
+ /** Get or set a property. */
104
+ prop<T extends keyof Element>(name: T, value?: Element[T]): Element[T] | this {
105
+ if (value === undefined) {
106
+ return this.element[name];
107
+ }
108
+ this.element[name] = value;
109
+ return this;
110
+ }
111
+
112
+ /** Read or write data attributes in camelCase. */
113
+ data(name: string, value?: string): string | this {
114
+ const key = name.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
115
+ if (value === undefined) {
116
+ return this.element.getAttribute(`data-${key}`) ?? '';
117
+ }
118
+ this.element.setAttribute(`data-${key}`, value);
119
+ return this;
120
+ }
121
+
122
+ /** Get or set text content. */
123
+ text(value?: string): string | this {
124
+ if (value === undefined) {
125
+ return this.element.textContent ?? '';
126
+ }
127
+ this.element.textContent = value;
128
+ return this;
129
+ }
130
+
131
+ /** Set HTML content using a sanitized string. */
132
+ /**
133
+ * Sets sanitized HTML content on the element.
134
+ * Uses the security module to sanitize input and prevent XSS attacks.
135
+ *
136
+ * @param value - The HTML string to set (will be sanitized)
137
+ * @returns The instance for method chaining
138
+ *
139
+ * @example
140
+ * ```ts
141
+ * $('#content').html('<strong>Hello</strong>');
142
+ * ```
143
+ */
144
+ html(value: string): this {
145
+ setHtml(this.element, value);
146
+ return this;
147
+ }
148
+
149
+ /**
150
+ * Sets HTML content without sanitization.
151
+ * Use only when you trust the HTML source completely.
152
+ *
153
+ * @param value - The raw HTML string to set
154
+ * @returns The instance for method chaining
155
+ *
156
+ * @warning This method bypasses XSS protection. Use with caution.
157
+ */
158
+ htmlUnsafe(value: string): this {
159
+ this.element.innerHTML = value;
160
+ return this;
161
+ }
162
+
163
+ /**
164
+ * Gets or sets CSS styles on the element.
165
+ *
166
+ * @param property - A CSS property name or an object of property-value pairs
167
+ * @param value - The value when setting a single property
168
+ * @returns The computed style value when getting a single property, or the instance for method chaining when setting
169
+ *
170
+ * @example
171
+ * ```ts
172
+ * // Get a computed style value
173
+ * const color = $('#box').css('color');
174
+ *
175
+ * // Set a single property
176
+ * $('#box').css('color', 'red');
177
+ *
178
+ * // Set multiple properties
179
+ * $('#box').css({ color: 'red', 'font-size': '16px' });
180
+ * ```
181
+ */
182
+ css(property: string): string;
183
+ css(property: string, value: string): this;
184
+ css(property: Record<string, string>): this;
185
+ css(property: string | Record<string, string>, value?: string): string | this {
186
+ if (typeof property === 'string') {
187
+ if (value !== undefined) {
188
+ (this.element as HTMLElement).style.setProperty(property, value);
189
+ return this;
190
+ }
191
+ const view = this.element.ownerDocument?.defaultView;
192
+ if (!view || typeof view.getComputedStyle !== 'function') {
193
+ return '';
194
+ }
195
+ return view.getComputedStyle(this.element).getPropertyValue(property);
196
+ }
197
+
198
+ for (const [key, val] of Object.entries(property)) {
199
+ (this.element as HTMLElement).style.setProperty(key, val);
200
+ }
201
+ return this;
202
+ }
203
+
204
+ /**
205
+ * Appends HTML or elements to the end of the element.
206
+ *
207
+ * @param content - HTML string or element(s) to append
208
+ * @returns The instance for method chaining
209
+ */
210
+ append(content: string | Element | Element[]): this {
211
+ this.insertContent(content, 'beforeend');
212
+ return this;
213
+ }
214
+
215
+ /**
216
+ * Prepends HTML or elements to the beginning of the element.
217
+ *
218
+ * @param content - HTML string or element(s) to prepend
219
+ * @returns The instance for method chaining
220
+ */
221
+ prepend(content: string | Element | Element[]): this {
222
+ this.insertContent(content, 'afterbegin');
223
+ return this;
224
+ }
225
+
226
+ /**
227
+ * Inserts content before this element.
228
+ *
229
+ * @param content - HTML string or element(s) to insert
230
+ * @returns The instance for method chaining
231
+ */
232
+ before(content: string | Element | Element[]): this {
233
+ this.insertContent(content, 'beforebegin');
234
+ return this;
235
+ }
236
+
237
+ /**
238
+ * Inserts content after this element.
239
+ *
240
+ * @param content - HTML string or element(s) to insert
241
+ * @returns The instance for method chaining
242
+ */
243
+ after(content: string | Element | Element[]): this {
244
+ this.insertContent(content, 'afterend');
245
+ return this;
246
+ }
247
+
248
+ /**
249
+ * Wraps the element with the specified wrapper element or tag.
250
+ *
251
+ * @param wrapper - Tag name string or Element to wrap with
252
+ * @returns The instance for method chaining
253
+ *
254
+ * @example
255
+ * ```ts
256
+ * $('#content').wrap('div'); // Wraps with <div>
257
+ * $('#content').wrap(document.createElement('section'));
258
+ * ```
259
+ */
260
+ wrap(wrapper: string | Element): this {
261
+ const wrapperEl = typeof wrapper === 'string' ? document.createElement(wrapper) : wrapper;
262
+ this.element.parentNode?.insertBefore(wrapperEl, this.element);
263
+ wrapperEl.appendChild(this.element);
264
+ return this;
265
+ }
266
+
267
+ /**
268
+ * Removes the parent element, keeping this element in its place.
269
+ * Essentially the opposite of wrap().
270
+ *
271
+ * **Important**: This method only moves the current element out of its parent
272
+ * before removing the parent. Any sibling elements will be removed along with
273
+ * the parent. For unwrapping multiple siblings, use a collection: `$$(siblings).unwrap()`.
274
+ *
275
+ * @returns The instance for method chaining
276
+ *
277
+ * @example
278
+ * ```ts
279
+ * // Before: <div><span id="text">Hello</span></div>
280
+ * $('#text').unwrap();
281
+ * // After: <span id="text">Hello</span>
282
+ * ```
283
+ */
284
+ unwrap(): this {
285
+ const parent = this.element.parentElement;
286
+ if (parent && parent.parentNode) {
287
+ parent.parentNode.insertBefore(this.element, parent);
288
+ parent.remove();
289
+ }
290
+ return this;
291
+ }
292
+
293
+ /**
294
+ * Replaces this element with new content.
295
+ *
296
+ * @param content - HTML string (sanitized) or Element to replace with
297
+ * @returns A new BQueryElement wrapping the replacement element
298
+ *
299
+ * @example
300
+ * ```ts
301
+ * const newEl = $('#old').replaceWith('<div id="new">Replaced</div>');
302
+ * ```
303
+ */
304
+ replaceWith(content: string | Element): BQueryElement {
305
+ const newEl = typeof content === 'string' ? createElementFromHtml(content) : content;
306
+ this.element.replaceWith(newEl);
307
+ return new BQueryElement(newEl);
308
+ }
309
+
310
+ /**
311
+ * Scrolls the element into view with configurable behavior.
312
+ *
313
+ * @param options - ScrollIntoView options or boolean for legacy behavior
314
+ * @returns The instance for method chaining
315
+ *
316
+ * @example
317
+ * ```ts
318
+ * $('#section').scrollTo(); // Smooth scroll
319
+ * $('#section').scrollTo({ behavior: 'instant', block: 'start' });
320
+ * ```
321
+ */
322
+ scrollTo(options: ScrollIntoViewOptions | boolean = { behavior: 'smooth' }): this {
323
+ this.element.scrollIntoView(options);
324
+ return this;
325
+ }
326
+
327
+ /**
328
+ * Removes the element from the DOM.
329
+ *
330
+ * @returns The instance for method chaining (though element is now detached)
331
+ */
332
+ remove(): this {
333
+ this.element.remove();
334
+ return this;
335
+ }
336
+
337
+ /**
338
+ * Clears all child nodes from the element.
339
+ *
340
+ * @returns The instance for method chaining
341
+ */
342
+ empty(): this {
343
+ this.element.innerHTML = '';
344
+ return this;
345
+ }
346
+
347
+ /**
348
+ * Clones the element, optionally with all descendants.
349
+ *
350
+ * @param deep - If true, clone all descendants (default: true)
351
+ * @returns A new BQueryElement wrapping the cloned element
352
+ */
353
+ clone(deep: boolean = true): BQueryElement {
354
+ return new BQueryElement(this.element.cloneNode(deep) as Element);
355
+ }
356
+
357
+ /**
358
+ * Finds all descendant elements matching the selector.
359
+ *
360
+ * @param selector - CSS selector to match
361
+ * @returns Array of matching elements
362
+ */
363
+ find(selector: string): Element[] {
364
+ return Array.from(this.element.querySelectorAll(selector));
365
+ }
366
+
367
+ /**
368
+ * Finds the first descendant element matching the selector.
369
+ *
370
+ * @param selector - CSS selector to match
371
+ * @returns The first matching element or null
372
+ */
373
+ findOne(selector: string): Element | null {
374
+ return this.element.querySelector(selector);
375
+ }
376
+
377
+ /**
378
+ * Finds the closest ancestor matching the selector.
379
+ *
380
+ * @param selector - CSS selector to match
381
+ * @returns The matching ancestor or null
382
+ */
383
+ closest(selector: string): Element | null {
384
+ return this.element.closest(selector);
385
+ }
386
+
387
+ /**
388
+ * Gets the parent element.
389
+ *
390
+ * @returns The parent element or null
391
+ */
392
+ parent(): Element | null {
393
+ return this.element.parentElement;
394
+ }
395
+
396
+ /**
397
+ * Gets all child elements.
398
+ *
399
+ * @returns Array of child elements
400
+ */
401
+ children(): Element[] {
402
+ return Array.from(this.element.children);
403
+ }
404
+
405
+ /**
406
+ * Gets all sibling elements.
407
+ *
408
+ * @returns Array of sibling elements (excluding this element)
409
+ */
410
+ siblings(): Element[] {
411
+ const parent = this.element.parentElement;
412
+ if (!parent) return [];
413
+ return Array.from(parent.children).filter((child) => child !== this.element);
414
+ }
415
+
416
+ /**
417
+ * Gets the next sibling element.
418
+ *
419
+ * @returns The next sibling element or null
420
+ */
421
+ next(): Element | null {
422
+ return this.element.nextElementSibling;
423
+ }
424
+
425
+ /**
426
+ * Gets the previous sibling element.
427
+ *
428
+ * @returns The previous sibling element or null
429
+ */
430
+ prev(): Element | null {
431
+ return this.element.previousElementSibling;
432
+ }
433
+
434
+ /**
435
+ * Adds an event listener.
436
+ *
437
+ * @param event - Event type to listen for
438
+ * @param handler - Event handler function
439
+ * @returns The instance for method chaining
440
+ */
441
+ on(event: string, handler: EventListenerOrEventListenerObject): this {
442
+ this.element.addEventListener(event, handler);
443
+ return this;
444
+ }
445
+
446
+ /**
447
+ * Adds a one-time event listener that removes itself after firing.
448
+ *
449
+ * @param event - Event type to listen for
450
+ * @param handler - Event handler function
451
+ * @returns The instance for method chaining
452
+ */
453
+ once(event: string, handler: EventListener): this {
454
+ this.element.addEventListener(event, handler, { once: true });
455
+ return this;
456
+ }
457
+
458
+ /**
459
+ * Removes an event listener.
460
+ *
461
+ * @param event - Event type
462
+ * @param handler - The handler to remove
463
+ * @returns The instance for method chaining
464
+ */
465
+ off(event: string, handler: EventListenerOrEventListenerObject): this {
466
+ this.element.removeEventListener(event, handler);
467
+ return this;
468
+ }
469
+
470
+ /**
471
+ * Triggers a custom event on the element.
472
+ *
473
+ * @param event - Event type to trigger
474
+ * @param detail - Optional detail data to include with the event
475
+ * @returns The instance for method chaining
476
+ */
477
+ trigger(event: string, detail?: unknown): this {
478
+ this.element.dispatchEvent(new CustomEvent(event, { detail, bubbles: true, cancelable: true }));
479
+ return this;
480
+ }
481
+
482
+ /**
483
+ * Adds a delegated event listener that only triggers for matching descendants.
484
+ * More efficient than adding listeners to many elements individually.
485
+ *
486
+ * Use `undelegate()` to remove the listener later.
487
+ *
488
+ * @param event - Event type to listen for
489
+ * @param selector - CSS selector to match against event targets
490
+ * @param handler - Event handler function, receives the matched element as context
491
+ * @returns The instance for method chaining
492
+ *
493
+ * @example
494
+ * ```ts
495
+ * // Instead of adding listeners to each button:
496
+ * const handler = (e, target) => console.log('Clicked:', target.textContent);
497
+ * $('#list').delegate('click', '.item', handler);
498
+ *
499
+ * // Later, remove the delegated listener:
500
+ * $('#list').undelegate('click', '.item', handler);
501
+ * ```
502
+ */
503
+ delegate(
504
+ event: string,
505
+ selector: string,
506
+ handler: (event: Event, target: Element) => void
507
+ ): this {
508
+ const key = `${event}:${selector}`;
509
+ const wrapper: EventListener = (e: Event) => {
510
+ const target = (e.target as Element).closest(selector);
511
+ if (target && this.element.contains(target)) {
512
+ handler(e, target);
513
+ }
514
+ };
515
+
516
+ // Store the wrapper so it can be removed later
517
+ if (!this.delegatedHandlers.has(key)) {
518
+ this.delegatedHandlers.set(key, new Map());
519
+ }
520
+ this.delegatedHandlers.get(key)!.set(handler, wrapper);
521
+
522
+ this.element.addEventListener(event, wrapper);
523
+ return this;
524
+ }
525
+
526
+ /**
527
+ * Removes a delegated event listener previously added with `delegate()`.
528
+ *
529
+ * @param event - Event type that was registered
530
+ * @param selector - CSS selector that was used
531
+ * @param handler - The original handler function passed to delegate()
532
+ * @returns The instance for method chaining
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * const handler = (e, target) => console.log('Clicked:', target.textContent);
537
+ * $('#list').delegate('click', '.item', handler);
538
+ *
539
+ * // Remove the delegated listener:
540
+ * $('#list').undelegate('click', '.item', handler);
541
+ * ```
542
+ */
543
+ undelegate(
544
+ event: string,
545
+ selector: string,
546
+ handler: (event: Event, target: Element) => void
547
+ ): this {
548
+ const key = `${event}:${selector}`;
549
+ const handlers = this.delegatedHandlers.get(key);
550
+
551
+ if (handlers) {
552
+ const wrapper = handlers.get(handler);
553
+ if (wrapper) {
554
+ this.element.removeEventListener(event, wrapper);
555
+ handlers.delete(handler);
556
+
557
+ // Clean up empty maps
558
+ if (handlers.size === 0) {
559
+ this.delegatedHandlers.delete(key);
560
+ }
561
+ }
562
+ }
563
+
564
+ return this;
565
+ }
566
+
567
+ /**
568
+ * Checks if the element matches a CSS selector.
569
+ *
570
+ * @param selector - CSS selector to match against
571
+ * @returns True if the element matches the selector
572
+ */
573
+ matches(selector: string): boolean {
574
+ return this.element.matches(selector);
575
+ }
576
+
577
+ /**
578
+ * Alias for `matches()`. Checks if the element matches a CSS selector.
579
+ *
580
+ * @param selector - CSS selector to match against
581
+ * @returns True if the element matches the selector
582
+ *
583
+ * @example
584
+ * ```ts
585
+ * if ($('#el').is('.active')) {
586
+ * console.log('Element is active');
587
+ * }
588
+ * ```
589
+ */
590
+ is(selector: string): boolean {
591
+ return this.matches(selector);
592
+ }
593
+
594
+ /**
595
+ * Checks if the element has a specific class.
596
+ *
597
+ * @param className - Class name to check
598
+ * @returns True if the element has the class
599
+ */
600
+ hasClass(className: string): boolean {
601
+ return this.element.classList.contains(className);
602
+ }
603
+
604
+ /**
605
+ * Shows the element by removing the hidden attribute and setting display.
606
+ *
607
+ * @param display - Optional display value (default: '')
608
+ * @returns The instance for method chaining
609
+ */
610
+ show(display: string = ''): this {
611
+ this.element.removeAttribute('hidden');
612
+ (this.element as HTMLElement).style.display = display;
613
+ return this;
614
+ }
615
+
616
+ /**
617
+ * Hides the element by setting display to 'none'.
618
+ *
619
+ * @returns The instance for method chaining
620
+ */
621
+ hide(): this {
622
+ (this.element as HTMLElement).style.display = 'none';
623
+ return this;
624
+ }
625
+
626
+ /**
627
+ * Toggles the visibility of the element.
628
+ *
629
+ * @param force - Optional force show (true) or hide (false)
630
+ * @returns The instance for method chaining
631
+ */
632
+ toggle(force?: boolean): this {
633
+ const isHidden = (this.element as HTMLElement).style.display === 'none';
634
+ const shouldShow = force ?? isHidden;
635
+ return shouldShow ? this.show() : this.hide();
636
+ }
637
+
638
+ /**
639
+ * Focuses the element.
640
+ *
641
+ * @returns The instance for method chaining
642
+ */
643
+ focus(): this {
644
+ (this.element as HTMLElement).focus();
645
+ return this;
646
+ }
647
+
648
+ /**
649
+ * Blurs (unfocuses) the element.
650
+ *
651
+ * @returns The instance for method chaining
652
+ */
653
+ blur(): this {
654
+ (this.element as HTMLElement).blur();
655
+ return this;
656
+ }
657
+
658
+ /**
659
+ * Gets or sets the value of form elements.
660
+ *
661
+ * @param newValue - Optional value to set
662
+ * @returns The current value when getting, or the instance when setting
663
+ */
664
+ val(newValue?: string): string | this {
665
+ const input = this.element as HTMLInputElement;
666
+ if (newValue === undefined) {
667
+ return input.value ?? '';
668
+ }
669
+ input.value = newValue;
670
+ return this;
671
+ }
672
+
673
+ /**
674
+ * Serializes form data to a plain object.
675
+ * Only works on form elements; returns empty object for non-forms.
676
+ *
677
+ * @returns Object with form field names as keys and values
678
+ *
679
+ * @example
680
+ * ```ts
681
+ * // For a form with <input name="email" value="test@example.com">
682
+ * const data = $('#myForm').serialize();
683
+ * // { email: 'test@example.com' }
684
+ * ```
685
+ */
686
+ serialize(): Record<string, string | string[]> {
687
+ const form = this.element as HTMLFormElement;
688
+ if (form.tagName.toLowerCase() !== 'form') {
689
+ return {};
690
+ }
691
+
692
+ const result: Record<string, string | string[]> = {};
693
+ const formData = new FormData(form);
694
+
695
+ for (const [key, value] of formData.entries()) {
696
+ if (typeof value !== 'string') continue; // Skip File objects
697
+
698
+ if (key in result) {
699
+ // Handle multiple values (e.g., checkboxes)
700
+ const existing = result[key];
701
+ if (Array.isArray(existing)) {
702
+ existing.push(value);
703
+ } else {
704
+ result[key] = [existing, value];
705
+ }
706
+ } else {
707
+ result[key] = value;
708
+ }
709
+ }
710
+
711
+ return result;
712
+ }
713
+
714
+ /**
715
+ * Serializes form data to a URL-encoded query string.
716
+ *
717
+ * @returns URL-encoded string suitable for form submission
718
+ *
719
+ * @example
720
+ * ```ts
721
+ * const queryString = $('#myForm').serializeString();
722
+ * // 'email=test%40example.com&name=John'
723
+ * ```
724
+ */
725
+ serializeString(): string {
726
+ const form = this.element as HTMLFormElement;
727
+ if (form.tagName.toLowerCase() !== 'form') {
728
+ return '';
729
+ }
730
+
731
+ const formData = new FormData(form);
732
+ const params = new URLSearchParams();
733
+
734
+ for (const [key, value] of formData.entries()) {
735
+ if (typeof value === 'string') {
736
+ params.append(key, value);
737
+ }
738
+ }
739
+
740
+ return params.toString();
741
+ }
742
+
743
+ /**
744
+ * Gets the bounding client rectangle of the element.
745
+ *
746
+ * @returns The element's bounding rectangle
747
+ */
748
+ rect(): DOMRect {
749
+ return this.element.getBoundingClientRect();
750
+ }
751
+
752
+ /**
753
+ * Gets the offset dimensions (width, height, top, left).
754
+ *
755
+ * @returns Object with offset dimensions
756
+ */
757
+ offset(): { width: number; height: number; top: number; left: number } {
758
+ const el = this.element as HTMLElement;
759
+ return {
760
+ width: el.offsetWidth,
761
+ height: el.offsetHeight,
762
+ top: el.offsetTop,
763
+ left: el.offsetLeft,
764
+ };
765
+ }
766
+
767
+ /**
768
+ * Internal method to insert content at a specified position.
769
+ * @internal
770
+ */
771
+ private insertContent(content: string | Element | Element[], position: InsertPosition) {
772
+ insertContent(this.element, content, position);
773
+ }
774
+ }