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

99.47% Statements 377/379
98.24% Branches 112/114
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 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 392x 2x 2x 392x 392x 392x 2x 2x 2x 2x 10804x 10804x 10804x 2x 2x 112x 20x 20x 20x 20x 20x 20x 4x 20x 16x 16x 20x 20x 20x 92x 92x 2x 2x 1117x 1117x 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 1299x 1299x 1299x 8x 8x 8x 8x 8x 1291x 1299x 200x 200x 200x 200x 200x 200x 1091x 1299x 24x 24x 24x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 18x 18x 18x 18x 18x 1067x 1067x 2x 2x 1089x 1089x 1089x 1089x 1103x 1103x 1103x 12x 2x 2x 2x 2x 12x 10x 2x 10x 8x 8x 10x 12x 12x 12x 1103x 1103x 1103x 1089x 1089x 8x 8x 1089x 1089x 1089x 1089x 1089x 1089x 1089x 1089x 1085x 1085x 1085x 1085x 1085x 1085x 40x 34x 34x 34x 6x 6x 1085x 1089x 1089x 2x 2x 1103x 1103x 1103x 1103x 1103x 1103x 1103x 112x 18x 18x 14x 14x 14x 18x 112x 94x 94x 94x 94x 112x 1103x 1103x 1858x 102x 102x 102x 102x 102x 102x 6x 102x 2x 2x 2x 102x 102x 1756x 1856x 1694x 1650x 1650x 1650x 1650x 4x 1650x 2x 2x 1650x 1692x 1692x 1694x 1742x 10x 10x 1742x 1692x 1694x 16x 16x 1676x 1676x 1676x 1676x 1676x 1694x 1676x 1676x 1676x 1676x 1694x 1696x 1696x 1696x 1696x 1692x 1696x 22x 22x 22x 22x 22x 1674x 1696x 10x 1696x 1664x 1664x 1674x 1674x 1674x 1694x 1858x 1103x 1103x 1103x 1103x 2x 2x 150x 4x 4x 150x 2x 2x 2x 1307x 1307x 36x 36x 1271x 1307x 1267x 1241x 1241x 26x 1146x 20x 20x 10x 1146x 6x 6x 1267x 8x 8x 8x 2x 2x 1311x 1311x 1311x 2x 2x 2x 2x 2x 2x 208x 208x 208x 208x 208x 5902x   5902x 5902x 5902x 16x 2x 2x 2x 5902x   5886x 2x 2x 5902x 5902x 208x  
/** @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') {
			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;
			}
		}
	}
}