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

98.91% Statements 365/369
96.42% Branches 108/112
100% Functions 12/12
98.9% Lines 361/365

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 3662x 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 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 375x 2x 2x 375x 375x 375x 2x 2x 2x 2x 10406x 10406x 10406x 2x 2x 96x 20x 20x 20x 20x 20x 20x 4x 20x 16x 16x 20x 20x 20x 76x 76x 2x 2x 1082x 1082x 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 1250x 1250x 1250x 8x 8x 8x 8x 8x 1242x 1250x 194x 194x 194x 194x 194x 194x 1048x 1250x 8x 8x 8x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1040x 1040x 2x 2x 1046x 1046x 1046x 1046x 1060x 1060x 1060x 12x 2x 2x 2x 2x 12x 10x 2x 10x 8x 8x 10x 12x 12x 12x 1060x 1060x 1060x 1046x 1046x 8x 8x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1046x 1044x 1044x 1044x 1044x 1044x 1044x 24x 22x 22x 22x 2x 2x 1044x 1046x 1046x 2x 2x 1060x 1060x 1060x 1060x 98x 98x 98x 98x 1060x 1060x 1799x 88x 88x 88x 1711x 1797x 1661x 1619x 1619x 1619x 1619x 4x 1619x 2x 2x 1619x 1659x 1659x 1661x 1707x 10x 10x 1707x 1659x 1661x 14x 14x 1645x 1645x 1645x 1645x 1645x 1661x 1645x 1645x 1645x 1645x 1661x 1663x 1663x 1663x 1663x 1659x 1663x 20x 20x 20x 20x 20x 1643x 1663x 10x 1663x 1633x 1633x 1643x 1643x 1643x 1661x 1799x 1060x 1060x 1060x 1060x 2x 2x 130x 2x 2x 130x 2x 2x 2x 1248x 1248x 14x 14x 1234x 1248x 1230x 1216x 1216x 14x 1118x 10x 10x 8x 1118x 4x 4x 1230x 8x 8x 8x 2x 2x 1258x 1258x 1260x 1260x 204x 1140x 206x 206x 206x     206x 204x 204x 204x 2x 2x 2x 2x 2x 2x 202x 202x 202x 202x 202x 5660x   5660x 5660x 5660x 16x 2x 2x 2x 5660x   5644x 2x 2x 5660x 5660x 202x  
/** @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';
 
/**
 * @typedef {{
 *   code: MagicString;
 *   dev: boolean;
 *   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,
		dev: options.dev,
		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 (options.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, next }) {
		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 (!state.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) {
				// `: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.SimpleSelector} selector */
		function remove_global_pseudo_class(selector) {
			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) {
				remove_global_pseudo_class(relative_selector.selectors[0]);
				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() 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);
					}
				}
 
				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') {
			return false; // TODO
		}
	}
 
	return true;
}
 
/** @param {Css.Rule} rule */
function is_used(rule) {
	for (const selector of rule.prelude.children) {
		if (selector.metadata.used) return true;
	}
 
	for (const child of rule.block.children) {
		if (child.type === 'Rule' && is_used(child)) return true;
 
		if (child.type === 'Atrule') {
			return true; // TODO
		}
	}
 
	return false;
}
 
/**
 *
 * @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;
			}
		}
	}
}