All files / src/compiler/phases/3-transform/css index.js

99.47% Statements 377/379
98.26% Branches 113/115
100% Functions 12/12
99.46% Lines 372/374

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 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 3752x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 394x 2x 2x 394x 394x 394x 2x 2x 2x 2x 11308x 11308x 11308x 2x 2x 112x 20x 20x 20x 20x 20x 20x 4x 20x 16x 16x 20x 20x 20x 92x 92x 2x 2x 1151x 1151x 24x 24x 24x 24x 438x 438x 438x 92x 16x 16x 92x 92x 24x 24x 68x 68x 438x 346x 346x 414x 414x 414x 24x 2x 2x 1351x 1351x 1351x 10x 10x 10x 10x 10x 1341x 1351x 212x 212x 212x 212x 212x 212x 1129x 1351x 24x 24x 24x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 18x 18x 18x 18x 18x 1105x 1105x 2x 2x 1165x 1165x 1165x 1165x 1183x 1183x 1183x 14x 2x 2x 2x 2x 14x 12x 2x 12x 10x 10x 12x 14x 14x 14x 1183x 1183x 1183x 1165x 1165x 10x 10x 1165x 1165x 1165x 1165x 1165x 1165x 1165x 1165x 1123x 1123x 1123x 1123x 1123x 1123x 44x 38x 38x 38x 6x 6x 1123x 1165x 1165x 2x 2x 1183x 1183x 1183x 1183x 1183x 1183x 1183x 130x 18x 18x 14x 14x 14x 18x 130x 112x 112x 112x 112x 130x 1183x 1183x 1946x 120x 120x 120x 120x 120x 120x 6x 120x 2x 2x 2x 120x 120x 1826x 1944x 1762x 1688x 1688x 1688x 1688x 4x 1688x 2x 2x 1688x 1760x 1760x 1762x 1842x 10x 10x 1842x 1760x 1762x 18x 18x 1742x 1742x 1742x 1742x 1742x 1762x 1742x 1742x 1742x 1742x 1762x 1794x 1794x 1794x 1794x 1790x 1794x 54x 54x 54x 54x 54x 1740x 1794x 10x 1794x 1730x 1730x 1740x 1740x 1740x 1762x 1946x 1183x 1183x 1183x 1183x 2x 2x 204x 42x 42x 204x 2x 2x 2x 1363x 1363x 36x 36x 1327x 1363x 1323x 1291x 1291x 32x 1202x 26x 26x 12x 1202x 6x 6x 1323x 10x 10x 10x 2x 2x 1367x 1367x 1367x 2x 2x 2x 2x 2x 2x 222x 222x 222x 222x 222x 6414x   6414x 6414x 6414x 16x 2x 2x 2x 6414x   6398x 2x 2x 6414x 6414x 222x  
/** @import { Visitors } from 'zimmerframe' */
/** @import { ValidatedCompileOptions, Css } from '#compiler' */
/** @import { ComponentAnalysis } from '../../types.js' */
import MagicString from 'magic-string';
import { walk } from 'zimmerframe';
import { is_keyframes_node, regex_css_name_boundary, remove_css_prefix } from '../../css.js';
import { merge_with_preprocessor_map } from '../../../utils/mapped_code.js';
import { dev } from '../../../state.js';
 
/**
 * @typedef {{
 *   code: MagicString;
 *   hash: string;
 *   selector: string;
 *   keyframes: string[];
 *   specificity: {
 *     bumped: boolean
 *   }
 * }} State
 */
 
/**
 *
 * @param {string} source
 * @param {ComponentAnalysis} analysis
 * @param {ValidatedCompileOptions} options
 */
export function render_stylesheet(source, analysis, options) {
	const code = new MagicString(source);
 
	/** @type {State} */
	const state = {
		code,
		hash: analysis.css.hash,
		selector: `.${analysis.css.hash}`,
		keyframes: analysis.css.keyframes,
		specificity: {
			bumped: false
		}
	};
 
	const ast = /** @type {Css.StyleSheet} */ (analysis.css.ast);
 
	walk(/** @type {Css.Node} */ (ast), state, visitors);
 
	code.remove(0, ast.content.start);
	code.remove(/** @type {number} */ (ast.content.end), source.length);
 
	const css = {
		code: code.toString(),
		map: code.generateMap({
			// include source content; makes it easier/more robust looking up the source map code
			includeContent: true,
			// generateMap takes care of calculating source relative to file
			source: options.filename,
			file: options.cssOutputFilename || options.filename
		})
	};
 
	merge_with_preprocessor_map(css, options, css.map.sources[0]);
 
	if (dev && options.css === 'injected' && css.code) {
		css.code += `\n/*# sourceMappingURL=${css.map.toUrl()} */`;
	}
 
	return css;
}
 
