Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                		<header>
			<h1>View Transitions Demo: Accordion</h1>
			<div class="box">
				<p>This demo is a POC for <a href="https://github.com/w3c/csswg-drafts/issues/8320" target="_top">w3c/csswg-drafts#8320</a> and <a href="https://github.com/w3c/csswg-drafts/issues/9141" target="_top">w3c/csswg-drafts#9141</a>.<br>It contains a (rough) polyfill for CSS <code>attr()</code> and <code>ident()</code></p>
				<p>Try this demo in Chrome Canary for best effect as it relies on <code>view-transition-class</code>.</p>
				<p>Original demo for comparison: <a href="https://codepen.io/bramus/pen/xxmozvN" target="_top">https://codepen.io/bramus/pen/xxmozvN</a></p>
			</div>
		</header>
		<main>
			<div class="accordion">
				<div class="item" id="item-1">
					<input type="radio" name="accordion" value="unblur" id="unblur" checked />
					<label for="unblur">
						<span class="title">Photo Unblur fixes your pics, even the old ones.</span>
						<span class="marker">&rsaquo;</span>
					</label>
					<div>
						<h2>Photo Unblur fixes your pics, even the old ones.</h2>
						<p>With a tap, sharpen and brighten picture-imperfect photos – even ones from non-Pixel phones. #FixedOnPixel</p>
					</div>
				</div>
				<div class="item" id="item-2">
					<input type="radio" name="accordion" value="magic-eraser" id="magic-eraser" />
					<label for="magic-eraser">
						<span class="title">Easily remove distractions in photos with Magic Eraser.</span>
						<span class="marker">&rsaquo;</span>
					</label>
					<div>
						<h2>Easily remove distractions in photos with Magic Eraser.</h2>
						<p>Make unwanted objects or photobombers disappear. Or change the color and brightness so an object blends right in. #FixedOnPixel</p>
					</div>
				</div>
				<div class="item" id="item-3">
					<input type="radio" name="accordion" value="night-sight" id="night-sight" />
					<label for="night-sight">
						<span class="title">Details pop out in the dark with Night Sight.</span>
						<span class="marker">&rsaquo;</span>
					</label>
					<div>
						<h2>Details pop out in the dark with Night Sight.</h2>
						<p>Now it’s easier to create rich, vibrant photos when it’s dark – city lights, portraits in low light, and starry skies with astrophotography.</p>
					</div>
				</div>
				<div class="item" id="item-4">
					<input type="radio" name="accordion" value="super-res-zoom" id="super-res-zoom" />
					<label for="super-res-zoom">
						<span class="title">Get amazing closeups with Super Res Zoom.</span>
						<span class="marker">&rsaquo;</span>
					</label>
					<div>
						<h2>Get amazing closeups with Super Res Zoom.</h2>
						<p>The Pixel 7a camera includes Super Res Zoom. So you can get up close without an extra telephoto lens.</p>
					</div>
				</div>
				<div class="item" id="item-5">
					<input type="radio" name="accordion" value="long-exposure" id="long-exposure" />
					<label for="long-exposure">
						<span class="title">Create energetic photos with Long Exposure.</span>
						<span class="marker">&rsaquo;</span>
					</label>
					<div>
						<h2>Create energetic photos with Long Exposure.</h2>
						<p>Add motion, texture, and artful blurs – including light trails – to waterfalls, crowds, city streets, and more. All without a tripod.</p>
					</div>
				</div>
			</div>
		</main>
		<footer>
			<p>Example URL: <a href="https://store.google.com/us/product/pixel_7a?hl=en-US">Pixel 7a – Google Store</a></p>
		</footer>
              
            
!

CSS

              
                @layer reset, layout, transitions;

body {
	background: white;
}

@layer transitions {
	:root {
		view-transition-name: none;
	}

	.item {
		--id: attr(id); /* Extract id from id attribute */

		view-transition-name: _auto; /* Using _auto because the engine currently disallows `auto` */
		view-transition-class: item;

		.marker {
			view-transition-name: _auto; /* Using _auto because the engine currently disallows `auto` */
			view-transition-class: marker;
		}
		&:has(input:checked) {
			& h2 {
				view-transition-name: ident("title-" var(--id)); /* Dynamically construct ident using --id */
				view-transition-class: title;
			}
		}
		&:not(.item:has(input:checked)) {
			& .title {
				view-transition-name: ident("title-" var(--id)); /* Dynamically construct ident using --id */
				view-transition-class: title;
			}
		}
	}

	@keyframes rotate-marker {
		from {
			rotate: 90deg;
		}
		to {
			rotate: 270deg;
			opacity: 0;
		}
	}
	::view-transition-group(*) {
		animation-duration: 0.5s;
	}
	::view-transition-group(.item) {
		overflow: hidden;
	}

	::view-transition-old(.marker):only-child {
		animation-name: rotate-marker;
	}
	::view-transition-new(.marker):only-child {
		animation-name: rotate-marker;
		animation-direction: reverse;
	}
}

