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

86.97% Statements 267/307
83.95% Branches 68/81
81.81% Functions 9/11
86.71% Lines 261/301

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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 3022x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 757x 365x 365x 365x 757x 2x 2x 2x 2x 2x 2x 2x 1516x 1516x 1516x 1516x 1516x 1516x 937x 937x 937x 14x 14x 14x 14x 14x 14x 14x 14x 937x 1502x 1516x 706x 1511x 332x 1516x 374x 374x 1516x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x     1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 397x 397x 397x 397x 358x 34x 34x 358x 192x 397x 1x 1x 397x 397x 397x 397x 397x 397x 397x 397x 709x 709x 509x 509x 709x 507x 709x 58x 58x 58x 58x 58x 58x 58x 58x 2x 58x 2x 2x 2x 58x 58x     58x 58x 58x 2x 58x 56x 56x 56x 56x 58x 709x 40x 40x 449x 24x 409x 4x 385x 56x 56x 381x 325x 325x 301x 301x 301x 325x 325x 67x   67x 67x 67x 67x 325x 254x 10x 10x 10x 254x 254x 254x 325x 709x 397x 397x 397x 2x 2x 2x 2x 2x 2x 2x 2x 43x                             43x 43x 43x 43x 43x 43x 43x 43x 43x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 22x 22x 22x 22x 22x 22x 22x 22x 609x 461x 461x 609x 22x 22x 22x 2x 2x 2x 2x 2x 2x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 14x 14x 1x 1x 2x 2x       2x 2x 2x 2x 2x 2x                                      
import { DEV } from 'esm-env';
import { hydrating } from '../hydration.js';
import { get_descriptors, map_get, map_set, object_assign } from '../../utils.js';
import { AttributeAliases, DelegatedEvents, namespace_svg } from '../../../../constants.js';
import { delegate } from './events.js';
import { autofocus } from './misc.js';
 
/**
 * The value/checked attribute in the template 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 {HTMLInputElement | HTMLSelectElement} dom
 * @returns {void}
 */
export function remove_input_attr_defaults(dom) {
	if (hydrating) {
		set_attribute(dom, 'value', null);
		set_attribute(dom, 'checked', null);
	}
}
 
/**
 * @param {Element} element
 * @param {string} attribute
 * @param {string | null} value
 */
export function set_attribute(element, attribute, value) {
	value = value == null ? null : value + '';
 
	// @ts-expect-error
	var attributes = (element.__attributes ??= {});
 
	if (hydrating) {
		attributes[attribute] = element.getAttribute(attribute);
 
		if (attribute === 'src' || attribute === 'href' || attribute === 'srcset') {
			check_src_in_dev_hydration(element, attribute, value);
 
			// If we reset these attributes, they would result in another network request, which we want to avoid.
			// We assume they are the same between client and server as checking if they are equal is expensive
			// (we can't just compare the strings as they can be different between client and server but result in the
			// same url, so we would need to create hidden anchor elements to compare them)
			return;
		}
	}
 
	if (attributes[attribute] === (attributes[attribute] = value)) return;
 
	if (value === null) {
		element.removeAttribute(attribute);
	} else {
		element.setAttribute(attribute, value);
	}
}
 
/**
 * @param {Element} dom
 * @param {string} attribute
 * @param {string} value
 */
export function set_xlink_attribute(dom, attribute, value) {
	dom.setAttributeNS('http://www.w3.org/1999/xlink', attribute, value);
}
 
/**
 * @param {any} node
 * @param {string} prop
 * @param {any} value
 */
export function set_custom_element_data(node, prop, value) {
	if (prop in node) {
		var curr_val = node[prop];
		var next_val = typeof curr_val === 'boolean' && value === '' ? true : value;
		if (typeof curr_val !== 'object' || curr_val !== next_val) {
			node[prop] = next_val;
		}
	} else {
		set_attribute(node, prop, value);
	}
}
 
/**
 * Spreads attributes onto a DOM element, taking into account the currently set attributes
 * @param {Element & ElementCSSInlineStyle} element
 * @param {Record<string, unknown> | undefined} prev
 * @param {Record<string, unknown>[]} attrs
 * @param {boolean} lowercase_attributes
 * @param {string} css_hash
 * @returns {Record<string, unknown>}
 */