/** @type {Visitors<Css.Node, State>} */
const visitors = {
	_: (node, context) => {
		context.state.code.addSourcemapLocation(node.start);
		context.state.code.addSourcemapLocation(node.end);
		context.next();
	},
	Atrule(node, { state, next }) {
		if (is_keyframes_node(node)) {
			let start = node.start + node.name.length + 1;
			while (state.code.original[start] === ' ') start += 1;
			let end = start;
			while (state.code.original[end] !== '{' && state.code.original[end] !== ' ') end += 1;
 
			if (node.prelude.startsWith('-global-')) {
				state.code.remove(start, start + 8);
			} else {
				state.code.prependRight(start, `${state.hash}-`);
			}
 
			return; // don't transform anything within
		}
 
		next();
	},
	Declaration(node, { state }) {
		const property = node.property && remove_css_prefix(node.property.toLowerCase());
		if (property === 'animation' || property === 'animation-name') {
			let index = node.start + node.property.length + 1;
			let name = '';
 
			while (index < state.code.original.length) {
				const character = state.code.original[index];
 
				if (regex_css_name_boundary.test(character)) {
					if (state.keyframes.includes(name)) {
						state.code.prependRight(index - name.length, `${state.hash}-`);
					}
 
					if (character === ';' || character === '}') {
						break;
					}
 
					name = '';
				} else {
					name += character;
				}
 
				index++;
			}
		}
	},
	Rule(node, { state, next, visit }) {
		// keep empty rules in dev, because it's convenient to
		// see them in devtools
		if (!dev && is_empty(node)) {
			state.code.prependRight(node.start, '/* (empty) ');
			state.code.appendLeft(node.end, '*/');
			escape_comment_close(node, state.code);
			return;
		}
 
		if (!is_used(node)) {
			state.code.prependRight(node.start, '/* (unused) ');
			state.code.appendLeft(node.end, '*/');
			escape_comment_close(node, state.code);
 
			return;
		}
 
		if (node.metadata.is_global_block) {
			const selector = node.prelude.children[0];
 
			if (selector.children.length === 1 && selector.children[0].selectors.length === 1) {
				// `:global {...}`
				state.code.prependRight(node.start, '/* ');
				state.code.appendLeft(node.block.start + 1, '*/');
 
				state.code.prependRight(node.block.end - 1, '/*');
				state.code.appendLeft(node.block.end, '*/');
 
				// don't recurse into selector or body
				return;
			}
 
			// don't recurse into body
			visit(node.prelude);
			return;
		}
 
		next();
	},
	SelectorList(node, { state, next, path }) {
		let pruning = false;
		let last = node.children[0].start;
 
		for (let i = 0; i < node.children.length; i += 1) {
			const selector = node.children[i];
 
			if (selector.metadata.used === pruning) {
				if (pruning) {
					let i = selector.start;
					while (state.code.original[i] !== ',') i--;
 
					state.code.overwrite(i, i + 1, '*/');
				} else {
					if (i === 0) {
						state.code.prependRight(selector.start, '/* (unused) ');
					} else {
						state.code.overwrite(last, selector.start, ' /* (unused) ');
					}
				}
 
				pruning = !pruning;
			}
 
			last = selector.end;
		}
 
		if (pruning) {
			state.code.appendLeft(last, '*/');
		}
 
		// if we're in a `:is(...)` or whatever, keep existing specificity bump state
		let specificity = state.specificity;
 
		// if this selector list belongs to a rule, require a specificity bump for the
		// first scoped selector but only if we're at the top level
		let parent = path.at(-1);
		if (parent?.type === 'Rule') {
			specificity = { bumped: false };
 
			/** @type {Css.Rule | null} */
			let rule = parent.metadata.parent_rule;
 
			while (rule) {
				if (rule.metadata.has_local_selectors) {
					specificity = { bumped: true };
					break;
				}
				rule = rule.metadata.parent_rule;
			}
		}
 
		next({ ...state, specificity });
	},
	ComplexSelector(node, context) {
		const before_bumped = context.state.specificity.bumped;
 
		/**
		 * @param {Css.PseudoClassSelector} selector
		 * @param {Css.Combinator | null} combinator
		 */
		function remove_global_pseudo_class(selector, combinator) {
			if (selector.args === null) {
				let start = selector.start;
				if (combinator?.name === ' ') {
					// div :global.x becomes div.x
					while (/\s/.test(context.state.code.original[start - 1])) start--;
				}
				context.state.code.remove(start, selector.start + ':global'.length);
			} else {
				context.state.code
					.remove(selector.start, selector.start + ':global('.length)
					.remove(selector.end - 1, selector.end);
			}
		}
 
		for (const relative_selector of node.children) {
			if (relative_selector.metadata.is_global) {
				const global = /** @type {Css.PseudoClassSelector} */ (relative_selector.selectors[0]);
				remove_global_pseudo_class(global, relative_selector.combinator);
 
				if (
					node.metadata.rule?.metadata.parent_rule &&
					global.args === null &&
					relative_selector.combinator === null
				) {
					// div { :global.x { ... } } becomes div { &.x { ... } }
					context.state.code.prependRight(global.start, '&');
				}
				continue;
			}
 
			if (relative_selector.metadata.scoped) {
				if (relative_selector.selectors.length === 1) {
					// skip standalone :is/:where/& selectors
					const selector = relative_selector.selectors[0];
					if (
						selector.type === 'PseudoClassSelector' &&
						(selector.name === 'is' || selector.name === 'where')
					) {
						continue;
					}
				}
 
				// for any :global() or :global at the middle of compound selector
				for (const selector of relative_selector.selectors) {
					if (selector.type === 'PseudoClassSelector' && selector.name === 'global') {
						remove_global_pseudo_class(selector, null);
					}
				}
 
				if (relative_selector.selectors.some((s) => s.type === 'NestingSelector')) {
					continue;
				}
 
				// for the first occurrence, we use a classname selector, so that every
				// encapsulated selector gets a +0-1-0 specificity bump. thereafter,
				// we use a `:where` selector, which does not affect specificity
				let modifier = context.state.selector;
				if (context.state.specificity.bumped) modifier = `:where(${modifier})`;
 
				context.state.specificity.bumped = true;
 
				let i = relative_selector.selectors.length;
				while (i--) {
					const selector = relative_selector.selectors[i];
 
					if (
						selector.type === 'PseudoElementSelector' ||
						selector.type === 'PseudoClassSelector'
					) {
						if (selector.name !== 'root' && selector.name !== 'host') {
							if (i === 0) context.state.code.prependRight(selector.start, modifier);
						}
						continue;
					}
 
					if (selector.type === 'TypeSelector' && selector.name === '*') {
						context.state.code.update(selector.start, selector.end, modifier);
					} else {
						context.state.code.appendLeft(selector.end, modifier);
					}
 
					break;
				}
			}
		}
 
		context.next();
 
		context.state.specificity.bumped = before_bumped;
	},
	PseudoClassSelector(node, context) {
		if (node.name === 'is' || node.name === 'where' || node.name === 'has') {
			context.next();
		}
	}
};
 