@layer layout {
	@layer general {
		body {
			background: #efeae6;
			font-family: 'Google Sans', Roboto, Arial, sans-serif;
			padding-top: 3rem;
		}
		header,
		footer {
			text-align: center;
		}
		main {
			margin: 2em auto;
			width: 90%;
			max-width: 30em;
		}
		
		.box {
			border: 1px solid #a4a4a4;
			width: max-content;
			margin: 0 auto;
			padding: 1em;
			border-radius: 1em;
			background: rgb(255 255 125 / 0.25);
			
			> *:first-child { margin-top: 0; }
			> *:last-child { margin-bottom: 0; }
		}
		
		a {
			color: blue;
		}
	}
	@layer accordion {
		.accordion {
			display: grid;
			grid-auto-flow: row;
			gap: 0.5em;
			border-radius: 1em;
			overflow: hidden;
			font-size: 1.25em;
		}

		.item {
			background: #f8f6f2;

			display: flex;
			flex-direction: column;

			& input {
				position: absolute;
				opacity: 0;
			}

			& label {
				flex: 1;
				cursor: pointer;
				padding: 1em;

				display: flex;
				flex-direction: row;
				gap: 1em;
				justify-content: space-between;
			}

			.marker {
				display: grid;
				place-content: center;
				height: 1.5rem;
				aspect-ratio: 1;
				border-radius: 50%;
				background-color: #fff;
				color: #5f6368;

				font-weight: 700;
				font-size: 1.5em;
				line-height: 1;
				rotate: 90deg;
			}

			& div {
				padding: 1em;

				:first-child {
					margin-top: 0;
				}
				:last-child {
					margin-bottom: 0;
				}
			}
		}

		/* Show/Hide label/content based on input being checked or not */
		.item:has(input:checked) {
			& label {
				display: none;
			}
		}
		.item:not(.item:has(input:checked)) {
			& div {
				display: none;
			}
		}
	}
}

@layer reset {
	html,
	body {
		height: 100%;
		margin: 0;
		padding: 0;
	}
}
              
            
!

JS

              
                const randomBetween = (min, max) => {
  return Math.random() * (max - min) + min;
}

document.querySelectorAll('.item input').forEach(($input) => {
	// @note: we listen on click because that happens *before* a change event
	$input.addEventListener('click', async (e) => {
		if (!document.startViewTransition) return;

		e.preventDefault();

		const t = document.startViewTransition(() => {
			e.target.setAttribute('checked', 'checked'); // Needed to trigger the Polyfill’s MutationObserver
			e.target.checked = true; // Needed to actually update the checked input
		});

		await t.finished;
		console.log('done');
	});
});

class SelectorMatcher {
	static watchers = new Map();
	static matchedElements = new Map();
	static observer;
		
	static register({selector, onMatch, onUnmatch}) {
		const watchers = this.watchers.has(selector) ? this.watchers.get(selector) : [];
		
		watchers.push({
			selector,
			onMatch,
			onUnmatch,
			currentMatches: [],
		});
		
		this.watchers.set(selector, watchers);
	}
	
	static processWatchers = (selector, watchers) => {
		const $newMatches = Array.from(document.querySelectorAll(selector));
		const $oldMatches = this.matchedElements.has(selector) ? this.matchedElements.get(selector) : [];

		// Process unmatches
		for (const $oldMatch of $oldMatches) {
			if (!$newMatches.includes($oldMatch)) {
				for (const watcher of watchers) {
					watcher.onUnmatch($oldMatch);
				}
			}
		}

		// Process matches
		for (const $newMatch of $newMatches) {
			if (!$oldMatches.includes($newMatch)) {
				for (const watcher of watchers) {
					watcher.onMatch($newMatch);
				}
			}
		}

		this.matchedElements.set(selector, $newMatches);
	};
	
	static watch() {
		this.observer = new MutationObserver((mutationList, observer) => {
			for (const mutation of mutationList) {
				// console.log(mutation);
				for (const [selector, watchersForSelector] of this.watchers.entries()) {
					this.processWatchers(selector, watchersForSelector);
				}
			}
		});
		
		this.observer.observe(document.documentElement, { attributes: true, childList: true, subtree: true });
		
		// @TODO: Watch clicks, hovers, focus, etc.
	}
	
