All files / src/internal/client/dom/elements misc.js

100% Statements 61/61
100% Branches 12/12
100% Functions 4/4
100% Lines 58/58

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 592x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x 6x 6x 6x 6x 6x 6x 6x 6x 6x 10x 2x 2x 2x 2x 2x 2x 2x 2x 17x 7x 7x 17x 2x 2x 2x 2x 1059x 3x 3x 3x 3x 4x 4x 4x 4x 4x 22x 22x 22x 4x 4x 3x 3x 3x 3x 3x 1059x  
import { hydrating } from '../hydration.js';
import { clear_text_content } from '../operations.js';
import { queue_micro_task } from '../task.js';
 
/**
 * @param {HTMLElement} dom
 * @param {boolean} value
 * @returns {void}
 */
export function autofocus(dom, value) {
	if (value) {
		const body = document.body;
		dom.autofocus = true;
 
		queue_micro_task(() => {
			if (document.activeElement === body) {
				dom.focus();
			}
		});
	}
}
 
/**
 * The child of a textarea actually corresponds to the defaultValue property, so we need
 * to remove it upon hydration to avoid a bug when someone resets the form value.
 * @param {HTMLTextAreaElement} dom
 * @returns {void}
 */
export function remove_textarea_child(dom) {
	if (hydrating && dom.firstChild !== null) {
		clear_text_content(dom);
	}
}
 
let listening_to_form_reset = false;
 
export function add_form_reset_listener() {
	if (!listening_to_form_reset) {
		listening_to_form_reset = true;
		document.addEventListener(
			'reset',
			(evt) => {
				// Needs to happen one tick later or else the dom properties of the form
				// elements have not updated to their reset values yet
				Promise.resolve().then(() => {
					if (!evt.defaultPrevented) {
						for (const e of /**@type {HTMLFormElement} */ (evt.target).elements) {
							// @ts-expect-error
							e.__on_r?.();
						}
					}
				});
			},
			// In the capture phase to guarantee we get noticed of it (no possiblity of stopPropagation)
			{ capture: true }
		);
	}
}