/** @param {Css.Rule} rule */
function is_empty(rule) {
	if (rule.metadata.is_global_block) {
		return rule.block.children.length === 0;
	}
 
	for (const child of rule.block.children) {
		if (child.type === 'Declaration') {
			return false;
		}
 
		if (child.type === 'Rule') {
			if (is_used(child) && !is_empty(child)) return false;
		}
 
		if (child.type === 'Atrule') {
			if (child.block === null || child.block.children.length > 0) return false;
		}
	}
 
	return true;
}
 
/** @param {Css.Rule} rule */
function is_used(rule) {
	return rule.prelude.children.some((selector) => selector.metadata.used);
}
 
/**
 *
 * @param {Css.Rule} node
 * @param {MagicString} code
 */
function escape_comment_close(node, code) {
	let escaped = false;
	let in_comment = false;
 
	for (let i = node.start; i < node.end; i++) {
		if (escaped) {
			escaped = false;
		} else {
			const char = code.original[i];
			if (in_comment) {
				if (char === '*' && code.original[i + 1] === '/') {
					code.prependRight(++i, '\\');
					in_comment = false;
				}
			} else if (char === '\\') {
				escaped = true;
			} else if (char === '/' && code.original[++i] === '*') {
				in_comment = true;
			}
		}
	}
}