	static unwatch() {
		this.observer?.disconnect();
	}
};

class StyleSheetProcessor {
	static properties = [];
	static valueRewriter = null;

	static process = (styleSheets, properties, valueRewriter) => {
		this.properties = properties;
		this.valueRewriter = valueRewriter;
		for (const styleSheet of styleSheets) {
			this.processStyleSheet(styleSheet);
		}
	}
	
	static processStyleSheet = (styleSheet) => {
		this.processCSSRules(styleSheet.cssRules);
	};

	static processCSSRules = (cssRules) => {
		if (cssRules) {
			for (const cssRule of cssRules) {
				this.processCSSRule(cssRule);
			}
		}
	};

	static processCSSRule = (cssRule) => {
		// Process Style Decelaration
		this.processCSSStyle(cssRule.styleMap, cssRule.style);

		// Process Nested Rules
		this.processCSSRules(cssRule.cssRules);
	};
	
	static processCSSStyle = (stylePropertyMap, styleDeclaration) => {
		if (stylePropertyMap) {
			for (const [prop, val] of stylePropertyMap) {
				if (this.properties.includes(prop)) {
										
					// Extract (flattened) selector from rule
					const selector = this.resolveSelector(styleDeclaration.parentRule);
					
					const createMatcher = (property, value) => {
						return ($element) => {
							$element.style.setProperty(
								property,
								this.valueRewriter(
									value,
									$element
								)
							);
						}
					};
					
					const createUnmatcher = (property) => {
						return ($element) => {
							$element.style.setProperty(property, '');
						}
					};
					
					// Register a SelectorMatcher watcher
					SelectorMatcher.register({
						selector,
						onMatch: createMatcher(prop, styleDeclaration.getPropertyValue(prop)),
						onUnmatch: createUnmatcher(prop),
					});
										
					// Remove the original declaration from the stylePropertyMap
					stylePropertyMap.delete(prop);
				}
			}
		}
	};
	
	static resolveSelector = (cssRule) => {
		let selector = '';
		
		const selectorTexts = [];
		do {
			if (cssRule.selectorText) {
				selectorTexts.unshift(cssRule.selectorText);
			}
			cssRule = cssRule.parentRule;
		} while (cssRule);

		for (let selectorText of selectorTexts) {
			// This is not needed, as CSSOM already prepends the & for nested selectors
			// if (!selectorText.includes('&')) {
			// 	selectorText = `& ${selectorText}`;
			// }
			selector = selectorText.replaceAll('&', `:is(${selector})`);
		}
		
		return selector;
	};
}
console.clear();
const polyfill = () => {
	// Properties to check
	const properties = ['--id', 'view-transition-name'];
	
	// Core of the polyfill that can rewrite CSS property values
	// @TODO: This needs proper value parsing, but hey … it’s a POC
	const valueRewriter = (value, $element) => {
		
		// auto
		const isAuto = value.trim() === '_auto';
		if (isAuto) {
			const ident = `vt-${randomBetween(0, 32768).toFixed()}-${randomBetween(0, 32768).toFixed()}`;
			return ident;
		}

		// attr()
		const isAttr = /attr\((.*)\)/gm;
		if (value.match(isAttr)) {
			const attribute = isAttr.exec(value)[1];
			if (['nonce'].includes(attribute)) {
				throw new Error(`Reading the attribute “${attribute}” using attr() is not allowed`);
			}
			return $element.getAttribute(attribute);
		}
		
		// ident()
		const isIdent = /ident\((.*)\)/gm;
		if (value.match(isIdent)) {
			let ident = isIdent.exec(value)[1];
			
			// Replace all Custom Props first
			const customProps = Array.from(ident.matchAll(/var\((.*?)\)/g));
			for (const customProp of customProps) {			
				ident = ident.replaceAll(customProp[0], getComputedStyle($element).getPropertyValue(customProp[1]));
			}
			
			// TODO: One can use attr() here as well
			
			// Glue it all together by removing quotes and whitespace
			ident = ident.replaceAll(' ', '').replaceAll('"', '').replaceAll('\'', '');

			return ident;
		}
		
		// Any other value
		return value;
	};
	
	StyleSheetProcessor.process(document.styleSheets, properties, valueRewriter);
	SelectorMatcher.watch();
}

console.clear();
polyfill();
              
            
!
999px

Console