export function set_attributes(element, prev, attrs, lowercase_attributes, css_hash) {
	var next = object_assign({}, ...attrs);
	var has_hash = css_hash.length !== 0;
 
	for (var key in prev) {
		if (!(key in next)) {
			next[key] = null;
		}
	}
 
	if (has_hash && !next.class) {
		next.class = '';
	}
 
	var setters = map_get(setters_cache, element.nodeName);
	if (!setters) map_set(setters_cache, element.nodeName, (setters = get_setters(element)));
 
	// @ts-expect-error
	var attributes = /** @type {Record<string, unknown>} **/ (element.__attributes ??= {});
 
	for (key in next) {
		var value = next[key];
		if (value === prev?.[key]) continue;
 
		var prefix = key[0] + key[1]; // this is faster than key.slice(0, 2)
		if (prefix === '$$') continue;
 
		if (prefix === 'on') {
			/** @type {{ capture?: true }} */
			var opts = {};
			var event_name = key.slice(2);
			var delegated = DelegatedEvents.includes(event_name);
 
			if (
				event_name.endsWith('capture') &&
				event_name !== 'ongotpointercapture' &&
				event_name !== 'onlostpointercapture'
			) {
				event_name = event_name.slice(0, -7);
				opts.capture = true;
			}
 
			if (!delegated && prev?.[key]) {
				element.removeEventListener(event_name, /** @type {any} */ (prev[key]), opts);
			}
 
			if (value != null) {
				if (!delegated) {
					element.addEventListener(event_name, value, opts);
				} else {
					// @ts-ignore
					element[`__${event_name}`] = value;
					delegate([event_name]);
				}
			}
		} else if (value == null) {
			attributes[key] = null;
			element.removeAttribute(key);
		} else if (key === 'style') {
			element.style.cssText = value + '';
		} else if (key === 'autofocus') {
			autofocus(/** @type {HTMLElement} */ (element), Boolean(value));
		} else if (key === '__value' || key === 'value') {
			// @ts-ignore
			element.value = element[key] = element.__value = value;
		} else {
			var name = key;
			if (lowercase_attributes) {
				name = name.toLowerCase();
				name = AttributeAliases[name] || name;
			}
 
			if (setters.includes(name)) {
				if (hydrating && (name === 'src' || name === 'href' || name === 'srcset')) {
					check_src_in_dev_hydration(element, name, value);
				} else {
					// @ts-ignore
					element[name] = value;
				}
			} else if (typeof value !== 'function') {
				if (has_hash && name === 'class') {
					if (value) value += ' ';
					value += css_hash;
				}
 
				set_attribute(element, name, value);
			}
		}
	}
 
	return next;
}
 
/**
 * @param {Element} node
 * @param {Record<string, unknown> | undefined} prev
 * @param {Record<string, unknown>[]} attrs
 * @param {string} css_hash
 */
export function set_dynamic_element_attributes(node, prev, attrs, css_hash) {
	if (node.tagName.includes('-')) {
		var next = object_assign({}, ...attrs);

		for (var key in prev) {
			if (!(key in next)) {
				next[key] = null;
			}
		}

		for (key in next) {
			set_custom_element_data(node, key, next[key]);
		}

		return next;
	}
 
	return set_attributes(
		/** @type {Element & ElementCSSInlineStyle} */ (node),
		prev,
		attrs,
		node.namespaceURI !== namespace_svg,
		css_hash
	);
}
 
/**
 * List of attributes that should always be set through the attr method,
 * because updating them through the property setter doesn't work reliably.
 * In the example of `width`/`height`, the problem is that the setter only
 * accepts numeric values, but the attribute can also be set to a string like `50%`.
 * If this list becomes too big, rethink this approach.
 */
var always_set_through_set_attribute = ['width', 'height'];
 
/** @type {Map<string, string[]>} */
var setters_cache = new Map();
 
/** @param {Element} element */
function get_setters(element) {
	/** @type {string[]} */
	var setters = [];
 
	// @ts-expect-error
	var descriptors = get_descriptors(element.__proto__);
 
	for (var key in descriptors) {
		if (descriptors[key].set && !always_set_through_set_attribute.includes(key)) {
			setters.push(key);
		}
	}
 
	return setters;
}
 
/**
 * @param {any} element
 * @param {string} attribute
 * @param {string | null} value
 */
function check_src_in_dev_hydration(element, attribute, value) {
	if (!DEV) return;
	if (attribute === 'srcset' && srcset_url_equal(element, value)) return;
	if (src_url_equal(element.getAttribute(attribute) ?? '', value ?? '')) return;
 
	// eslint-disable-next-line no-console
	console.error(
		`Detected a ${attribute} attribute value change during hydration. This will not be repaired during hydration, ` +
			`the ${attribute} value that came from the server will be used. Related element:`,
		element,
		' Differing value:',
		value
	);
}
 
/**
 * @param {string} element_src
 * @param {string} url
 * @returns {boolean}
 */
function src_url_equal(element_src, url) {
	if (element_src === url) return true;
	return new URL(element_src, document.baseURI).href === new URL(url, document.baseURI).href;
}
 
/** @param {string} srcset */
function split_srcset(srcset) {
	return srcset.split(',').map((src) => src.trim().split(' ').filter(Boolean));
}
 
/**
 * @param {HTMLSourceElement | HTMLImageElement} element
 * @param {string | undefined | null} srcset
 * @returns {boolean}
 */
function srcset_url_equal(element, srcset) {
	var element_urls = split_srcset(element.srcset);
	var urls = split_srcset(srcset ?? '');

	return (
		urls.length === element_urls.length &&
		urls.every(
			([url, width], i) =>
				width === element_urls[i][1] &&
				// We need to test both ways because Vite will create an a full URL with
				// `new URL(asset, import.meta.url).href` for the client when `base: './'`, and the
				// relative URLs inside srcset are not automatically resolved to absolute URLs by
				// browsers (in contrast to img.src). This means both SSR and DOM code could
				// contain relative or absolute URLs.
				(src_url_equal(element_urls[i][0], url) || src_url_equal(url, element_urls[i][0]))
		)
	);
}