<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<atom:link href="https://www.component-odyssey.com/rss.xml" rel="self" type="application/rss+xml" />
<title>Component Odyssey Articles</title>
<link>https://www.component-odyssey.com</link>
<description>Learn how to easily build, manage, and distribute your component library in an ever-increasing
complex web development landscape</description>
<language>en</language>
<item>
<guid>https://www.component-odyssey.com/articles/15-my-development-environment-setup</guid>
<title>Setting up my Development Environment</title>
<link>https://www.component-odyssey.com/articles/15-my-development-environment-setup</link>
<description>Whenever I get a new MacBook, I take joy in setting in up from scratch. Over the years, I’ve become particular about how I like my machine to behave, from trusted applications, to handy shortcuts.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-1534lza">Every few years I get a shiny new MacBook. Either I’ve upgraded my trusty MacBook Pro for a newer, faster, shinier model, or I’ve started at a company that supplies me with my dedicated work machine.</p> <p data-svelte-h="svelte-1p1qv12">I know folks who like to clone a customised Linux distro, or restore from a backup, but I take joy in setting up a machine manually from a clean slate. Over the years, I’ve become particular about how I like my machine setup, from which trusted applications to install, through to personalised handy shortcuts I can’t live without. On the flipside, I get to shed the cruft that’s managed to squat rent-free on my old machine.</p> <h2 data-svelte-h="svelte-190rsku">Computer setup</h2> <p data-svelte-h="svelte-1e7vtpe">Let’s start with the settings built in to the MacBook. The focus here is to improve security, privacy, and reduce distractions.</p> <ul data-svelte-h="svelte-4sh9uw"><li>Encrypt device</li> <li>Enable firewall</li> <li>Turn off advertising and analytics settings</li> <li>Disable all notifications</li> <li>Remove unnecessary icons from dock</li> <li>Remove unnecessary items from the menu bar</li> <li>Automatically hide dock</li></ul> <p data-svelte-h="svelte-1vidp9l">There are also a few personal preferences I like to set:</p> <ul data-svelte-h="svelte-gbb410"><li>Max out key repeat speed</li> <li>Use fn keys as standard keys</li> <li>Turn off all “smart” keyboard features</li> <li>Turn off automatic brightness adjustment when charging</li> <li>Always show scrollbars</li></ul> <h2 data-svelte-h="svelte-4ahosz">Software</h2> <p data-svelte-h="svelte-1u246xs">Here, I take stock of all the software I use on a regular basis as someone who uses a device both for personal enjoyment, but also for web development.</p> <p data-svelte-h="svelte-8k8q0j">These are software I install regardless of how I expect to use my machine on a day-to-day basis. Programs like Slack won’t make the list because it’s likely, but not guaranteed, to be a work requirement.</p> <h3 data-svelte-h="svelte-hxf1gt">Browsers</h3> <p data-svelte-h="svelte-37ztiq">It’s a common joke, that Safari’s only job is to install a better browser. In my case, it’s four better browsers.</p> <ul data-svelte-h="svelte-rfc1m6"><li>Arc</li> <li>Chrome</li> <li>Firefox</li> <li><a href="https://polypane.app/" rel>Polypane</a></li></ul> <h3 data-svelte-h="svelte-1yhmezb">Productivity/Utilities</h3> <ul data-svelte-h="svelte-ee2yux"><li>Notion</li> <li>TickTick</li> <li>Loom</li> <li>BetterDisplay</li> <li>Screen Studio</li> <li>Maccy (Clipboard manaager)</li> <li>Magnet (Window manager)</li> <li>Elgato Control Center</li> <li>Elgato Camera Hub</li></ul> <h3 data-svelte-h="svelte-1v36q6f">Web Development</h3> <ul data-svelte-h="svelte-115jc8o"><li>Docker</li> <li>iTerm2<ul><li>Set up Natural Text Editing Keymaps</li> <li><a href="https://ohmyz.sh/" rel>Add oh-my-zsh</a></li> <li><a href="https://gist.github.com/n1snt/454b879b8f0b7995740ae04c5fb5b7df" rel>Add autocomplete plugins</a></li> <li><a href="https://github.com/junegunn/fzf" rel>Add fzf</a></li></ul></li> <li>VSCode/Cursor<ul><li><a href="https://stackoverflow.com/questions/39972335/how-do-i-press-and-hold-a-key-and-have-it-repeat-in-vscode" rel>disable Apple press hold</a></li> <li>Sync VSCode settings</li></ul></li> <li>Homebrew<ul><li>Node</li></ul></li> <li>Figma</li></ul> <h2 data-svelte-h="svelte-91s2zm">Scripts and Configurations</h2> <ul data-svelte-h="svelte-1yoee6n"><li>Setup git shortcuts</li></ul> <pre class="language-bash"><!-- HTML_TAG_START --><code class="language-bash"><span class="token assign-left variable">alias.co</span><span class="token operator">=</span>checkout
<span class="token assign-left variable">alias.ci</span><span class="token operator">=</span>commit
<span class="token assign-left variable">alias.br</span><span class="token operator">=</span>branch
<span class="token assign-left variable">alias.st</span><span class="token operator">=</span>status
<span class="token assign-left variable">alias.po</span><span class="token operator">=</span>push <span class="token parameter variable">-u</span> origin HEAD
<span class="token assign-left variable">alias.rect</span><span class="token operator">=</span>for-each-ref <span class="token parameter variable">--sort</span><span class="token operator">=</span>committerdate <span class="token parameter variable">--count</span><span class="token operator">=</span><span class="token number">10</span> <span class="token parameter variable">--format</span><span class="token operator">=</span><span class="token string">'%~(refname:short)'</span> refs/heads/
<span class="token assign-left variable">alias.cb</span><span class="token operator">=</span><span class="token operator">!</span>sh <span class="token parameter variable">-c</span> <span class="token string">'git co $(git rect | fzf)'</span></code><!-- HTML_TAG_END --></pre> <h2 data-svelte-h="svelte-kw6zbk">Browser Extensions</h2> <ul data-svelte-h="svelte-35u0rf"><li>Bitwarden</li> <li><a href="https://chromewebstore.google.com/detail/web-developer/bfbameneiokkgbdmiekhjnmfkcnldhhm?pli=1" rel>Web Developer</a></li> <li><a href="https://chromewebstore.google.com/detail/enhancer-for-youtube/ponfpcnoihfmfllpaingbgckeeldkhle?hl=en-GB" rel>Enhancer for YouTube</a></li> <li><a href="https://chromewebstore.google.com/detail/read-aloud-a-text-to-spee/hdhinadidafjejdhmfkjgnolgimiaplp" rel>Read Aloud: Text to Speech</a></li></ul>
]]></content>
<pubDate>Mon, 11 Nov 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/14-improving-no-spoilers</guid>
<title>Making no-spoilers more accessible</title>
<link>https://www.component-odyssey.com/articles/14-improving-no-spoilers</link>
<description>no-spoilers was sorely lacking with respect to accessibility. Thanks to the lessons learned from Scott's article, I was able to make some much needed improvements.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-1i0iz4q">When building Component Odyssey, I needed a mechanism to prevent students from being spoilt by the answers of exercises. I built <code>no-spoilers</code>, a web component that blurs the spoiler content and includes a button to toggle the visibility of said spoiler.</p> <video controls loop data-svelte-h="svelte-1839zau"><source src="https://component-odyssey.com/images/articles/14-improving-no-spoilers/no-spoilers.mp4" type="video/mp4"></video> <p data-svelte-h="svelte-d2m7gg">Admittedly, I had rushed the implementation which led to a subpar experience for assistive technology users.</p> <p data-svelte-h="svelte-deefgs"><a href="https://www.scottohara.me/blog/2024/08/22/spoiler.html" rel>Scott O’Hara’s recent blogpost pressured me to get off my butt</a> and make some much needed improvements to the component. I’d recommend you read the article for yourself, it’s super interesting and he deserves full credit for the changes I made to <code>no-spoilers</code>.</p> <p data-svelte-h="svelte-127ey91">You can find a summary of the changes I made to <code>no-spoilers</code> but only after you promise me that you’ve read Scott’s article:</p> <no-spoilers button-text="I promise I've read Scott's article" class="svelte-81xwzv"><details><ul data-svelte-h="svelte-110db6"><li>Improving the semantics of the spoiler container</li> <li>Using aria attributes to communicate the state of the button to assistive technologies</li> <li>Making the “show spoilers” button togglable</li> <li>Preventing hidden content from being viewable by assistive technologies</li></ul></details> </no-spoilers> <p data-svelte-h="svelte-hm6m3p">If you decide to give the component a try and you find some issues, then please open up an issue on <a href="https://github.com/andrico1234/no-spoilers" rel>GitHub</a>.</p>
]]></content>
<pubDate>Fri, 13 Sep 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/tips/04-reducing-memory-consumption-using-event-delegation</guid>
<title>Reduce Your App’s Memory Consumption With Event Delegation</title>
<link>https://www.component-odyssey.com/tips/04-reducing-memory-consumption-using-event-delegation</link>
<description>Learn how to improve you're site's performance and memory consumption with event delegation.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-qxt988">Adding event listeners to DOM nodes can incur performance and memory costs. You might not notice it at first, but your users on low-powered devices will, especially if you add and remove dozens (or even hundreds) of event listeners.</p> <h2 data-svelte-h="svelte-fi4xlo">The cost of adding event</h2> <p data-svelte-h="svelte-1lb9tyz">In the following snippet, I’m querying a single input element and adding an event listener to it.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/04-reducing-memory-consumption-using-event-delegation/single-event-listener.png" alt="JavaScript of adding an event listener to an input"></div> </p> <p data-svelte-h="svelte-3orthu">Let’s have a look at the memory consumption for one input.</p> <p data-svelte-h="svelte-934ena">The browser stores the event name, reference to the function, and reference to the DOM node in memory. For the most simple of event listeners. The two properties worth noting are “Shallow Size” and “Retained Size”, and the number of event listeners.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/04-reducing-memory-consumption-using-event-delegation/memory-consumption-low.png" alt="9 event listeners on the page, 648 bytes shallow size, 1504 reatined size"></div> </p> <p data-svelte-h="svelte-fijg5k">In this case, there are 9 event listeners set on the page (the browser automatically applies a few, and your extensions may add additional ones too).</p> <p data-svelte-h="svelte-2j3px4">Let’s break down what’s going on above:</p> <p data-svelte-h="svelte-obavcs"><em>Shallow Size</em> - The size of the object that’s stored in memory.</p> <p data-svelte-h="svelte-eqhi9u"><em>Retained Size</em> - The total amount of memory used by the object, and any objects that reference it. This number indicates how much memory can be freed if the object is deleted</p> <p data-svelte-h="svelte-lqjfs4">The more event listeners you use, the more memory your app will require. The costs start off small, but can explode if you’re using heavy frameworks and you’re not optimising your JavaScript.</p> <p data-svelte-h="svelte-mo5nkg">Let’s look at an example. If you’re building the table of contents for a video course, you might decide to have a checkmark next to a video’s title, to let a user mark the video as watched. The markup could look like this:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/04-reducing-memory-consumption-using-event-delegation/1000inputs.png" alt="HTML showing the markup of multiple checkboxes"></div> </p> <p data-svelte-h="svelte-1bkujfp">You would then query the list of inputs and add an event listener to each and every one.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/04-reducing-memory-consumption-using-event-delegation/multiple-event-listeners.png" alt="JavaScript iterating over all the inputs and adding an event listener to each one"></div> </p> <p data-svelte-h="svelte-dcl62o">You can see how this affects memory consumption in the browser:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/04-reducing-memory-consumption-using-event-delegation/memory-consumption-high.png" alt="1008 total event listeners on the page, 72kb in shallow size, 113kb in retained size"></div> </p> <p data-svelte-h="svelte-vl54er">The browser needs to keep track of 1000 event listeners, which increases the shallow size by over 10,000%.</p> <p data-svelte-h="svelte-xsb969">I know that this is a contrived example, but you can see how things can escalate for a complex web application. Fortunately, there’s a straightforward optimisation you can make to massively reduce the memory consumption of your event listeners, <em>event delegation</em>.</p> <h2 data-svelte-h="svelte-vmbfuc">Event Delegation</h2> <p data-svelte-h="svelte-1y05tg">Instead of adding the same event listener to every input element, you can add a single event listener to a common ancestor.</p> <p data-svelte-h="svelte-a40plu">This is when you add a single event listener to a common ancestor instead of on all the child elements. Inside of the event handler, you can check to see whether the target element was a button, and if so, perform the same logic you would have otherwise done.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/04-reducing-memory-consumption-using-event-delegation/event-listener-on-container.png" alt="Instead of adding an event listener to each input, instead a single event listener is added to the container element"></div> </p> <p data-svelte-h="svelte-zhpvm0">Let’s take a look at the memory usage now</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/04-reducing-memory-consumption-using-event-delegation/memory-consumption-after.png" alt="9 event listeners on the page, 648 bytes shallow size, 1504 reatined size"></div> </p> <p data-svelte-h="svelte-p4yjhl">The browser no longer keeps track of 1000 event listeners in memory.</p> <p data-svelte-h="svelte-1gegm5m">Even the the memory consumption in this example was small, it’s still important to be mindful especially when you’re building heavier applications in a more JavaScript-intensive framework.</p>
]]></content>
<pubDate>Wed, 28 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/13-improving-performance-by-changing-two-lines-of-css</guid>
<title>The Two Lines of CSS That Tanked Performance (120fps to 40fps)</title>
<link>https://www.component-odyssey.com/articles/13-improving-performance-by-changing-two-lines-of-css</link>
<description>Learn WCs felt so sluggish on Firefox that I disabled the background animation for all users. Turns out, fixing it took changing two lines of CSS.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-1l2zcmf">I recently released <a href="https://learn-wcs.com/" rel>Learn WCs</a>. If you’ve seen it, you’ve likely noticed the animation in the background, where the coloured circles move diagonally across the screen. It looks like this:</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/a4ed32251e3b4963c1604bee45e123b1/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2Fa4ed32251e3b4963c1604bee45e123b1%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="Learn WCs in Chrome is very smooth. No dip in performance when using the site." loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-1yxithc">It works nicely on Chrome and Safari, but I noticed a severe drop in performance on Firefox.</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/4855432cd2aea8ccf232fcd3682db1fb/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F4855432cd2aea8ccf232fcd3682db1fb%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="When using Learn WCs in Firefox, the FPS counter consistently drops around the 40-60 mark. It feels very janky." loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-1sp2umu">You might not be able to see it much in the video, but the FPS drops signficially. As a user, you can really feel this drop in performance. It was so bad, that I straight up disabled this animation in Firefox.</p> <h2 data-svelte-h="svelte-1rhzmnq">How does the animation work?</h2> <p data-svelte-h="svelte-1c5p44h">The animation is built using two divs. The outer div is the first child of <code>body</code> element.</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>background-mask<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>background-gradient<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token comment">&lt;!-- Rest of content --></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-vq5s2j">The <code>.background-gradient</code> element is responsible for creating a gradient that spans the entire width and height of its parent container. Like so:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/13-improving-performance-by-changing-two-lines-of-css/background-no-mask.png" alt="The background with no mask is just a gradient that goes from purple to red to orange."></div> </p> <p data-svelte-h="svelte-12rzgvi">The outer <code>.background-mask</code> is responsible for two things:</p> <ol data-svelte-h="svelte-14qyqvc"><li>Setting the position to <code>fixed</code> to make the container fill the entire dimensions of the viewport.</li> <li>Creating a dotted mask over the gradient</li></ol> <p data-svelte-h="svelte-1t1zlki">The latter steps ensures the colour of the dots is the colour of the gradient directly underneath it:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/13-improving-performance-by-changing-two-lines-of-css/background-with-mask.png" alt="The background with mask."></div> </p> <p data-svelte-h="svelte-107q7bt">Finally, I’m animating the mask by adjusting its position over time. It repeats indefinitely, giving it that cool diagonally flowing motion.</p> <p data-svelte-h="svelte-1brncvd">Here’s the CSS for everything I described above:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.background-mask</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--mask-size</span><span class="token punctuation">:</span> 24px<span class="token punctuation">;</span>
	<span class="token comment">/* Position Styles */</span>
	<span class="token property">position</span><span class="token punctuation">:</span> fixed<span class="token punctuation">;</span>
	<span class="token property">width</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
	<span class="token property">height</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
	<span class="token property">z-index</span><span class="token punctuation">:</span> -1<span class="token punctuation">;</span>
	<span class="token comment">/* Mask Styles */</span>
	<span class="token property">mask-image</span><span class="token punctuation">:</span> <span class="token function">radial-gradient</span><span class="token punctuation">(</span>black 2px<span class="token punctuation">,</span> transparent 2px<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">mask-size</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span> <span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">mask-position</span><span class="token punctuation">:</span> 0px 0px<span class="token punctuation">;</span>
	<span class="token property">animation</span><span class="token punctuation">:</span> mask-move 3s infinite linear<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.background-gradient</span> <span class="token punctuation">&#123;</span>
	<span class="token property">background</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--red<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">background-image</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--gradient<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">width</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
	<span class="token property">height</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token atrule"><span class="token rule">@keyframes</span> mask-move</span> <span class="token punctuation">&#123;</span>
	<span class="token selector">0%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">mask-position</span><span class="token punctuation">:</span> 0px 0px<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token selector">100%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">mask-position</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span> <span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<span class="token atrule"><span class="token rule">@media</span> <span class="token punctuation">(</span><span class="token property">prefers-reduced-motion</span><span class="token punctuation">:</span> reduce<span class="token punctuation">)</span></span> <span class="token punctuation">&#123;</span>
	<span class="token selector">.hero-background-mask</span> <span class="token punctuation">&#123;</span>
		<span class="token property">animation</span><span class="token punctuation">:</span> none<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <aside data-svelte-h="svelte-1qyyawi"><p>If you’re interested in learning more about masks in CSS, then I can recommend this comprehensive post by <a href="https://ishadeed.com/article/css-masking/" rel>Ahmad Shadeed</a></p></aside> <h2 data-svelte-h="svelte-13twl6j">What’s causing this drop in performance?</h2> <p data-svelte-h="svelte-wi3bao">Not all CSS properties animate equally. Without going too much into how the browser renders HTML to the page (<a href="https://component-odyssey.com/tips/02-how-does-the-browser-render-html" rel>though I’ve outlined it here</a>), there are a handful of stages it goes through. The three stages that we’re interested in are:</p> <ul data-svelte-h="svelte-10xgfkf"><li>Layout - When the browser calculates the size and positions of the elements on the page</li> <li>Paint - When the browser draws all the visual aspects of the page, like images, colors, shadows, etc</li> <li>Composite - When the browser layers the elements on top of one another in the correct order</li></ul> <p data-svelte-h="svelte-q4ik88">The order of the pipeline looks like this:</p> <p data-svelte-h="svelte-1ll14b3">Layout → Paint → Composite</p> <p data-svelte-h="svelte-r8xj0h">The layout and paint processes can be CPU-intensive, so it’s important to try and reduce the amount of times your CSS triggers the stages in the pipeline. The browser helps in some part by optimising performance for certain properties, some skip entire stages of the rendering pipeline and others can leverage <em>hardware acceleration</em> to move computation from the CPU to the GPU.</p> <p data-svelte-h="svelte-1x27ufg">Animating certain properties, like <code>translate</code> and <code>opacity</code> , can avoid triggering a layout and use hardware acceleration.</p> <p data-svelte-h="svelte-orx6qh">Sadly, this is not the case when animating <code>mask-position</code>. I took a look at Chrome and saw that the paint count for the background div was increasing on every frame. After a few seconds it had already triggered a paint over 1,000 times.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/13-improving-performance-by-changing-two-lines-of-css/paint-count-bad.png" alt="Paint count for the background div layer is 7941."></div> </p> <p data-svelte-h="svelte-d04t38">Even with this high paint count, the animation on Chrome felt smooth. However, it felt super janky on Firefox. Annoyingly, I couldn‘t find a way to measure the paint count on Firefox, so any assumptions I make about Firefox’s poor performance is purely conjecture.</p> <p data-svelte-h="svelte-fbm553">I did noticed that the performance is fine for small devices, but gets worse as the size of the screen increases. My working theory is that Firefox doesn’t batch the layout triggers for each of the 24x24 masks, causing the FPS to tank when more masks are present. Again, I might be completely wrong here.</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/b928529e924ae288cc2c5012d6c3f53e/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2Fb928529e924ae288cc2c5012d6c3f53e%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="The performance on Firefox is 100+ FPS on mobile device sizes, but noticeably degrades as the width of the viewport increases." loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <h2 data-svelte-h="svelte-1938srs">How did I fix this?</h2> <p data-svelte-h="svelte-1ru4mhu">Instead of animating badly optimised CSS properties like <code>mask-position</code> , I needed to lean on the more performant properties, like <code>translate</code>.</p> <p data-svelte-h="svelte-uwe1bn">The solution wasn’t to move the masks by 24px, but to instead move the entire background element using the <code>translate</code> property.</p> <p data-svelte-h="svelte-1p9juny">From an abstract standpoint, this is how the animation works:</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/29da1dce24d683dad8770c38fe3a9aea/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F29da1dce24d683dad8770c38fe3a9aea%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="An animation outline showing the background starting -24px top and left, and slowly moving over to cover the entire viewport." loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-7eo3ae">Here’s the two line change in the CSS:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token comment">/* --mask-size = 24px */</span>
<span class="token atrule"><span class="token rule">@keyframes</span> mask-move</span> <span class="token punctuation">&#123;</span>
	<span class="token selector">0%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translate</span><span class="token punctuation">(</span><span class="token function">calc</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span> * -1<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token function">calc</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span> * -1<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token selector">100%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translate</span><span class="token punctuation">(</span>0px<span class="token punctuation">,</span> 0px<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1jv8zv9">The browser no longer animates the <code>mask-position</code>, which triggered a layout on each frame. Even though the background moves on each frame, <code>translate</code> doesn’t trigger a layout or a paint. You can see that the background div only paints twice, down from 1,000+ every minute.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/13-improving-performance-by-changing-two-lines-of-css/paint-count-good.png" alt="Paint count for the background div layer is 2."></div> </p> <p data-svelte-h="svelte-1v6rtjj">Eagle-eyed viewers will have spotted a problem. If you remember, the height and width of the background fills the viewport. Shifting the background left and up by 24px leaves us with this empty space in the viewport.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/13-improving-performance-by-changing-two-lines-of-css/empty-gap.png" alt="At the start of the animation the background doesn't cover the far right and far bottom of the viewport."></div> </p> <p data-svelte-h="svelte-8aqh4p">Solving it is as simple as adding the mask size to the width and height of the container:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.background-mask</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--mask-size</span><span class="token punctuation">:</span> 24px<span class="token punctuation">;</span>
	<span class="token property">width</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span>100% + <span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">height</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span>100% + <span class="token function">var</span><span class="token punctuation">(</span>--mask-size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-wd7bzm">Let’s take a look again in Firefox:</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/546db812758b1f932240762d854cf330/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F546db812758b1f932240762d854cf330%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="Performance in Firefox has improved with FPS being consistently over 100." loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-zj3ki5">It may not be a perfect solution, but it’s always a little satisfying pulling off a fun <em>smoke and mirrors</em> CSS trick.</p>
]]></content>
<pubDate>Thu, 22 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/12-improving-the-screen-reader-experience-for-learn-wcs</guid>
<title>Improving the Screen Reader Experience for Learn WCs</title>
<link>https://www.component-odyssey.com/articles/12-improving-the-screen-reader-experience-for-learn-wcs</link>
<description>I refactored markup, wrangled with browser quirks, and hid elements all in the hopes of improving the screen reader experience</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-ya342l">A few weeks back I released a site called <a href="https://learn-wcs.com/" rel>Learn WCs</a>. It’s a free and fun interactive roadmap for learning web components.</p> <p data-svelte-h="svelte-vibwbx">As most web developers will understand, there are infinite possible environments within which a site can be used. If you were to look at all the ways every single user used your site, you’d see:</p> <ul data-svelte-h="svelte-1mgk3vo"><li>Different browsers</li> <li>Operating systems</li> <li>Input modalities</li> <li>Device power</li> <li>Screen sizes</li> <li>… And more!</li></ul> <p data-svelte-h="svelte-1xngarb">It’s impossible to test every single possibility. Even as a single developer building a side project, I still try to accommodate a wide range of these possibilities.</p> <p data-svelte-h="svelte-12j03lp">This includes testing with a screen reader to ensure that users with low/no vision can navigate around the site.</p> <aside data-svelte-h="svelte-1hny70i">A screen reader is a form of assistive technology that reads out the screen’s contents. It’s often (but not always), used by those hard of sight to navigate the web.</aside> <p data-svelte-h="svelte-3wokih">During testing, I noticed that the screen reader experience was sub-optimal:</p> <ul data-svelte-h="svelte-140gmjl"><li>Some elements were not being read out correctly.</li> <li>Purely presentational elements were being read out.</li> <li>Forms weren’t communicating their state clearly</li></ul> <p data-svelte-h="svelte-1szurtm">Improving the experience required making a variety of different changes. Some were noticeable changes in the site’s markup, others involved adding visually hidden elements for screen readers, and others were workarounds for small browser quirks.</p> <p data-svelte-h="svelte-mixgtc">This article summarises my changes to Learn WCs site to improve the screen reader experience.</p> <h2 data-svelte-h="svelte-8mofzs">A brief disclaimer</h2> <p data-svelte-h="svelte-1u2d7go">I’m testing with VoiceOver on a MacBook Pro. Like browsers, different screen readers have subtle differences in their behaviour. Ensuring compatibility with different screen readers means becoming familiar with and testing with them. I don’t have the resources to test with other popular screen readers like JAWS and NVDA, so to ensure compatibility between different screen readers, I’ve done my best to adhere to the ARIA spec.</p> <p data-svelte-h="svelte-q3xoot">Across my career, I’ve had the opportunity to learn from screen reader users. I’ve learnt that there’s no <em>one way</em> to use a screen reader, every user behaves differently. The improvements outlined in this article may not be perfect but result in a better experience. If you’re building production applications, it’s important to get feedback from a wide range of your users.</p> <p data-svelte-h="svelte-1tyjc61">Let’s dive in!</p> <h2 data-svelte-h="svelte-1ir70it">Better alternative content for screen readers</h2> <p data-svelte-h="svelte-2qd1vy">In Learn WCs, I went for a striking <em>Shibuya Punk</em> aesthetic, inspired by games like Persona and Jet Set Radio. In the hero, I have the top-level heading, that looks like this:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/12-improving-the-screen-reader-experience-for-learn-wcs/hero.jpg" alt="Learn to build components that work anywhere. A free roadmap for learning web components."></div> </p> <p data-svelte-h="svelte-rqh4z0">Providing a background to some characters in the title is done by wrapping them in a span, and adjusting the styles. This is what the markup looks like:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>
	Learn to B<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>u<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>ild<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>br</span> <span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>C<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>omp<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>o<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>nents<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>br</span> <span class="token punctuation">/></span></span>
	Th<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>a<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>t Wo<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>r<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>k Anywhere
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1rr0gpr">It’s not clean, but it’s something I could live with if it wasn’t for how it’s interpreted by screen readers. Have a listen to this:</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/81aa32231c2b36eeea4465f288c97ed0/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F81aa32231c2b36eeea4465f288c97ed0%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="A screen reader is reading out the title, but with big pauses between each letter" loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-1i90d6a">VoiceOver adds small pauses at the start and end of each span, which makes it difficult to discern what it’s saying.</p> <p data-svelte-h="svelte-5exhr8">Resolving this requires two changes to the markup:</p> <ol data-svelte-h="svelte-14pvl34"><li>A visually hidden new element that contains the pure, unadulterated title</li> <li>An <code>aria-hidden</code> attribute on the existing title</li></ol> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>visually-hidden<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> Learn to Build Components That Work Anywhere <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">aria-hidden</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>true<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		Learn to B<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>u<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>ild<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>br</span> <span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>C<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>omp<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>o<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>nents<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>br</span> <span class="token punctuation">/></span></span>
		Th<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>a<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>t Wo<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>span</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>alt-ff<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>r<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>k Anywhere
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>span</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <h3 data-svelte-h="svelte-bhgngs">The <code>visually-hidden</code> class</h3> <p data-svelte-h="svelte-nzn49t">Visually hidden is a CSS class that removes the content visually, but still ensures that it gets announced by screen readers. This is useful, because we can ensure that the heading of the page is understandable for screen reader users, while ensuring that the visual identity of the site isn’t impacted.</p> <p data-svelte-h="svelte-m0otwo">Check out <a href="https://www.scottohara.me/blog/2017/04/14/inclusively-hidden.html" rel>Scott O’Hara’s post</a> on the subject if you’d like to understand the <code>visually-hidden</code>class in more detail.</p> <h3 data-svelte-h="svelte-1bm95yj">The <code>aria-hidden</code> property</h3> <p data-svelte-h="svelte-1ehp3ig">You can also see that I’ve used <code>aria-hidden</code> on the original markup. This behaves the opposite to the <code>visually-hidden</code> class. This html attribute ensures that the content is still presented visually on the page but is ignored by screen readers.</p> <p data-svelte-h="svelte-gw1arg">In this scenario, we have the best of both worlds. <code>aria-hidden</code> should be used sparingly though, and we’ll see why a little later on in the article.</p> <p data-svelte-h="svelte-t5t6fa">After these changes, the screen reader reads out the title as expected:</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/005b1cdd21997d8e4ea514849a13d5b1/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F005b1cdd21997d8e4ea514849a13d5b1%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="The screen reader reading out the title of the page as expected." loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <h2 data-svelte-h="svelte-1eryqf1">Removing decorative content for screen readers</h2> <p data-svelte-h="svelte-1iaumzi">Just under the hero of the site is a marquee. It has a little animation on scroll, and is used to reinforce the idea that the web components you build will work in any frontend framework.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/12-improving-the-screen-reader-experience-for-learn-wcs/marquee.jpg" alt="A marquee element with the words react, svelte, vue, and angular inside of it"></div> </p> <p data-svelte-h="svelte-1jvaxia">With that said, it is a purely decorative element, and doesn’t enhance the core experience in any way. In fact, for screen readers, the announcement of “react”, “svelte”, “vue”, and “angular” may even seem unusual.</p> <p data-svelte-h="svelte-ii0io0">Applying an aria-hidden on the marquee may not be necessary depending on who you ask. I decided to hide it based on the suggestions provided in the <a href="https://www.w3.org/TR/wai-aria-1.2/#aria-hidden" rel>aria specifications</a></p> <blockquote data-svelte-h="svelte-au4dep"><p>Authors <strong><em>MAY</em></strong>, with caution, use aria-hidden to hide visibly rendered content from assistive technologies <em>only</em> if the act of hiding this content is intended to improve the experience for users of assistive technologies by removing redundant or extraneous content.</p></blockquote> <h2 data-svelte-h="svelte-1iymdnj">When <code>aria-hidden</code> isn’t the way to go…</h2> <p data-svelte-h="svelte-1tgk90q">If you’ve used Learn WCs, you may have noticed a little easter egg. If you complete all of the lessons for some sections, you’ll get a little sticker in the hero. To give you a clear look at all the stickers you’ve collected, you can hide the title elements.</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/a2a6cc4e8161a1601e24301e75d0d246/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2Fa2a6cc4e8161a1601e24301e75d0d246%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="Completing all the lessons for the 'Why Web Components' section adds a sticker to the top of the page. Clicking the 'eye' icon toggles the visibility of the titles which are partially obscuring the sticker" loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-v70jnb">Initially I planned to hide the button and the stickers from screen readers. My rationale was that since the stickers are decorative, and the button’s effect is purely decorative, then there’s no point in announcing either to screen readers.</p> <p data-svelte-h="svelte-1b03u15">This isn’t the way to go. Using <code>aria-hidden</code> on interactive elements is an <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-hidden" rel>accessibility violation</a>. This makes sense, as sighted users can also use screen readers (according to the <a href="https://webaim.org/projects/screenreadersurvey10/#disability" rel>Web AIM Screen Reader Survey</a>). On top of that, the ARIA specs say the following:</p> <blockquote data-svelte-h="svelte-ww5mc0"><p>Authors using aria-hidden to hide visible content from screen readers <strong><em>MUST</em></strong> ensure that identical or equivalent meaning and functionality is exposed to assistive technologies.</p></blockquote> <p data-svelte-h="svelte-1psvm5q">Honestly, I didn’t come up with a solution that felt appropriate. I reached out to the a11y Slack community, and quickly had some wonderful suggestions from members of the community.</p> <p data-svelte-h="svelte-niwr2r">I settled on <a href="https://mastodon.online/@backwardok" rel>Diane Ko</a>’s suggestion:</p> <ul data-svelte-h="svelte-7us5xk"><li>Ensure the button and the stickers are visible to screen readers</li> <li>Add a label to the button</li> <li>Add a description to the button, to better convey exactly what the effect is.</li></ul> <p data-svelte-h="svelte-1ya1k9p">I also used the <code>aria-pressed</code> attribute to indicate its current state to the accessibility API.</p> <p data-svelte-h="svelte-1uqz7tx">Here’s the behaviour in action:</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/6cfa15b6703a82734bedcb13990fa6d8/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F6cfa15b6703a82734bedcb13990fa6d8%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="The screen reader navigates the hero, toggles the visibility of the titles, where it can then inspect the stickers." loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <h2 data-svelte-h="svelte-108rlg5">Improving accessible names</h2> <p data-svelte-h="svelte-12kyw2p">I mentioned earlier how the Learn WCs site is going for a distinct visual identity. This extends to the link copy. You can see that every link has an emphatic and colloquial “LET’S GO!”. The proximity of the link to the card’s title makes it clear that the two are associated.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/12-improving-the-screen-reader-experience-for-learn-wcs/link-cards.jpg" alt="Top card element has title HTML Attributes with a link to the resource that says 'Lets Go!' The bottom card has the same layout but with the title Get, set, remove attributes in JS."></div> </p> <p data-svelte-h="svelte-bragut">It’s more difficult to communicate this relationship in a non-visual way. On top of that, in VoiceOver’s list view, the names of the links are all the same.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/12-improving-the-screen-reader-experience-for-learn-wcs/lets-go-before.jpg" alt="The VoiceOver list of links has 8 links on the page with the name 'Lets go!'"></div> </p> <p data-svelte-h="svelte-1dyws84">This is a quick fix. I added an aria label with the title of the article that the link directs to. One interesting thing to note, the ARIA specs recommend including the visual text within the label. This ensures that the link can be triggered through voice activation. Failure to do so is a <a href="https://www.w3.org/WAI/WCAG21/Understanding/label-in-name.html" rel>WCAG failure</a>.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/12-improving-the-screen-reader-experience-for-learn-wcs/lets-go-after.jpg" alt="The VoiceOver list of links has 8 links each with a clear and unique name, like 'Lets go - HTML Attributes' and 'Let's go - Get, set, remove attributes in JS'"></div> </p> <h2 data-svelte-h="svelte-esnefk">Semantic HTML over ARIA</h2> <p data-svelte-h="svelte-1icpn8v">The beef of the site is the curated list of resources. Click the section that you want to learn more about and the site displays a list of relevant articles. Initially this was implemented using button elements.</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/1b4929228a94f4290707276047a36998/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F1b4929228a94f4290707276047a36998%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="Navigating the menu using a keyboard" loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-4kf857">This works fine when interacting with a mouse or keyboard, but there are a few problems when used with a screen reader:</p> <ol data-svelte-h="svelte-1rdxwna"><li>Clicking a button doesn’t alert the screen reader that anything’s changed.</li> <li>There’s no clear link between the buttons on the left and the content on the right</li></ol> <h3 data-svelte-h="svelte-1nfsw2q">Screen reader feedback</h3> <p data-svelte-h="svelte-2oymes">When navigating between the dozen or so buttons, the screen reader needs to indicate which one is currently selected. Because they’re buttons, and their selected state is visualised using CSS, the information doesn’t get passed over to the accessibility APIs.</p> <p data-svelte-h="svelte-coj1z2">Initially, I had considered the following attributes to address this problem:</p> <ul data-svelte-h="svelte-1uoxznc"><li><code>aria-checked</code></li> <li><code>aria-selected</code></li> <li><code>aria-pressed</code></li></ul> <p data-svelte-h="svelte-13oficc">None are appropriate though. According to <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-checked#associated_roles" rel>MDN</a>, the <code>aria-checked</code> attribute is only supported for the following roles:</p> <ul data-svelte-h="svelte-1olox8f"><li>checkbox</li> <li>menuitemcheckbox</li> <li>menuitemradio</li> <li>option</li> <li>radio</li> <li>switch</li></ul> <p data-svelte-h="svelte-pq6ab8">The button doesn’t adhere to any of these roles. It’s also a good practice to avoid manually declaring and implementing roles when there are native HTML elements that can do the job (foreshadowing).</p> <p data-svelte-h="svelte-19xetar">After mulling it over, I decided to reimplement the list as a set of radio inputs instead. This makes much more sense. Since radio inputs have built-in state management. The screen reader announces which radio input item is currently selected.</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/53b3486f311a310c743c2c669bfb18f5/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F53b3486f311a310c743c2c669bfb18f5%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="Navigating the menu using a screen reader. The screen reader announces which radio item is currently selected" loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <p data-svelte-h="svelte-1m3ekpt">A shoutout to <a href="https://front-end.social/@joshtumath@mastodon.social" rel>Josh Tumath</a> for offering his feedback while I was evaluating a couple of different options.</p> <h3 data-svelte-h="svelte-4knayq">Linking the menu with the content</h3> <p data-svelte-h="svelte-1bwx5gu">After selecting an element, the screen reader doesn’t indicate a change to the list of resources on the right hand side. There should be a very clear link between pressing the button and perceiving the new content.</p> <p data-svelte-h="svelte-1muxkl1">I considered solving this using the following options:</p> <ol data-svelte-h="svelte-1xcyqqq"><li><code>aria-controls</code></li> <li><code>aria-live</code></li> <li><code>output</code> element</li> <li>Adding more verbose headings to the DOM structure</li></ol> <p data-svelte-h="svelte-b08jsx"><code>aria-controls</code> looked like a perfect choice for what I needed to do. According to <a href="https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-controls" rel>MDN</a>:</p> <blockquote data-svelte-h="svelte-gjgw9d"><p>The global <code>aria-controls</code> property identifies the element (or elements) whose contents or presence are controlled by the element on which this attribute is set.</p></blockquote> <p data-svelte-h="svelte-1j3ls17">This would be perfect if not for the fact that my left-hand side menu is encapsulated within a shadow DOM. The encapsulation mechanism extends to IDs on elements, meaning that the ID specified in the <code>aria-controls</code> attribute won’t be able to reference the element outside of the shadow DOM.</p> <p data-svelte-h="svelte-y4rn5n">The diagram below shows that the element with ID menu is encapsulated within a shadow DOM. As a result, it does not have access to elements with IDs resources, item-1, item-2, item-3 within its scope.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/12-improving-the-screen-reader-experience-for-learn-wcs/id-diagram.jpg" alt="The DOM structure, showing the menu inside of the shadow DOM, unable to reference light DOM nodes via ID"></div> </p> <aside data-svelte-h="svelte-1cel60m"><p>The <a href="https://github.com/leobalter/cross-root-aria-delegation/blob/main/explainer.md" rel>Cross-root ARIA</a> proposal goes into more details about some of the accessibility challenges associated with the shadow DOM</p></aside> <p data-svelte-h="svelte-ktfnt3"><code>aria-live</code> is a prospective option, as I can alert the screen reader when a part of the DOM gets updated. In this case it’s when the list of resources change after the user selects a section on the left.</p> <p data-svelte-h="svelte-1e0eqd9">I have reservations with using <code>aria-live</code>. For starters, the overuse of status updates and notifications gets annoying, especially when using the <code>assertive</code> value. There are also lots of inconsistencies with how <code>aria-live</code> behaves across different screen readers. Since I can only test with VoiceOver, I can’t guarantee that the behaviour I experience works across different screen readers. (This is called out directly in the <a href="https://www.scottohara.me/blog/2022/02/05/are-we-live.html" rel>Are We Live?</a> article)</p> <p data-svelte-h="svelte-1bnrjew">I tried two things:</p> <ol data-svelte-h="svelte-wbby0"><li>Adding <code>aria-live</code> around the resources list, but the screen reader announced the entire DOM subtree on every change, which is too verbose.</li> <li>Adding a small live region to announce the currently selected section, using a <code>output</code> element, but this repeated information announced by the screen reader when selecting a radio input.</li></ol> <p data-svelte-h="svelte-vsjzav">Instead of adding potentially finicky or problematic live regions, I opted to add a visually hidden heading above the resources list, to better distinguish the link between the radio button and the resources section.</p> <h2 data-svelte-h="svelte-8lw2oi">Using <code>aria-live</code>, sparingly</h2> <p data-svelte-h="svelte-1vs94zn">Finally, I moved over to the email form.</p> <p data-svelte-h="svelte-19rpwvv">I learnt that providing a label to a form allows VoiceOver to set it up as a landmark in the <em>landmarks</em> menu. Instead of labelling it using an <code>aria-label</code>, I used the <code>aria-labelledby</code> property. <code>aria-labelledby</code> lets you reference the text content for an existing DOM node as the label. There are a couple of benefits to using <code>aria-labelledby</code>:</p> <ol data-svelte-h="svelte-c81rpe"><li>You’re reusing content that’s already in the DOM, ensuring a more consistent experience between input modes.</li> <li><code>aria-label</code> can’t get automatically translated, while the content referenced by <code>aria-labelledby</code> can.</li></ol> <p data-svelte-h="svelte-1vyh5c">This is as easy as adding an ID to the button, and referencing that ID on the form element.</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>form</span> <span class="token attr-name">aria-labelledby</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>subscribe-button<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>submit<span class="token punctuation">"</span></span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>subscribe-button<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Subscribe<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>form</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-124u58m">Finally, after a user subscribes I append a notification with <code>aria-live=&quot;polite&quot;</code> to the page. This ensures that the notification gets read out, but it doesn’t interrupt the screen reader’s current announcements.</p> <p data-svelte-h="svelte-pejgvu">As a little bonus, I noticed a bug where the notification wasn’t being announced when the form was submitted while the text input was focused. This is because I reset the form once the request came back as successful and VoiceOver announces this if the input is focused. For some reason, it caused the notification to not be announced 🤷🏽.
So I did a hack and removed focus from the input before resetting the form values.</p> <iframe src="https://customer-2bboo8lk1rvh6fvm.cloudflarestream.com/90c8a14d2a444d4a78294264d704c9e1/iframe?poster=https%3A%2F%2Fcustomer-2bboo8lk1rvh6fvm.cloudflarestream.com%2F90c8a14d2a444d4a78294264d704c9e1%2Fthumbnails%2Fthumbnail.jpg%3Ftime%3D%26height%3D600" title="Filling out an email form using a screen reader. The screen reader makes an announcement when the form is successfully submitted" loading="lazy" aria-describedby="iframe-caption" class="cdn svelte-p8h0p9" allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture;" allowfullscreen></iframe> <h2 data-svelte-h="svelte-1dj9woh">Wrapping Up</h2> <p data-svelte-h="svelte-1zz3kn">Thanks a lot for reading. I implore you to try the same next time you build a web site. Crack open a screen reader and see if you can perform all the actions that a mouse and keyboard user would easily be able to do.</p>
]]></content>
<pubDate>Thu, 22 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/tips/03-how-to-be-notified-when-images-get-loaded-in-html</guid>
<title>How to be Notified When Images Get Loaded in HTML</title>
<link>https://www.component-odyssey.com/tips/03-how-to-be-notified-when-images-get-loaded-in-html</link>
<description>This is how you can be notified when images have been loaded in HTML within a DOM subtree.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-pq7xad">I recently created a web component to render masonry layouts, <a href="https://masonry-gallery-wc.netlify.app/" rel>masonry-gallery</a>.</p> <p data-svelte-h="svelte-1fwtv85">It does this by calculating the width and height of the images, and ordering them based on those dimensions. But I came across a bunch of problems pretty quickly.</p> <p data-svelte-h="svelte-87jo80">For starters, there’s no guarantee that the custom element is registered immediately, by the time it is registered some of its child images may have loaded while others may not have.</p> <p data-svelte-h="svelte-1wmfvu7">For galleries with dozens of images, the images could take a long time to load. To ensure that the masonry gallery renders the optimal layout, the layout algorithm needs to run every single time an image has loaded.</p> <h3 data-svelte-h="svelte-reuejk">When does the <code>load</code> event fire?</h3> <p data-svelte-h="svelte-1rkonh5">I did this by attaching a <code>load</code> listener on to the custom element itself. While the load event runs when child images load, it also runs when:</p> <ul data-svelte-h="svelte-1y4my1x"><li>The HTML page finishes loading</li> <li>iFrames, and other external resources finish loading</li></ul> <p data-svelte-h="svelte-5d8frc">External resources can be loaded via <code>link</code>, <code>embed</code>, <code>script</code> and other HTML elements, not just <code>img</code>. It’s important to add a check to ensure that the layout algorithm doesn’t run when load events from elements other than <code>img</code> are dispatched.</p> <h3 data-svelte-h="svelte-1ltiqg1">Using event delegation for <code>load</code> events</h3> <p data-svelte-h="svelte-1i46piv">I mentioned a second ago that I attached a single listener to the custom element that listeners to <code>load</code> events fired from the children. This is known as <em>event delegation</em> (which I’ll talk more about in a future newsletter). This is an alternative for adding event listeners to each individual child.</p> <p data-svelte-h="svelte-1lbo37g">Here’s an HTML grid that contains several images:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>grid<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>1.png<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>2.png<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>3.png<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>4.png<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-f15r16">You might think to attach an event listener to the parent element, like so:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">const</span> grid <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'.grid'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
grid<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">'load'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
	<span class="token function">generateLayout</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-142zrw2">However, this approach doesn’t work. This does work for other events, like <code>click</code>. So what gives?</p> <p data-svelte-h="svelte-vf8480">It turns out that the <code>load</code> event doesn’t <em>bubble</em>. Meaning that after the <code>img</code> element runs its <code>load</code> event handler, the event stops propagating. As a result, the event listener I added to the grid element doesn’t fire, meaning <code>generateLayout</code> doesn’t get invoked.</p> <p data-svelte-h="svelte-19c41t1">To solve this problem, you can add an option to <code>addEventListener</code> so that the even fires during the <em>capture</em> phase and not the bubble phase:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">const</span> grid <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'.grid'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
grid<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span>
	<span class="token string">'load'</span><span class="token punctuation">,</span>
	<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
		<span class="token function">generateLayout</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
	<span class="token punctuation">&#123;</span> <span class="token literal-property property">capture</span><span class="token operator">:</span> <span class="token boolean">true</span> <span class="token punctuation">&#125;</span>
<span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre>
]]></content>
<pubDate>Fri, 16 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/tips/02-how-does-the-browser-render-html</guid>
<title>How Does the Browser Render HTML?</title>
<link>https://www.component-odyssey.com/tips/02-how-does-the-browser-render-html</link>
<description>Let's take a high-level overview of how the browser renders your HTML</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-cleoph">The browser goes through a whole pipeline of actions to render your HTML.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/02-how-does-the-browser-render-html/rendering-pipeline.png" alt="The rendering pipeline for displaying HTML to the browser."></div> </p> <h2 data-svelte-h="svelte-1gshvcv">Construction</h2> <p data-svelte-h="svelte-16ws8uv">The browser starts by parsing the HTML + CSS and constructs the Document Object Model (DOM) and the CSS Object Model (CSSOM). These objects represent the structure and style of a given web page.</p> <p data-svelte-h="svelte-1mwx0fp">These two objects are then merged into the render tree, which represents all of the elements that will be rendered to the document, including the styles applied to each HTML element.</p> <h2 data-svelte-h="svelte-1st8hme">Layout / Reflow</h2> <p data-svelte-h="svelte-u9e2nt">Once that’s done, the browsers determines the dimensions and positions of these elements on the screen. This is a process known as layout. Layout is a CPU-intensive operation that can be affected by all manner of things like:</p> <ul data-svelte-h="svelte-9ntmhm"><li>the depth of the DOM</li> <li>the size of the DOM</li> <li>the complexity of CSS selectors</li> <li>the number of CSS rules</li></ul> <p data-svelte-h="svelte-fexbaj">While <em>layout</em> happens on the first render of the page. The browser can perform <em>reflow</em>, which is a similar process that happens on subsequent alterations to the page’s structure. It can occur after:</p> <ul data-svelte-h="svelte-gsoj6l"><li>adding or removing an element to the DOM</li> <li>applying certain styles to an element, like height and width</li> <li>using JavaScript to ready and modify the DOM</li></ul> <p data-svelte-h="svelte-1hd86br">The browser may not run the reflow for the entire DOM tree, but a subtree depending on where in the DOM tree the change was.</p> <h2 data-svelte-h="svelte-1q01i0o">Paint / Repaint</h2> <p data-svelte-h="svelte-17rp12i"><em>Paint</em> happens on the first render of the page and <em>repaint</em> occurs after subsequent reflows. This is when the browser displays the visual content to the screen.</p> <p data-svelte-h="svelte-ok7c20">It’s worth noting that there are CSS properties that you can apply to your HTML after initial render that don’t trigger a reflow. Understanding how to avoid reflow can be hugely helpful when trying to optimise your web page for performance. Properties that don’t affect the flow of the DOM include:</p> <ul data-svelte-h="svelte-1q7kk7f"><li>color and backgroundColor</li> <li>visibility</li> <li>outline</li> <li>…and others</li></ul> <h2 data-svelte-h="svelte-1dj9woh">Wrapping Up</h2> <p data-svelte-h="svelte-bya98f">In a previous edition of the newsletter, I talked about using <em>document fragments</em> to batch write changes to the DOM to reduce reflows. Having a high-level overview of how the browser renders your HTML can help you spot possible performance bottlenecks and fix them, so it’s worth diving deeper if you’d like to learn more:</p> <h2 data-svelte-h="svelte-170bgtm">Additional Resources</h2> <ul data-svelte-h="svelte-juq8xx"><li><a href="https://web.dev/articles/critical-rendering-path/render-tree-construction" rel>RenderTree Constructions</a></li> <li><a href="https://gist.github.com/faressoft/36cdd64faae21ed22948b458e6bf04d5" rel>DOM Performance</a></li> <li><a href="https://gist.github.com/paulirish/5d52fb081b3570c81e3a" rel>What forces reflow/repaint</a></li></ul>
]]></content>
<pubDate>Thu, 15 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/tips/01-using-document-fragments</guid>
<title>Using Document Fragments for Performant DOM Operations</title>
<link>https://www.component-odyssey.com/tips/01-using-document-fragments</link>
<description>Let's see how we can use document fragments to perform DOM operations in a performant way.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-1t5z0vt">Whenever you make a change to the DOM, like adding, updating, or removing DOM nodes, this can cause the browser to re-run CPU expensive processes like reflows and repaints.</p> <p data-svelte-h="svelte-1muuc7m">Instead you can use <em>document fragments</em>, to create a document object that’s separate from the DOM rendered on the page. With a <em>fragment</em>, you can perform DOM operations on it. When you’ve finished doing all you need to, you can append it to the rendered DOM, therefore massively reducing the number of reflow operations.</p> <p data-svelte-h="svelte-1yw0vzc">I use document fragments in my recent <a href="https://masonry-gallery-wc.netlify.app/" rel><code>&lt;masonry-layout&gt;</code></a> component.</p> <p data-svelte-h="svelte-10tyjqv">Imagine that you have a single-page application. You have a <code>&lt;main&gt;</code> element that your JavaScript uses to create and append markup to. If you’re rendering a heavy application, you might need to perform a lot of operations on that DOM element.</p> <p data-svelte-h="svelte-1ggir16">Instead of performing those CRUD operations on the DOM itself, you can create a fragment, run the operations on the fragment, and then append it to the document when you’re all done.</p> <p data-svelte-h="svelte-dt63ax">Here’s a very stripped back example of me using this in action:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">const</span> mainEl <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'main'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> docFrag <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">createDocumentFragment</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token keyword">const</span> div <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">createElement</span><span class="token punctuation">(</span><span class="token string">'div'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// perform a bunch of operations on the element, like adding more DOM nodes</span>
docFrag<span class="token punctuation">.</span><span class="token function">appendChild</span><span class="token punctuation">(</span>div<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token comment">// Add the fragment to the document</span>
mainEl<span class="token punctuation">.</span><span class="token function">replaceChildren</span><span class="token punctuation">(</span>docFrag<span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1drp7bv">Instead of the browser recalculating the page layout and styles on every operation, it does it just when the document is appended to the main element.</p>
]]></content>
<pubDate>Wed, 14 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/tips/00-using-fewer-dependencies</guid>
<title>Trying to Use Fewer Dependencies</title>
<link>https://www.component-odyssey.com/tips/00-using-fewer-dependencies</link>
<description>Can we reduce our reliance on third-party code?</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-zxgg8p">Recently I made a couple of contributions to the e18e initiative. I created a <a href="https://github.com/es-tooling/module-replacements-codemods/pull/68" rel>codemod</a> that converts usages of common NPM packages with lots of dependencies to use native JS features. You’d be shocked at how many <a href="https://x.com/passle_/status/1810805530706792930" rel><em>simple</em> packages pull in dozens (or hundreds) of dependencies</a>.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/tips/00-using-fewer-dependencies/traverse.png" alt="The dependencies tree for the traverse package contains dozens of packages"></div> </p> <p data-svelte-h="svelte-12oita6">It got me thinking about reducing my own reliance on third-party code. I’m not in favour of removing all dependencies from every package, but it puts my blind faith into question. I put a lot of faith whenever I install a package. I trust that:</p> <ul data-svelte-h="svelte-dbejms"><li>it’s well maintained</li> <li>it does the jobs it promises to do</li> <li>it’s performant</li> <li>there’s no unnecessary code (like support for old browsers + runtimes)</li></ul> <p data-svelte-h="svelte-1i5gvdz">I also don’t believe it’s my responsibility as a package author to be concerned about things like minification. These concerns should be the responsibility of application developers as they better understand the needs of their users. (If you’re interested in library-level concerns vs application-level concerns, then I cover this in <a href="/">Component Odyssey</a>).</p> <p data-svelte-h="svelte-10we5ol">If I were to publish a simple library that installs a commonly-used dependency like Lodash, even for a single function, like <code>isObject</code>, anyone using my component library will also have to install the Lodash dependency. This results in longer install times, heavier node_modules directory, and a worse experience for the end user if the developer doesn’t correctly optimise their project.</p> <p data-svelte-h="svelte-1xyz4lo">I wanted to avoid any third-party dependencies if possible in my most <a href="https://masonry-gallery-wc.netlify.app/" rel>recently published component</a>, <code>&lt;masonry-gallery&gt;</code>. <code>&lt;masonry-gallery&gt;</code> is a focused component. It renders its children as a masonry layout. Considering that the component does little more than re-order its children based on the element heights, I didn’t see a need to rely on any third parties.</p> <p data-svelte-h="svelte-14xrt53">The logic was fairly straightforward, but instead of leaning on Lodash for an <code>isEmpty</code> and a <code>debounce</code> function, I used the <a href="https://github.com/you-dont-need/You-Dont-Need-Lodash-Underscore" rel>You Might Not Need Lodash</a> GitHub repo to guide me into writing the equivalent code directly in my project.</p> <p data-svelte-h="svelte-gimawh">As a result, the <code>&lt;masonry-gallery&gt;</code> package has zero dependencies and is 2.4kb minified, 1.1kb minified + gzipped.</p> <p data-svelte-h="svelte-ppbz86">This simplifies my dev environment too and makes it easier to publish code that works across a range of different projects by default.</p>
]]></content>
<pubDate>Tue, 13 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/11-masonry-gallery</guid>
<title>masonry-gallery Web Component</title>
<link>https://www.component-odyssey.com/articles/11-masonry-gallery</link>
<description>A quick and simple HTML web component to render a masonry layout.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-2ioc30">A few years back I created an image gallery inside a React project. The images had inconsistent widths and heights, and so it made sense to display it as a masonry layout.</p> <p data-svelte-h="svelte-17v348n">For those not familiar, a masonry layout is a way of displaying content (usually images), where each image is appended to the currently shortest column, like so:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/11-masonry-gallery/layout-chart.png" alt="Several boxes with different heights placed within a 3 column grid. The number inside of each box indicates the order in which they're appended to the layout"></div> </p> <p data-svelte-h="svelte-1o6obms">The numbers in the box, indicates the order in they’re appended to the layout. There’s currently no masonry layout implemented across the browsers, though the specs are currently being defined.</p> <p data-svelte-h="svelte-aagjtr">As for creating a component, it was such a waste for the OG being locked in React-land. Especially as I have no plans to revisit that project.</p> <p data-svelte-h="svelte-readnl">It made a lot more sense to create a web component that renders a masonry layout. For starters:</p> <ol data-svelte-h="svelte-pw3jvn"><li>Should the component fail to load/register, the user still sees the default browser behaviour</li> <li>It wouldn’t rely on a specific JavaScript framework.</li> <li>There’s no complex logic going on, so it would be a lean component with little overhead.</li> <li>There’s no need for style encapsulation, so <code>masonry-gallery</code> avoids using the Shadow DOM</li></ol> <p data-svelte-h="svelte-1xvlso4">In fact, <code>masonry-gallery</code> is only 4kb unzipped and has zero dependencies. The component doesn’t use the shadow DOM either, so you can style it to your heart’s content using your global CSS.</p> <p data-svelte-h="svelte-1y5yyjp">Here’s the component in action:</p> <masonry-gallery class="svelte-1qnaawt" data-svelte-h="svelte-brxnum"><img src="/images/articles/11-masonry-gallery/doggo-1.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-2.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-3.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-4.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-5.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-6.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-7.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-8.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-9.jpeg" alt="A random cute dog"> <img src="/images/articles/11-masonry-gallery/doggo-10.jpeg" alt="A random cute dog"></masonry-gallery> <h2 data-svelte-h="svelte-1gkebot">Getting started</h2> <p data-svelte-h="svelte-1q5f06m">To use this layout in your project, run the following:</p> <pre class="language-bash"><!-- HTML_TAG_START --><code class="language-bash"><span class="token function">npm</span> <span class="token function">install</span> masonry-gallery</code><!-- HTML_TAG_END --></pre> <h3 data-svelte-h="svelte-kiba3">Usage in HTML</h3> <p data-svelte-h="svelte-oyar9v">You can then import the module inside of your HTML:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>masonry-gallery</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>https://placedog.net/600/400<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>img</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>https://placedog.net/220/450<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>masonry-gallery</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>module<span class="token punctuation">"</span></span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>node_modules/masonry-gallery/masonry-gallery.js<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token script"></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <h3 data-svelte-h="svelte-l4n3ll">Usage in JavaScript</h3> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">import</span> <span class="token string">'masonry-gallery/masonry-gallery.js'</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-ypejvs">You’ll need to ensure that the above JS file is imported within your webpage.</p> <h2 data-svelte-h="svelte-smz8fp">Learn More</h2> <p data-svelte-h="svelte-1crsbrp">Jump over to the <a href="https://github.com/andrico1234/masonry-gallery?tab=readme-ov-file" rel>GitHub</a> if you want to learn more or see the code itself.</p>
]]></content>
<pubDate>Thu, 08 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/10-what-is-a-library-should-you-build-your-own</guid>
<title>What is a Component Library and Should You Build Your Own?</title>
<link>https://www.component-odyssey.com/articles/10-what-is-a-library-should-you-build-your-own</link>
<description>Before diving into building you're own component library from scratch, let's have a look at the different types of component libraries out there, and the benefits and drawbacks of using them.</description>
<content type="html"><![CDATA[
 <aside data-svelte-h="svelte-cbvhhy"><p>💡 I want to give a special shoutout to @stephband (<a href="https://front-end.social/@stephband" rel>Mastodon</a>, <a href="https://bsky.app/profile/stephen.band" rel>Bluesky</a>) for proofreading and providing feedback.</p></aside> <h2 data-svelte-h="svelte-1tmzbxd">What if there were no music albums?</h2> <p data-svelte-h="svelte-3unvhg">I’m a huge music fan. One of my favourite pastimes is to put on a record and listen to it front to back. A music album is simple in concept, it’s a suite of recorded tracks by an artist and is considered a complete and coherent set of songs.</p> <p data-svelte-h="svelte-ybxvnq">But what if recorded music didn’t exist? Instead of putting songs to tape, CD, or mp3 (or FLAC if you’re that way inclined), you could only listen to an album if the artist played it live for you. You’d need to go to the band, ask them to set up their equipment and get them to play the album front-to-back. They’d need to play it the same way every time to ensure that everyone had the exact same experience.</p> <p data-svelte-h="svelte-195983z">The cracks would start to show. It’s not an efficient way to ensure that anyone interested in the band’s music can listen to it. If Taylor Swift were to play her song Fortnight personally for every person who listened to it on Spotify, it would take her 3,179 years. And that doesn’t account for any <a href="https://www.threads.net/@adhd.international/post/C6ugTXAPt71?hl=en-gb" rel>plane travel</a>. Artists would get bored, maybe even careless, leading to a lesser experience for their listeners.</p> <p data-svelte-h="svelte-11wkbdl">So how does this relate to web development? Every time you build a UI control, you have to ensure it’s functioning, robust, and accessible. You’ll get bored if you keep rewriting the same UI every time. Mistakes will slip through, leading to a worse experience for your end users.</p> <h2 data-svelte-h="svelte-2zbp9w">A little about me</h2> <p data-svelte-h="svelte-b21195">I’ve been a web developer for nearly 10 years, and I’ve written hundreds of components myself, often the same UI pattern many times. I’ve used dozens of component libraries, and have built admin dashboards, component libraries, mobile applications, blogs, figma plugins, VSCode extensions, and more. This article will be a distillation about where I see the role of components, libraries, and whether developers should write their own.</p> <h2 data-svelte-h="svelte-1aqw74h">What is a component?</h2> <p data-svelte-h="svelte-1t4fp8a">When building user interfaces, we don’t write all the HTML markup from scratch every single time. We write our UIs using components— reusable building blocks that encapsulate common UI patterns. Writing a component lets you use it multiple times in a single project or even in independent projects.</p> <p data-svelte-h="svelte-qfehez">Here I’ve written a counter component, I’ve written it once and used it in multiple places on the page.</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <p data-svelte-h="svelte-1wqweu4">Us tutorial creators like to demo counters like they’re going out of style, but a real-world application will contain dozens of different UI patterns written as components.</p> <p data-svelte-h="svelte-1d1iio8">In this article, I’ll group CSS rules that provide styling for certain UI patterns under the components umbrella. The definition can get murky depending on who you ask.</p> <h2 data-svelte-h="svelte-s6umvc">What is a component library?</h2> <p data-svelte-h="svelte-1btc2sb">Not all components are standalone. It makes sense for many components to be grouped within a single package, called a component library.</p> <p data-svelte-h="svelte-1i81xfb">If you want your site to have a specific look or feel, you can use a <em>component library</em>. There are component libraries that:</p> <ul data-svelte-h="svelte-3u5wgs"><li>offer components that adhere to a design specification.</li> <li>offer multiple solutions for a specific UI pattern.</li> <li>work with specific toolchain</li></ul> <p data-svelte-h="svelte-1r3bnzk">But they come in different shapes and sizes. The definition I’ve come to use when defining a component library is the following:</p> <p data-svelte-h="svelte-1afynmc"><em>A component library is a set of reusable components that are cohesive in their utility, or appearance (or both). A great component library will help developers achieve their UI needs efficiently, while offering an exemplary experience for the end user.</em></p> <h2 data-svelte-h="svelte-11kg1jc">What’s the difference between a component library and a design system</h2> <p data-svelte-h="svelte-t47gx3">I talk about guidelines and design systems later in this article, so I’ll take a moment to disambiguate them. It can be difficult to see where one ends, one begins, or one subsumes the other.</p> <p data-svelte-h="svelte-acs6ul"><strong>Design Systems</strong></p> <p data-svelte-h="svelte-1u7rc95">I see a design system as a specification for how things should look, feel, and behave. A design system can encompass a product, a brand, or a company to ensure consistency across the suite of experiences. A comprehensive design system will dictate everything from font families, font sizes, spacing sizes, UI patterns, and copy guidelines.</p> <p data-svelte-h="svelte-sdh2f0">A few of the most well-known design systems include:</p> <ul data-svelte-h="svelte-1r41nw7"><li><a href="https://m3.material.io/foundations/layout/understanding-layout/overview" rel>Material Design</a> (Google)</li> <li><a href="https://base.uber.com/6d2425e9f/p/294ab4-base-design-system" rel>Base Design</a> (Uber)</li> <li><a href="https://www.lightningdesignsystem.com/getting-started/" rel>Lightning Design System</a> (Salesforce)</li></ul> <p data-svelte-h="svelte-ext7qv">While many design systems are specific to companies, there are design systems, like Material Design, that teams across the globe use to shortcut their way to building familiar feeling products. You’ve probably used a handful of products that use Material Design principles but they’re <a href="https://www.smashingmagazine.com/2021/02/material-design-text-fields/" rel>certainly not free from basic usability issues</a>.</p> <p data-svelte-h="svelte-1na8tl9"><strong>Component Libraries</strong></p> <p data-svelte-h="svelte-tjl450">As for component libraries, they may or may not be the code implementation of a design system. If you work for a company with a design system, it’s likely that the corresponding component library (if one exists), is tightly integrated with it.</p> <p data-svelte-h="svelte-eqoqv0">For instance, Google’s <a href="https://material-web.dev/" rel>Material Web</a> is a web component implementation of Material Design. <a href="https://baseweb.design/components/button/" rel>Base Web</a> and <a href="https://lwc.dev/guide/introduction" rel>Lightning Web Components</a> are also open source too.</p> <h2 data-svelte-h="svelte-165dhnm">A brief history of component libraries</h2> <p data-svelte-h="svelte-15sat77">The concept of UI components (or widgets) has been around for a long time. If you want to see a museum’s worth of retro user interfaces, grab some popcorn and watch this <a href="https://vimeo.com/61556918" rel>2+ hour video of “all the widgets” from 1974-1990</a>.</p> <p data-svelte-h="svelte-1iqzato">From the early 2000s, we’d start seeing component libraries made to help developers build for the web. The web browser landscape back then was unrecognisable from what we see now. Versions of Internet Explorer deviated away from the spec entirely, which was particularly problematic given the <a href="https://en.wikipedia.org/wiki/Usage_share_of_web_browsers#TheCounter.com_(2000_to_2009)" rel>huge market share that IE had back in the day</a>. <a href="https://www.quora.com/Why-do-people-hate-IE6-so-much-and-want-it-to-die#:~:text=IE6%20doesn't%20support%20web,PNGs%20to%20natively%20support%20IE6" rel>Internet Explorer 6 was famously known for being a pain to develop for</a>. Mainly due to its incorrect implementation of the <a href="https://www.webfx.com/blog/web-design/definitive-guide-to-taming-the-ie6-beast/#616723179a361-3" rel>box model</a>, and lack of CSS2 support.</p> <aside data-svelte-h="svelte-d4gr07"><p>💡 TIL, Internet Explorer supported a “<a href="https://www.notion.so/Complete-written-content-806882f918204715a6e45df68f492bdd?pvs=21" rel>quirks mode</a>” that let developers write non-standard HTML and CSS to appease older browsers that didn’t support the standards.</p></aside> <p data-svelte-h="svelte-y19rz3">Fortunately, when I started web development in earnest, many of these issues were ironed out. By this point, there were still a handful of libraries that made writing complex interfaces with cross-browser support a little easier. <a href="https://jqueryui.com/" rel>jQuery UI</a>, the first component library I used, supported accordions and other widgets. But the browser is constantly evolving, and we now have a native way of implementing this accordion pattern using the <code>details</code> and <code>summary</code> elements, available in all browsers in 2020. With these elements, you can get pretty far along creating interactive accordions without JavaScript.</p> <p data-svelte-h="svelte-11aiahy">Contrast this with 2009, and these elements haven’t been implemented in any browser. It required a fair bit of JS to get working. Have a look at the <a href="https://code.jquery.com/ui/1.7.0/jquery-ui.js" rel>jQuery UI v1.7 source code</a>, and CTRL+F “accordion” if you want to see how web devs were implementing accordions 15 years ago.</p> <p data-svelte-h="svelte-1s0k86k">Over the next couple of decades, the capabilities of the web grew. More powerful devices meant more powerful browsers. More powerful browsers meant web applications became more ambitious. Developers responded by creating the tools to help us build these applications by allowing us to create UIs using <em>building blocks</em>, i.e., a component model. We saw a proliferation of these component-based frameworks. I’m talking Angular, React, and Vue. Each with its own rich ecosystem of component libraries.</p> <aside data-svelte-h="svelte-1dtt64a">There’s a reasonable argument to be made that there has been an over-correction and that the frontend landscape is now oversaturated with tools that are _too_ powerful for most people’s needs, but let’s not go there.</aside> <p data-svelte-h="svelte-1xz0hsl">With tools like jQuery UI, library consumers would write the markup themselves, and manually add the interactivity, like so:</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <p data-svelte-h="svelte-b00oh7">With the newer component model, developers could author fully encapsulated components with markup and behaviour, and consume it by doing little more than plopping it on the page:</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <p data-svelte-h="svelte-ndr5h2">You can see that the behaviour between the two accordion components aren’t 1-2-1. I could add a little JS to make it behave like the jQuery accordion. The benefit is that the second accordion is built using HTML only, and the JS can be used to enhance the core experience.</p> <h2 data-svelte-h="svelte-1y8kl66">What makes a good component library?</h2> <p data-svelte-h="svelte-1smlxpa">The challenge with building a component library is that they’re not a <em>one-and-done</em> deal. Many of the most popular libraries have been around for years and have had heaps of research, usage feedback, and contributions to get them to where they are now.</p> <p data-svelte-h="svelte-b1wgvj">I’ve found that a good component library often has the following traits:</p> <ul data-svelte-h="svelte-1ffnvbz"><li>It understands the problems of its target developers and solves those problem well</li> <li>It has great documentation</li> <li>It ensures a good experience for the end-user</li> <li>It’s robust and caters for appropriate input modes and devices.</li></ul> <p data-svelte-h="svelte-7d7nn4">On the flip side, a way to discern if a component library <em>isn’t good</em> is if it doesn’t consider accessibility, has an inconsistent API, has little to no project stewardship, or has no clear and consistent documentation.</p> <h2 data-svelte-h="svelte-ha4zi8">What are the benefits of using a component library?</h2> <p data-svelte-h="svelte-13vprkz">We know what a good component library looks like, so let’s see how one can make your life, and the lives of your users a little better.</p> <h3 data-svelte-h="svelte-is7y37">Component libraries save you time</h3> <p data-svelte-h="svelte-latzc2">If you’re on a project with a tight deadline, it’s important to be efficient. But efficiency shouldn’t come at the cost of crafting a robust web experience. Using a component library lets you spend less time reinventing the wheel and more time focusing on the finer details.</p> <h3 data-svelte-h="svelte-7ncxps">Component libraries make you and your users happier</h3> <p data-svelte-h="svelte-5gm42p">We’re not motivated by repetitive work. We enjoy technical challenges, and writing the same components over again is not a fun challenge. We’ve already spoken about what happens when we get bored and let mistakes slip through.</p> <p data-svelte-h="svelte-t7cb2e">If you wanted to implement a dialog component from scratch, you’d need to:</p> <ul data-svelte-h="svelte-zjbsa2"><li>Handle focus trapping correctly</li> <li>Make the rest of the page inert</li> <li>Position the dialog correctly</li> <li>Ensure that it works with assistive technologies</li></ul> <p data-svelte-h="svelte-19e5zoj">It takes work to remember and implement the above, but the consequence of getting it wrong can render your interface literally unusable, such is the case if you <a href="https://www.w3.org/WAI/WCAG21/Understanding/no-keyboard-trap.html" rel>incorrectly handle focus</a>.</p> <p data-svelte-h="svelte-3pnwfb">By using a component library that’s been built with the end users in mind, you can prevent the risk of introducing broken experiences, while spending less time rebuilding the same components.</p> <h3 data-svelte-h="svelte-cjzes">Component libraries lead to consistent experiences</h3> <p data-svelte-h="svelte-1125ye0">If you work for a company with several different web applications, they’ll generally follow a set of guidelines. These guidelines might dictate the colour palette to use, the size of your typography, or how UI elements should look and behave.</p> <p data-svelte-h="svelte-1ty5xu4">But you increase the likelihood of your application deviating from the style guide if you’re re-writing components. By having a component library, you can more easily audit your component’s UI against the brand guidelines so they look great, wherever they’re used.</p> <p data-svelte-h="svelte-1i11mit">Uber has several different apps that share the same user interface elements. I’m almost certain that they use the same component library across these apps. That way each new app is virtually guaranteed to adhere to the brand’s guidelines.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/10-what-is-a-library-should-you-build-your-own/uber.png" alt="Different Uber apps side by side, showing how similar they are in terms of appearance"></div> </p> <h2 data-svelte-h="svelte-428h8s">What are the drawbacks of using a third-party component library?</h2> <p data-svelte-h="svelte-1oaw4mr">The benefits I’ve mentioned above are irrespective of whether you’re using your own component library or a third party. If you or your team has decided that they don’t want to build a library, and instead lean on a third-party, then it’s worth considering the following.</p> <h3 data-svelte-h="svelte-1fqu7lz">Vendor lock-in</h3> <p data-svelte-h="svelte-1c5gycm">By choosing a component library, you’re picking a partner who will greatly impact how you write your frontend code and how your interfaces will look and behave.</p> <p data-svelte-h="svelte-1dxect">The former will have a big impact on you, and the latter will have a big impact on your end users. Using a component library is locking you into the standards of that component library.</p> <p data-svelte-h="svelte-12np1oe">The library could introduce massive breaking changes in a major version that could require dedicated development time, and a lot of testing to ensure that no serious regressions were introduced.</p> <p data-svelte-h="svelte-1gkuwca">A few years back I used React Admin to build a complex admin dashboard to an internal division. The library offered a suite of components specifically dedicate for fetching and displaying complex data. Because our application at the time relied heavily on React Admin, upgrading between major versions was challenging, especially as many of the internal tools used by React Admin had been swapped out for others. The change surface was huge, and we spent a good deal of time upgrading and flagging the issues that we spotted.</p> <p data-svelte-h="svelte-2kfw1o">I don’t believe that building our own solution would have saved us any time in the long term, but this kind of vender lock-in is worth considering, especially before going all in on a tool.</p> <h3 data-svelte-h="svelte-1l65n9z">Code bloat</h3> <p data-svelte-h="svelte-1e4evhu">Shocking as it is, libraries with a lot of components tend to be written using lots of code. Code that you download when installing dependencies, and code you sending over to your end users.</p> <p data-svelte-h="svelte-dqsp8e">Modern tooling makes it easier to perform bundle optimisations like tree-shaking to remove unused code, but there’s no guarantee that you’re removing all of the code that your users won’t need.</p> <p data-svelte-h="svelte-71bd0v">Unless you dig deep into the libraries that you’re using, you may not be aware of all the separate packages they’re importing. You could end up with hundreds of unnecessary dependencies. The folks in the <a href="https://e18e.dev/" rel>e18e</a> community have been working hard at bringing this problem to light, <a href="https://x.com/DanaWoodman/status/1819084012729798833" rel>while also fixing it too</a>.</p> <p data-svelte-h="svelte-1yfzzaf">Many of these problems could also be said about rolling your own component library. The biggest difference is that you have stewardship over your component library. You’re able to define how it solves your specific problems, and you have control over improving its shortcomings.</p> <h2 data-svelte-h="svelte-rfhj6u">The different shapes a component library can take</h2> <p data-svelte-h="svelte-11t7oyc">The <a href="https://cds.cern.ch/record/369245/files/dd-89-001.pdf" rel>initial proposal</a> for the World Wide Web was a tool to improve communication between researchers at CERN. The proposal outlined how documents could be shared, and linked to one another through the use of hypertext. This is the fundamental cornerstone of the web, and we still use the humble <code>&lt;a&gt;</code> tag to link between other HTML documents across the web.</p> <p data-svelte-h="svelte-1e3hcrt">But the web has grown in scope over the last few decades, and the browsers we use to navigate the web have become beasts of their own. The browsers today can enable <a href="https://plumegame.com/" rel>powerful forms of creative expression</a>, and the <a href="https://medium.com/@addyosmani/photoshop-is-now-on-the-web-38d70954365a" rel>running of native-like software</a>.</p> <p data-svelte-h="svelte-1a76vln">There are hundreds of different solutions out there, some general purpose, others hyper-niche, but finding the right tool for your next project requires a complex decision process that might look like this.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/10-what-is-a-library-should-you-build-your-own/flowchart.png" alt="The different kinds of component libraries, and when you should use them. The diagram's context is explored below"></div> </p> <p data-svelte-h="svelte-1xbpj63">This isn’t a comprehensive list of ALL use cases or component library types, but it illustrates how component libraries differ in terms of:</p> <ul data-svelte-h="svelte-1rk10uu"><li>the technologies involved.</li> <li>the levels of abstraction they offer.</li> <li>the problems they solve.</li></ul> <p data-svelte-h="svelte-9k9cds">Let’s take a look at some of the most common component library types</p> <h3 data-svelte-h="svelte-19ylwi9">Utility classes libraries / CSS Style Guides</h3> <p data-svelte-h="svelte-10pw3es">For me, <a href="https://getbootstrap.com/" rel>Bootstrap</a> is the first that comes to mind. Back in the day, if you wanted to give your site a quick lick of paint, you’d drop the CDN link to the bootstrap CSS file and immediately get that Bootstrap look. It was everywhere in the mid-2010s.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/10-what-is-a-library-should-you-build-your-own/bootstrap.png" alt="A demo example of a Bootstrap web, circa 2013"></div> </p> <p data-svelte-h="svelte-1nki44x">The technical scope of these kind of tools range from</p> <ul data-svelte-h="svelte-16nlmc"><li>A single CSS file (<a href="https://picocss.com/" rel>Pico</a>)</li></ul> <p data-svelte-h="svelte-8wg17z">to</p> <ul data-svelte-h="svelte-37u07k"><li>A toolchain to generate CSS classes based on your configuration (<a href="https://tailwindcss.com/" rel>Tailwind</a>)</li></ul> <p data-svelte-h="svelte-2pu81p">Dozens of other tools, like <a href="https://open-props.style/" rel>Open Props</a>, fit somewhere in between.</p> <h3 data-svelte-h="svelte-1ddqvjo">Off-the-shelf component libraries</h3> <p data-svelte-h="svelte-17vjxtm">If you’re building an interactive web application, you might just want to grab a suite of components that look great and function well. There are many of these off-the-shelf component libraries that give you everything you need and more.</p> <p data-svelte-h="svelte-17ra5br">Regardless of which framework you’re writing your app with, there’s likely to be a set of great looking components for you to use.</p> <p data-svelte-h="svelte-1qlyau5">Another great component library is <a href="https://shoelace.style/" rel>Shoelace</a>, which provides dozens of fully interactive and fully-styled components.</p> <p data-svelte-h="svelte-1vrjcfz">What makes libraries like Shoelace particularly interestingly is that it’s built using web components, the browser’s built-in way of writing components. Building your UIs with tools like Shoelace, give you the added benefit of being able to use them across different frontend frameworks. <a href="/articles/01-writing-components-that-work-in-any-framework">Which is something I’ve spoken a little about in the past.</a></p> <p data-svelte-h="svelte-4cqsh9">Here’s the same Shoelace component being used in Vue and React.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/10-what-is-a-library-should-you-build-your-own/shoelace.gif" alt="Shoelace in Vue and React"></div> </p> <h3 data-svelte-h="svelte-l967ua">Unstyled components</h3> <p data-svelte-h="svelte-lh2kvr">Depending on your project’s specs, you might not have the luxury of using an off-the-shelf tool. Your design specs might be very specific.</p> <p data-svelte-h="svelte-1ksi5ot">I’ve seen teams roll components at the first sign of friction. And in one case of a hand-rolled data picker, led to a way worse user experience. In retrospect, using an unstyled component library would have given the team flexibility with appearance, while ensuring that the time</p> <p data-svelte-h="svelte-yve5t6">That’s why you can reach for a library out there that offers completely unstyled components with flexible styling hooks. If it’s a good library, it’ll also take care of all those complex interactions. It’s a best of both worlds situation.</p> <p data-svelte-h="svelte-3do8o">It’s easy to mess up a checkbox if you want to push beyond the styling hooks that the browser provides, unless you test with a wide-range of devices and input modes.</p> <div style="aspect-ratio:16/9;position:relative;width:100%"><iframe title="Custom checkbox component" src="https://player.vimeo.com/video/995085532?badge=0&autopause=0&player_id=0&app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture;" style="position:absolute;top:0;left:0;width:100%;height:100%;"></iframe></div> <p data-svelte-h="svelte-1az159z"><a href="https://www.radix-ui.com/" rel>Radix</a> is a popular example of a library, but it’s built using React.</p> <p data-svelte-h="svelte-yz5q8k">Other examples of component libraries like this are <a href="https://lion-web.netlify.app/" rel>Lion</a> and <a href="https://headlessui.com/" rel>HeadlessUI</a>.</p> <h3 data-svelte-h="svelte-psjm3b">Copy Pastable Component Libraries</h3> <p data-svelte-h="svelte-1aabveo">Some developers might want the best of both worlds. They might want a component built by a trusted third-party library, while also having full control over the markup, styles, and functionality. Libraries like <a href="https://ui.shadcn.com/" rel>ShadCN</a> allow for this kind of work flow, by allowing developers to copy and paste the component definition into their own projects, effectively letting them <em>own</em> the component.</p> <h2 data-svelte-h="svelte-ho430a">Why isn’t there one component library to rule them all?</h2> <p data-svelte-h="svelte-131lzn6">At this point, it’s probably clear why no such single component library exists. We’ve looked at a non-exhaustive look at different groups of component libraries.</p> <p data-svelte-h="svelte-vbovgg">There is, however, a movement to introduce a “<a href="https://bradfrost.com/blog/post/a-global-design-system/" rel>Global Design System</a>”, a concept spearheaded by Brad Frost.</p> <p data-svelte-h="svelte-1epzdow">In the announcement, Brad outlines that in the hundreds of projects he’s been a part of, many of the UI controls behave (or should behave) similarly across these various projects, yet developers reimplement the same thing in every single project. This has lead to lots of wasted time and effort, and inconsistencies between projects. This also expands to the existing component libraries out there. You’ll see that the keyboard behaviour for a combobox in React Aria, is different to that of the combobox in ShadCN.</p> <div style="aspect-ratio:16/9;position:relative;width:100%"><iframe title="Combobox comparison" src="https://player.vimeo.com/video/995085659?badge=0&autopause=0&player_id=0&app_id=58479" frameborder="0" allow="autoplay; fullscreen; picture-in-picture;" style="position:absolute;top:0;left:0;width:100%;height:100%;"></iframe></div> <p data-svelte-h="svelte-17ubmbu">Brad Frost is proposing a Global Design System as a set of web components that should be adoptable by almost any frontend project to ensure a baseline of functionality for the controls that are not yet available in HTML.</p> <p data-svelte-h="svelte-1o9ulyq">There are <a href="https://github.com/openui/open-ui/issues/1066" rel>discussions going on within the Open UI</a> to see how this could start taking shape within the next few years.</p> <h2 data-svelte-h="svelte-1fb3n8y">Should you build your own component library?</h2> <p data-svelte-h="svelte-1pm7bmr">This article has been a wide dive into component libraries, and with all that context, you’ll inevitably ask yourself, when staring at the empty HTML page for your next big project, whether to build your own component library or use an existing one.</p> <p data-svelte-h="svelte-6gkldh">My first thought is: <em>I don’t think you should build your library.</em></p> <p data-svelte-h="svelte-j382t3">I generally favour picking a battle-tested library. Particularly one that has:</p> <ul data-svelte-h="svelte-1ktpz9s"><li>Been used across thousands of projects</li> <li>A strong community, in Discord, or GitHub</li> <li>Great documentation</li> <li>A strong focus on accessibility</li> <li>Worked with the strengths of the chosen framework</li></ul> <p data-svelte-h="svelte-1tpza1m">Most importantly out of all of these is to use a component library puts care into building accessible components.</p> <p data-svelte-h="svelte-rycc1r">Take a combobox for instance. It’s a search input and a select menu mixed into one. If you’ve built your own, you may get it looking good, and working with your mouse. But you’ll also need to consider:</p> <ul data-svelte-h="svelte-1fifpie"><li>Cross browser support</li> <li>Tab and focus behaviour</li> <li>Screen reader support</li> <li>Handle states for async loading of search results</li></ul> <p data-svelte-h="svelte-hp7o6e">Konnor Rogers, who does excellent work in the web + web component space, has shared countless frustrations with his experiences building an accessible combobox. Here’s one such <a href="https://x.com/RogersKonnor/status/1797529313279140294" rel>tweet he shared</a>.</p> <p data-svelte-h="svelte-xbfr35">Screen reader support is particularly complex, and is worth of its own bullet-point list. To support screen readers, you’ll also need to handle:</p> <ul data-svelte-h="svelte-1d9a8ra"><li>live regions</li> <li>interactive controls</li> <li>selected items</li> <li>support between different screen readers</li></ul> <p data-svelte-h="svelte-18y3nlm">As a side note, I only have access to Voiceover, meaning it’s difficult for me to test these complex UI patterns using different screen readers. Like browsers, there are differences between screen readers. In this article, <a href="https://www.scottohara.me/blog/2022/02/05/are-we-live.html" rel>Are We Live?</a>, Scott O’Hara describes how there’s variance among the difference with how they treat the live regions.</p> <p data-svelte-h="svelte-lua3oh">This means it’s also up to you, the developer to pick a component library that you can trust has been developed with accessibility in mind. This is why it’s also important to pick a component library that has a strong community. It’s important to be able to:</p> <ul data-svelte-h="svelte-5fiyzi"><li>See the bugs and issues others have flagged for a given library</li> <li>Suggest (or even contribute) improvements and changes to such library</li> <li>Discuss ideas with members of the community and build working relationships with active members of the community or even maintainers themselves</li></ul> <p data-svelte-h="svelte-1s7c5bz">Finally, and not least, a great component library will consider much more than the aesthetics of their components. For a component library designed for the web, it should try it’s best to:</p> <ul data-svelte-h="svelte-1a2bmam"><li>adhere to the <a href="https://www.w3.org/TR/WCAG21/" rel>Web Content Accessibility Guidelines (WCAG)</a></li> <li>ensure that the components work across different input modalities (touch, keyboard, screen reader)</li> <li>ensure that the components are usable for folks with additional requirements, like those living with vestibular disorders, vision impairments, or a broken hand.</li></ul> <h2 data-svelte-h="svelte-e65u5z">Building your own component library can be a good thing, actually</h2> <p data-svelte-h="svelte-ach380">If I haven’t scared you off from building a component library, then let me contradict myself and explain why it can be a really good thing to build your own.</p> <p data-svelte-h="svelte-2w00z7">If you take the time to put care and attention into building a component library, then you’ll find yourself a developer who better understands the browser platform, accessibility best practices, testing practices, and more.</p> <p data-svelte-h="svelte-mvd1v2">But it doesn’t just stop there, there are some excellent reasons to build your own library.</p> <p data-svelte-h="svelte-wug3q7">For starters, you can build something tailored to your needs, and avoid some of the bloat you might get form an off-the-shelf component library. It’s up to you and your team to understand your end users, and you can build something specifically for them.</p> <p data-svelte-h="svelte-1ljw1tr">You also have the opportunity to experiment with novel approaches. If you have a hyper-niche problem, there might not be a component library out there to solves that need. It could be a component library that:</p> <ul data-svelte-h="svelte-1xg6fkm"><li>Visualises data in specific way</li> <li>Has a distinct and unique visual identity</li> <li>Is built on a new framework</li></ul> <p data-svelte-h="svelte-qfp1a6">That gives you the opportunity to build something tailored to your needs. You then have the opportunity to change and fix things as your needs change, or as you understand the problem space better.</p> <p data-svelte-h="svelte-jqwrfy">Importantly, you’ll learn more about the web by doing so. If it’s your first time building a component library, it can be an opportunity to dive deeper into the <a href="https://html.spec.whatwg.org/multipage/" rel>HTML browser specs</a>, or brush up on your <a href="https://www.w3.org/TR/WCAG21/" rel>web accessibility knowledge</a>. This will improve your abilities as a web developer, which will serve you well in any frontend project in the future. It could even help you land your next job.</p> <p data-svelte-h="svelte-1n066a1">So whether you should build a component library depends on your end goals. Consider questions like:</p> <ul data-svelte-h="svelte-1vra2cb"><li>Do I want to better under stand the browser?</li> <li>Do I want to build something quickly?</li> <li>Do I want to make it usable for as many users as possible?</li> <li>Do libraries exist that solve my current problem?</li></ul> <p data-svelte-h="svelte-1q8y6q">Depending on what your answers are, you can make the right call for your project.</p>
]]></content>
<pubDate>Mon, 05 Aug 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/09-different-host-selectors</guid>
<title>Wait, what's the difference between :host, :host(), and :host-context()?!</title>
<link>https://www.component-odyssey.com/articles/09-different-host-selectors</link>
<description>There are three different, yet similar selectors available in web components, :host, :host(), and :host-context(). Let's look at the difference between them.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-gwug31">In this article we’re going to be looking at three similar, but very different selectors available in web components, <code>:host</code>, <code>:host()</code>, <code>:host-context()</code></p> <p data-svelte-h="svelte-17ka6tq">Before we start, here’s a little refresher on some useful terminology.</p> <p data-svelte-h="svelte-1kzbzu4">In the demos, we’ll look at a <code>&lt;progress-indicator&gt;</code> web component. This component has some markup that’s encapsulated within the shadow DOM. Once the component has been registered, you can use it within your HTML file via the <code>&lt;progress-indicator&gt;</code> element.</p> <p data-svelte-h="svelte-18hbmn5">The <code>&lt;progress-indicator&gt;</code> element is what’s known as a <em>shadow host</em>. This means that it exists in the light DOM and attaches its shadow DOM.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/09-different-host-selectors/shadow-host.png" alt="diagram of relationship between the progress indicator component and the light DOM.gif"></div> </p> <p data-svelte-h="svelte-y4lg0w">The shadow host is particularly interesting because it can be styled both from the light dom, via the <code>progress-indicator</code> CSS element selector, and from within the shadow DOM via the <code>:host</code> selector. Let’s look a little further.</p> <h2 data-svelte-h="svelte-nh1vn5"><code>:host</code></h2> <p data-svelte-h="svelte-kecdvd">If you’ve been building web components for a minute, you’ve probably used the <code>:host</code> selector to style your web components.</p> <p data-svelte-h="svelte-1q1q58">This is a special selector only available inside of the shadow DOM that targets the shadow host.</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <p data-svelte-h="svelte-1sljgmq">Jump back to the code above and toggle the comments on line 13-16. You’ll see that the border gets added around the component. Recomment 13-16 and uncomment lines 25-28. You can see that it applies the same styles. This is because the <code>:host</code> selector and the <code>progress-indicator</code> element selector target the same element.</p> <div class="aside-wrapper svelte-12vh5ck" data-svelte-h="svelte-1bkzujq"><aside>If you want to learn how to build web components by building your own resilient component
		library, why not check out <a href="/">Component Odyssey </a>?</aside> </div> <h2 data-svelte-h="svelte-15jtgfs"><code>:host()</code></h2> <p data-svelte-h="svelte-3oiwkl">The <code>:host()</code> function also targets the host element, but allows the author to apply conditions in the form of additional selectors as an argument.</p> <p data-svelte-h="svelte-etxgon">For instance, you might want to apply styles based on classes or attributes that a consumer has added to the shadow host.</p> <p data-svelte-h="svelte-1wbbhet">You can see this in action by adding/removing/changing the size attribute on the <code>&lt;progress-indicator&gt;</code> element. Try it yourself by uncommenting line 18:</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <h2 data-svelte-h="svelte-w52wzq"><code>:host-context()</code></h2> <p data-svelte-h="svelte-188if5q">This is similar to the previous selector, but instead of the argument being a selector that targets the host element itself, the selector targets the ancestors of the shadow host.</p> <p data-svelte-h="svelte-5jggon">This means that you can change the appearance of the web component based on classes and attributes that are included in the light DOM. One handy use case is to set themes.</p> <p data-svelte-h="svelte-i81nmu">In the example below, you can see that the body element has a <code>data-theme=&quot;dark&quot;</code> attribute, which changes the color of the page’s background. The <code>:host-context</code> looks out for this selector on an ancestor and adjusts its styles accordingly.</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <p data-svelte-h="svelte-r5c1b4">It’s worth noting that the <code>:host-context</code> selector is not supported in all browsers, and it’s not likely to be implemented in Firefox or Safari. Shoutout to <a href="https://front-end.social/@knowler@sunny.garden" rel>Nathan Knowler</a> for pointing this out to me.</p>
]]></content>
<pubDate>Wed, 17 Jul 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/08-refactoring-a-js-driven-scroll-animation-to-css</guid>
<title>Refactoring a scroll-driven animation from JavaScript to CSS</title>
<link>https://www.component-odyssey.com/articles/08-refactoring-a-js-driven-scroll-animation-to-css</link>
<description>Cut down on the amount of JavaScript you ship by refactoring a scroll-linked animation from JavaScript to CSS.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-24lk9o">Scroll-linked animations are all the rage in the frontend space right now, in no part due to the increased availability of a native CSS way to link animations to scroll progress. I’ve even used them on this site. The progress indicator at the top-left of the screen was <a href="/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator">built using heaps of cutting-edge CSS features</a>.</p> <p data-svelte-h="svelte-1vwm11l">Scroll-linked animations aren’t new though, what <strong>is</strong> new is the increasing support for implementing this cool visual flourish without a line of JavaScript. Not everyone has the pleasure of building fun and engaging user interfaces in a greenfield project. What if you already have a scroll-linked animation driven by JS? In this article, I’ll run through how to migrate a scroll-linked animation driven by JavaScript, to use the new CSS properties.</p> <div class="aside-wrapper svelte-12vh5ck" data-svelte-h="svelte-1bkzujq"><aside>If you want to learn how to build web components by building your own resilient component
		library, why not check out <a href="/">Component Odyssey </a>?</aside> </div> <p data-svelte-h="svelte-mejddw">We’ll do this by migrating the following animation from a JavaScript implementation to use the new CSS properties.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/08-refactoring-a-js-driven-scroll-animation-to-css/starter-animation.gif" alt="home-animation-simple-starter.gif"></div> </p> <p data-svelte-h="svelte-1kkbccn">This animation is driven using JavaScript. The general logic is like so:</p> <ol data-svelte-h="svelte-1mybwzy"><li>When the page loads, I attach a “scroll” event listener to the window</li> <li>Whenever the user scrolls, the event handler fires which:<ol><li>iterates over the list of target elements.</li> <li>checks to see if a target element is inside of the visible window</li> <li>If it is, it determines the current state of the animation</li> <li>it sets the progress value to a CSS variable, which is used to set the target element’s styles.</li></ol></li></ol> <p data-svelte-h="svelte-14z03ec">It sounds a bit much, so here’s a code sandbox with the running code. Feel free to explore and play with the code yourself.</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <aside data-svelte-h="svelte-8b7pg0"><p>The code inside of <code>starter.js</code> shows the web component that contains the animation logic written in JavaScript. The code inside of <code>finisher.js</code> shows the web component that contains the animation logic written in CSS.</p></aside> <p data-svelte-h="svelte-1i7jncy">Let’s dive deeper into the code:</p> <p data-svelte-h="svelte-1hchvi">The page is set up as a simple HTML page which renders a web component. The web component contains the encapsulated logic for the animatable element. Don’t worry, you don’t need to understand web components to follow along!</p> <p data-svelte-h="svelte-1mhi655">Here’s the markup for the animatable element:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>container<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>row<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square-wrapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square one<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square-wrapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square two<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>row<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square-wrapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square three<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square-wrapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square four<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1fhaz3l">(I’ll explain why the <code>.square</code> elements are wrapped in a <code>.square-wrapper</code> div later on)</p> <p data-svelte-h="svelte-1t0ftg6">This renders the following to the page:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/08-refactoring-a-js-driven-scroll-animation-to-css/rendered-html.png" alt="four grey blocks rendered to the page"></div> </p> <p data-svelte-h="svelte-12t8bli">Most of the CSS is strictly visual, but each square has a couple of properties whose values are linked to the current scroll position:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.square.one</span> <span class="token punctuation">&#123;</span>
	<span class="token property">opacity</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translateX</span><span class="token punctuation">(</span><span class="token function">calc</span><span class="token punctuation">(</span>-50px + <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span> * 50px<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.square.two</span> <span class="token punctuation">&#123;</span>
	<span class="token property">opacity</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translateY</span><span class="token punctuation">(</span><span class="token function">calc</span><span class="token punctuation">(</span>50px - <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span> * 50px<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.square.three</span> <span class="token punctuation">&#123;</span>
	<span class="token property">opacity</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translateY</span><span class="token punctuation">(</span><span class="token function">calc</span><span class="token punctuation">(</span>-50px + <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span> * 50px<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.square.four</span> <span class="token punctuation">&#123;</span>
	<span class="token property">opacity</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translateX</span><span class="token punctuation">(</span><span class="token function">calc</span><span class="token punctuation">(</span>50px - <span class="token function">var</span><span class="token punctuation">(</span>--animation-position<span class="token punctuation">)</span> * 50px<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-rcpz7v">The value for <code>opacity</code> is the value of a variable set inside of the scroll event handler. As for the transform property, it uses the animation position to move the element from its starting position to its ending position.</p> <p data-svelte-h="svelte-1vn9dty">Now let’s take a look at the JavaScript. Note, I’ve written it in pseudo code to avoid filling the example with too much detail.</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">const</span> <span class="token function-variable function">#onScroll</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">const</span> elementsToAnimate <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelectorAll</span><span class="token punctuation">(</span><span class="token string">'.square'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	elementsToAnimate<span class="token punctuation">.</span><span class="token function">forEach</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">el</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
		<span class="token comment">// Entry Animation range is between 70% and 90% of the viewport height</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">elIsWithinEntryAnimationRange</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      el<span class="token punctuation">.</span>style<span class="token punctuation">.</span><span class="token function">setProperty</span><span class="token punctuation">(</span><span class="token string">'--animation-position'</span><span class="token punctuation">,</span> <span class="token function">getAnimationPosition</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
		<span class="token comment">// Exit Animation range is between 10% and 30% of the viewport height</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">elIsWithinExitAnimationRange</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      el<span class="token punctuation">.</span>style<span class="token punctuation">.</span><span class="token function">setProperty</span><span class="token punctuation">(</span><span class="token string">'--animation-position'</span><span class="token punctuation">,</span> <span class="token function">getAnimationPosition</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
		<span class="token comment">// The animation is in its complete state between 30% and 70% of the viewport height</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">elIsWithinVisibleRange</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      el<span class="token punctuation">.</span>style<span class="token punctuation">.</span><span class="token function">setProperty</span><span class="token punctuation">(</span><span class="token string">'--animation-position'</span><span class="token punctuation">,</span> <span class="token number">1</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
		<span class="token comment">// The element is in its idle state when below 10% or above 90% of the viewport height</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token function">elIsOutsideVisibleRange</span><span class="token punctuation">(</span>el<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      el<span class="token punctuation">.</span>style<span class="token punctuation">.</span><span class="token function">setProperty</span><span class="token punctuation">(</span><span class="token string">'--animation-position'</span><span class="token punctuation">,</span> <span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span><span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span>
<p>window<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">‘scroll’</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>#onScroll<span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-ekkv1u">The full implementation requires ~50 lines of code. In addition to the amount of code I’ve written, there other downsides to this approach:</p> <ol data-svelte-h="svelte-oyn0vc"><li>The code isn’t portable. I need to write bespoke code for any scroll linked animations.</li> <li>The code uses JavaScript, which is fine, but we should strive to reduce the amount we’re shipping to our users</li> <li>The <code>onScroll</code> function runs every time the user scrolls, which can be several times a second. If you’ve set multiple computationally expensive scroll handlers, your users may notice a drop in performance.</li> <li>The logic can get complex. I need to add the guards myself to ensure that the animation only works within certain scroll ranges. I also need to compute the intermediate animation values myself. There are heaps of other edge cases I haven’t accommodated for either.</li></ol> <aside data-svelte-h="svelte-87aztq"><p>Note: In fact, one major edge case is having to calculate the the correct animation position for an element that has its position adjusted via the <code>transform</code> property. It’s why each square is being wrapped in a <code>.square-wrapper</code> div.</p></aside> <h2 data-svelte-h="svelte-he39ho">Migrating over to CSS</h2> <p data-svelte-h="svelte-hqk4ng">Let’s simplify the DOM by removing redundant element.</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation"><</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">”</span>container<span class="token punctuation">”</span></span><span class="token punctuation">></span></span></p>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>outer<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>row<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square one<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square two<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>row<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square three<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>square four<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-14vuxht">The first step is to remove all of the JavaScript, including the event listener. You can replace it with a simple keyframe animation:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token atrule"><span class="token rule">@keyframes</span> appear</span> <span class="token punctuation">&#123;</span>
	<span class="token selector">from,
	to</span> <span class="token punctuation">&#123;</span>
		<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translateX</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--fade-in-start-pos-x<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token function">translateY</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--fade-in-start-pos-y<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token property">opacity</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token selector">25%,
	75%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">translate</span><span class="token punctuation">(</span>0px<span class="token punctuation">,</span> 0px<span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token property">opacity</span><span class="token punctuation">:</span> 1<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1mx87of">In short the animation does the following:</p> <ul data-svelte-h="svelte-1n490yh"><li>The target element appears during the first 25% of the animation</li> <li>From 25%-75% of the animation, the target element will just sit there and look pretty</li> <li>The target element exits during the last 75% of the animation</li></ul> <p data-svelte-h="svelte-35d9qa">The <code>--fade-in-start-pos-x</code> and <code>--fade-in-start-pos-y</code> variables are set inside of the <code>.square</code> selectors, to give each square control over its starting position.</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.square.one</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--fade-in-start-pos-x</span><span class="token punctuation">:</span> -50px<span class="token punctuation">;</span>
	<span class="token property">--fade-in-start-pos-y</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.square.two</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--fade-in-start-pos-x</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
	<span class="token property">--fade-in-start-pos-y</span><span class="token punctuation">:</span> 50px<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.square.three</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--fade-in-start-pos-x</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
	<span class="token property">--fade-in-start-pos-y</span><span class="token punctuation">:</span> -50px<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.square.four</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--fade-in-start-pos-x</span><span class="token punctuation">:</span> 50px<span class="token punctuation">;</span>
	<span class="token property">--fade-in-start-pos-y</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-hs6pii">The very last thing I need to do is link the animation to the scroll progress. I do this with the following three lines of code:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.square</span> <span class="token punctuation">&#123;</span>
	<span class="token property">animation</span><span class="token punctuation">:</span> appear linear both<span class="token punctuation">;</span>
	<span class="token property">animation-timeline</span><span class="token punctuation">:</span> <span class="token function">view</span><span class="token punctuation">(</span>block<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">animation-range</span><span class="token punctuation">:</span> contain 10% contain 90%<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1s5k1up">Let’s step through each line individually:</p> <h3 data-svelte-h="svelte-z2b7j1"><code>animation</code></h3> <p data-svelte-h="svelte-34aumk"><code>animation: appear linear both</code></p> <p data-svelte-h="svelte-r7s0y2">This is a shorthand animation property that:</p> <ul data-svelte-h="svelte-149c35w"><li>specifies the name of the keyframes rule we want to use, <code>appear</code></li> <li>specifies the easing function, <code>linear</code>,</li> <li>specifies the fill mode, <code>both</code></li></ul> <p data-svelte-h="svelte-1rlza2m"><code>fill-mode: both</code> ensures the start and end styles of the animation persist on the element after the animation has finished completing. <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode" rel>You can learn more about fill-mode on MDN</a>.</p> <h3 data-svelte-h="svelte-1bsdomz"><code>animation-timeline</code></h3> <p data-svelte-h="svelte-x3gxa"><code>animation-timeline: view();</code></p> <p data-svelte-h="svelte-1dqn8xc">This single line of CSS has heaps to unpack.</p> <p data-svelte-h="svelte-1jjrb2t">For starters, this CSS property accepts two different functions, <code>scroll()</code> and <code>view()</code>.</p> <p data-svelte-h="svelte-1q2b91d"><code>scroll()</code> links the animation to the scroll progress of an ancestor element. By default, this ancestor element is the nearest ancestor that has scroll bars.</p> <p data-svelte-h="svelte-cwerlv"><code>view()</code> links the animation progress to the visibility of the target element.</p> <h3 data-svelte-h="svelte-3x4vtt"><code>animation-range</code></h3> <p data-svelte-h="svelte-7qpdyc">Finally, the last line of CSS gives fine control over when the animation begins and ends. By default the animation begins when the top of the target element enters the viewport and ends when the bottom of the element exits the viewport.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/08-refactoring-a-js-driven-scroll-animation-to-css/default-duration.png" alt="The target element is only 30% inside of the vioewport, and so it's animation has only completed 30%"></div> </p> <p data-svelte-h="svelte-1du61ah">In my case, I want to start the animation only when the entire element is <em>contained</em> within the viewport. The same goes for the exit animation, it should complete the moment the element reaches the end of the viewport.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/08-refactoring-a-js-driven-scroll-animation-to-css/contain-duration.png" alt="There's a buffer within the viewport, where the animation only triggers when an element has passed it. In this case the element is fully contained within the viewport, but its only passed 20% of the threshold, meaning the animation has only completed 20%"></div> </p> <p data-svelte-h="svelte-s6ipgw">The shaded green section shows the threshold the element needs to pass through before the animation begins and ends.</p> <p data-svelte-h="svelte-1m0zmf6">To set this behaviour you need to set animation-range to <code>contain</code>:</p> <p data-svelte-h="svelte-yr0bk0"><code>animation-range: contain;</code></p> <p data-svelte-h="svelte-1tg3gjy">I want to make one more change though. I want to reduce the range of the animation timeline by 10% at the start and at the end of the animation.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/08-refactoring-a-js-driven-scroll-animation-to-css/contain-offset-duration.png" alt="There's a buffer within the viewport, and those buffers have been pulled further intot he viewport an additional 10%"></div> </p> <p data-svelte-h="svelte-xipjzo">In the above image you can see that both <em>contain</em> barriers have been brought inside of the viewport by 10% of the viewport height.</p> <p data-svelte-h="svelte-aq7jvo">This is done by setting the following CSS.</p> <p data-svelte-h="svelte-14l1yth"><code>animation-range: contain 10% 90%</code></p> <p data-svelte-h="svelte-18wln4l">There’s a lot to take in, especially when it comes to <code>animation-range</code> property. I recommend checking out Bramus’s <a href="https://scroll-driven-animations.style/tools/view-timeline/ranges/#range-start-name=cover&range-start-percentage=0&range-end-name=cover&range-end-percentage=100&view-timeline-axis=block&view-timeline-inset=0&subject-size=smaller&subject-animation=reveal&interactivity=clicktodrag&show-areas=yes&show-fromto=yes&show-labels=yes" rel>amazing visualiser</a> to help acquaint you with its capabilities</p> <p data-svelte-h="svelte-ef8r8z">With all that done, the animation should work nicely</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="/images/articles/08-refactoring-a-js-driven-scroll-animation-to-css/finisher-animation.gif" alt="home-animation-simple-finisher.gif"></div> </p> <aside data-svelte-h="svelte-1bhh7by">Note: You may need to tweak some of the offset and easing values to get an equivalent animation experience.</aside> <p data-svelte-h="svelte-jz8zx0">And we’ve achieved this by ripping out dozens of lines of JS and adding a handful of lines of CSS.</p>
]]></content>
<pubDate>Mon, 10 Jun 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/07-convince-your-boss</guid>
<title>Convince Your Boss</title>
<link>https://www.component-odyssey.com/articles/07-convince-your-boss</link>
<description>Convince your boss that Component Odyssey is a worthy investment in your and your team’s development.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-1ixlv8r">To help employees upskill, many companies have an education budget to cover things like books, conferences, and courses.</p> <p data-svelte-h="svelte-k9gyi5">If you’d like your boss to cover the cost of Component Odyssey, use the following template to help convince them that Component Odyssey is a worthy investment in your and your team’s development.</p> <p data-svelte-h="svelte-mhz2i4">Before copying and pasting the template to your boss, consider the following:</p> <ul data-svelte-h="svelte-17gy185"><li>How can you relate the benefits of the course directly to a project?</li> <li>How can you relate the benefits of the course to the overall goals of your team/company?</li></ul> <p data-svelte-h="svelte-ifajqv">Feel free to tweak parts of the template to communicate the benefits of Component Odyssey that are most relevant to your situation.</p> <h2 data-svelte-h="svelte-1s9gvss">Template</h2> <p data-svelte-h="svelte-rndcvz">Hey <code>{BossName}</code>,</p> <p data-svelte-h="svelte-eitsmb">I recently came across an online web development course called Component Odyssey, which focuses on building reusable component libraries. I believe this course would be a valuable investment for both my growth and the team’s long-term efficiency. Could you consider purchasing this course as part of my ongoing professional development?</p> <h2 data-svelte-h="svelte-1vwx63a">Course Overview</h2> <p data-svelte-h="svelte-m258ke">This course offers a comprehensive guide on building a reusable component library from scratch. It covers everything from writing components to publishing them for others to use. The course teaches how to build reusable components compatible with any web development framework, making our codebase more maintainable and easier to scale.</p> <h2 data-svelte-h="svelte-1x7lr6r">Key Benefits</h2> <ul data-svelte-h="svelte-1v2uqna"><li>The course focuses on native browser technologies, which will make me a more well-rounded web developer.</li> <li>It teaches how to build components that work with any web framework, allowing us to use different UI frameworks without rewriting our entire component library.</li> <li>By building a component library, we can reuse code across multiple projects, leading to huge savings in time and resources in the long run.</li></ul> <h2 data-svelte-h="svelte-lt28jw">Costs</h2> <p data-svelte-h="svelte-1li2no">The course has a one-time cost of $99, including tax. I’m convinced it’s a great opportunity for professional growth and will positively impact our team’s capabilities.</p> <p data-svelte-h="svelte-1ombcgc">I appreciate your consideration, and I’m looking forward to hearing your thoughts</p> <p data-svelte-h="svelte-6zulfd">Best regards, <code>{YourName}</code></p> <p data-svelte-h="svelte-17u0fbr">P.S. I think this course would also be valuable for other members of the team, especially <code>{ColleagueOrTeamNames}</code>. We can reach out to <a href="mailto:hello@component-odyssey.com">hello@component-odyssey.com</a> for some pretty sizeable bulk discounts.</p>
]]></content>
<pubDate>Thu, 30 May 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/06-the-dilemmas-youll-face-when-creating-a-component-library</guid>
<title>The Dilemmas You'll Face When Creating a Component Library</title>
<link>https://www.component-odyssey.com/articles/06-the-dilemmas-youll-face-when-creating-a-component-library</link>
<description>Building a component library can be complicated, let's explore some of the dilemmas you'll face when creating one.</description>
<content type="html"><![CDATA[
 <h2 data-svelte-h="svelte-x1wuce">The Dilemmas You’ll Face When Creating a Component Library</h2> <p data-svelte-h="svelte-3z3f04">Building a component library is a challenging and rewarding experience, but there’s more to it than writing great-looking components. At every step of the journey, you’ll need to make choices to ensure your library is built appropriately for its intended audience.</p> <div class="aside-wrapper svelte-12vh5ck" data-svelte-h="svelte-1bkzujq"><aside>If you want to learn how to build web components by building your own resilient component
		library, why not check out <a href="/">Component Odyssey </a>?</aside> </div> <p data-svelte-h="svelte-zcb9dq">When building your library, you’ll need to consider the following dilemmas:</p> <ul data-svelte-h="svelte-xr6fnj"><li>Should I write vanilla web components or use a library?</li> <li>Should I export my library as a single package or as scoped packages?</li> <li>How should I structure the repo of my library?</li> <li>Should I use tooling to build and/or bundle my library?</li> <li>What optimizations do I need to run?</li> <li>How can I safely publish my library?</li> <li>What should my library’s testing strategy be?</li> <li>How to write documentation for my component library</li></ul> <p data-svelte-h="svelte-uyfbz3">The full article is posted on GitHub as a way to make it a more collaborative experience. I hope others can share their experiences and make the article more comprehensive.</p> <p data-svelte-h="svelte-1dtbv3p"><a href="https://github.com/andrico1234/the-dilemmas-youll-face" rel>Read the full article on GitHub</a></p>
]]></content>
<pubDate>Sun, 12 May 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator</guid>
<title>Using Heaps of Cutting Edge CSS Features to Build a Progress Indicator</title>
<link>https://www.component-odyssey.com/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator</link>
<description>Learn how to use cutting edge CSS features like animation-timeline, color-mix, and trigonometric functions to build a sleek progress indicator.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-288m1m">For the last 7 months, I’ve had my head down building Component Odyssey. It’s been a richly fulfilling project and I’m eager for people to take the course and learn heaps about building component libraries using web components.</p> <p data-svelte-h="svelte-1eqr21o">I’ve seen some incredible demos over the past year and wanted to bite my teeth into some of these cool new features. So I used some downtime over the Christmas period to cram tons of new CSS features into a lesson progress indicator for the Component Odyssey platform. The result is the following progress indicator that shows how much of the page the user has scrolled:</p> <div class="article__image" data-svelte-h="svelte-1etzxum"><img class="mid-size-image" alt="the fully completed progress indicator as it exists on Component Odyssey" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/component-odyssey-indicator.gif"></div> <p data-svelte-h="svelte-18inbq4">Building it gave me some exposure to some of the latest CSS features like:</p> <ul data-svelte-h="svelte-b8pesw"><li><code>animation-timeline: scroll()</code></li> <li>CSS trig functions, <code>sin()</code> and <code>cos()</code></li> <li><code>color-mix()</code></li> <li>the <code>@property</code> at-rule</li></ul> <p data-svelte-h="svelte-bkham5">I know the risks of building something with a particular tool in mind. As the saying goes “When all you have is a hammer, then something something nails”</p> <p data-svelte-h="svelte-1xnku0t">Yes, I have a hammer, and I’m going to smash the walls down with it.</p> <div class="aside-wrapper svelte-12vh5ck" data-svelte-h="svelte-1bkzujq"><aside>If you want to learn how to build web components by building your own resilient component
		library, why not check out <a href="/">Component Odyssey </a>?</aside> </div> <p data-svelte-h="svelte-dzvhq3">In this article, I’ll run through how to create a pared-down version of this swanky progress animation while still using all of the CSS features mentioned above. I’ll also show you how to gracefully handle browsers that don’t support these features through <strong>progressive enhancement</strong>.</p> <p data-svelte-h="svelte-64vm9q">If you want to follow along, then it’s best to use the latest versions of Chrome or Safari, currently Firefox doesn’t have general support for properties like <code>animation-timeline</code>. Get started by jumping into the <a href="https://codepen.io/andrico1234/pen/WNmQrGK" rel>starter Codepen</a>.</p> <p data-svelte-h="svelte-1gvidgp">If you want to peruse the finished code, you can <a href="https://codepen.io/andrico1234/pen/qBvdjLd" rel>check it out here.</a></p> <h2 data-svelte-h="svelte-c1n3wm">Creating the markup</h2> <p data-svelte-h="svelte-ouc5cy">I’ve already provided a little markup to simulate a page with enough content that you need to scroll to get to the bottom. To get started creating the progress indicator, you’ll need to add some more markup.</p> <p data-svelte-h="svelte-1bx3p5w">The markup itself is really simple, we’ll only need to create 3 div elements.</p> <p data-svelte-h="svelte-1kc3pk9">The outer element is responsible for the positioning and layout of the loader. We’ll give this a class of <code>wrapper</code>.</p> <p data-svelte-h="svelte-19iamqg">The middle element is responsible for rendering the track to the screen. We’ll give this element a class of <code>progress</code>. We’ll later use a <code>::after</code> pseudo-element to create the thumb.</p> <p data-svelte-h="svelte-7tpvun">The innermost element will be used to create the circular hole in the middle, making the indicator look like a low-calorie doughnut. This will have a class of <code>inner</code>.</p> <p data-svelte-h="svelte-ykzu18">Take a look at the following if you need a hand visualising the structure:</p> <img alt="A visual representation of the information outlined above" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/markup-structure.png"> <p data-svelte-h="svelte-16ac1f0">Provide the following markup as the first child of the <code>main</code> element create the following markup:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>wrapper<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>progress<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>inner<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-k4bvvr">You’ll also need to apply the following styles to give the markup a base visual experience:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.wrapper</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--size</span><span class="token punctuation">:</span> 80px<span class="token punctuation">;</span>
	<span class="token property">position</span><span class="token punctuation">:</span> fixed<span class="token punctuation">;</span>
	<span class="token property">width</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--size<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">aspect-ratio</span><span class="token punctuation">:</span> 1/1<span class="token punctuation">;</span>
	<span class="token property">top</span><span class="token punctuation">:</span> 24px<span class="token punctuation">;</span>
	<span class="token property">left</span><span class="token punctuation">:</span> 24px<span class="token punctuation">;</span>
	<span class="token property">display</span><span class="token punctuation">:</span> flex<span class="token punctuation">;</span>
	<span class="token property">align-items</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span>
	<span class="token property">justify-content</span><span class="token punctuation">:</span> center<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.progress</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--track-size</span><span class="token punctuation">:</span> 16px<span class="token punctuation">;</span>
	<span class="token property">width</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--size<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">aspect-ratio</span><span class="token punctuation">:</span> 1/1<span class="token punctuation">;</span>
	<span class="token property">border-radius</span><span class="token punctuation">:</span> 50%<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token selector">.inner</span> <span class="token punctuation">&#123;</span>
	<span class="token property">position</span><span class="token punctuation">:</span> absolute<span class="token punctuation">;</span>
	<span class="token property">width</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span>100% - <span class="token function">var</span><span class="token punctuation">(</span>--track-size<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">aspect-ratio</span><span class="token punctuation">:</span> 1/1<span class="token punctuation">;</span>
	<span class="token property">background</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--background-color<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">border-radius</span><span class="token punctuation">:</span> 50%<span class="token punctuation">;</span>
	<span class="token property">top</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
	<span class="token property">left</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
	<span class="token property">right</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
	<span class="token property">bottom</span><span class="token punctuation">:</span> 0<span class="token punctuation">;</span>
	<span class="token property">margin</span><span class="token punctuation">:</span> auto<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1qxwe1u">Most of the CSS here shouldn’t come as a shock to you, so I won’t go over it line by line, but I will touch on some of the more interesting bits.</p> <p data-svelte-h="svelte-tdkq8x">In <code>.wrapper</code> we’re fixing the element to the top left of the screen, and using flexbox to center the children horizontally and vertically.</p> <aside data-svelte-h="svelte-2rwer7">💡 I learnt that if you want an element to share the same value for both its width and height, you just set the width and use `aspect-ratio: 1/1`. The browser will implicitly set the height. This is a neat trick because you won’t have to define the same value twice, and it makes it easier to guarantee that the width and the height share the same value.</aside> <p data-svelte-h="svelte-8avkk3">As for the <code>.inner</code> element, I’ve used a mix of absolute positioning and the <code>margin: auto</code> to center it in the middle of the <code>.progress</code> element. We’ve also deducted the <code>--track-size</code> from the full width of the container, to ensure that it’s correctly positioned over the <code>.progress</code> element.</p> <p data-svelte-h="svelte-1hq8kt3">You won’t be able to see anything just yet, but if you add a temporary <code>background-color: red</code> to the <code>.progress</code> element, it should render as follows:</p> <div class="article__image" data-svelte-h="svelte-48mkc9"><img alt="a basic doughnut shaped indacator without any animation" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/basic-ui.png"></div> <h2 data-svelte-h="svelte-kftc1b">Creating an animated progress indicator</h2> <p data-svelte-h="svelte-p0o6f">Creating a scroll-driven animation of this kind requires a lot of new CSS features that you may have not used before. Instead of learning everything all at once, we’ll start by decoupling the animation from the scrolling mechanics.</p> <p data-svelte-h="svelte-1t5xobm">That way, by the end of this section, you should have the following animation that plays automatically:</p> <div class="article__image" data-svelte-h="svelte-1ch1lpb"><img alt="A progress indicator playing automatically in an infinite loop" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/infinite-loading.gif"></div> <p data-svelte-h="svelte-1yao2ae">We’ll start by creating a new animation called <code>load</code>:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token atrule"><span class="token rule">@keyframes</span> load</span> <span class="token punctuation">&#123;</span>
	<span class="token selector">0%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">--progress</span><span class="token punctuation">:</span> 0%<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token selector">100%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">--progress</span><span class="token punctuation">:</span> 100%<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-s1x5i1">All this does is move the progress along from 0 to 100 over the course of the animation. In your <code>.progress</code> rule, add the following CSS properties:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.progress</span> <span class="token punctuation">&#123;</span>
	# Existing rules
	<span class="token property">animation</span><span class="token punctuation">:</span> load linear 1s infinite<span class="token punctuation">;</span>
	<span class="token property">background</span><span class="token punctuation">:</span> <span class="token function">conic-gradient</span><span class="token punctuation">(</span>
		from 0deg at 50% 50%<span class="token punctuation">,</span>
		<span class="token function">var</span><span class="token punctuation">(</span>--red<span class="token punctuation">)</span> <span class="token function">var</span><span class="token punctuation">(</span>--progress<span class="token punctuation">)</span><span class="token punctuation">,</span>
		<span class="token function">var</span><span class="token punctuation">(</span>--black<span class="token punctuation">)</span> <span class="token function">var</span><span class="token punctuation">(</span>--progress<span class="token punctuation">)</span>
	<span class="token punctuation">)</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1uosljj">The <code>animation</code> property should be pretty straightforward, but there’s a lot going on with the <code>background</code> rule, so let’s step through it.</p> <p data-svelte-h="svelte-1k7rxie">For starters, we’re using a <code>conic-gradient</code> as it makes it easy for us to animate the background over 360 degrees, in the way shown in the animation above. We’re starting from the <code>0deg</code> position, which is top and center. We’re describing where we want the center of the gradient to be using <code>at 50% 50%</code>.</p> <p data-svelte-h="svelte-1qmombb"><code>conic-gradient(from 0deg at 50% 50%)</code> alone would render something like the following:</p> <div class="article__image" data-svelte-h="svelte-py6w6z"><img alt="A visualisation of a radial gradient starting from the center, like a sonar radar" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/radial-gradient.png"></div> <p data-svelte-h="svelte-msytgo">Hopefully I’ve made it clear why that’s the case.</p> <p data-svelte-h="svelte-1q75u5j">As for the the second and third arguments of the <code>conic-gradient</code> function, we’re linking the <code>--progress</code> variable (which is being calculated via the <code>load</code> animation) to the two colors. The <code>--red</code> is used to denote the completed progress, while the <code>--black</code> is used to denote the remaining position. It might be confusing why they share the same <code>--progress</code> value. The <code>--progress</code> value for the <code>--red</code> value denotes where the gradient stop ends, while the <code>--progress</code> value for the <code>--black</code> denotes where the gradient stop begins. Because it’s the last stop on the gradient, it’s implied that it ends at 100%. By setting the same <code>--progress</code> value to both stops in the gradient, we create a hard transition between the two colors. Without doing so, our progress indicator (with a <code>--progress</code> value set to 16%) would look like this:</p> <div class="article__image" data-svelte-h="svelte-1h25xj"><img alt="The progress indicator where the color gradient goes slowly from red to black" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/radial-gradient-no-stop.png"></div> <p data-svelte-h="svelte-nefbvr">Now, something strange is probably happening. Instead of your progress indicator transitioning gracefully across the entire perimeter of the circle, it’s instead flashing between the black and red.</p> <p data-svelte-h="svelte-10egb3p">Why is this happening?</p> <p data-svelte-h="svelte-1bogh63">This is because we’re making the browser interpolate between percentage values, which is something it can’t do automatically. Even though we’ve given the <code>--progress</code> variable a percentage value, the browser doesn’t assume that it’s always going to be a percentage value.</p> <p data-svelte-h="svelte-u6xxxg">We can solve this by telling the browser that <code>--progress</code> will always be a percentage value. We can do this by explicitly defining the <code>--progress</code> property using the <code>@property</code> CSS rule. Just add the following to the top-level of your CSS:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token atrule"><span class="token rule">@property</span> --progress</span> <span class="token punctuation">&#123;</span>
	<span class="token property">syntax</span><span class="token punctuation">:</span> <span class="token string">'&lt;percentage>'</span><span class="token punctuation">;</span>
	<span class="token property">inherits</span><span class="token punctuation">:</span> false<span class="token punctuation">;</span>
	<span class="token property">initial-value</span><span class="token punctuation">:</span> 0%<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-7r5la7">We’re telling the browser that <code>--progress</code> should only support percentage values and that the initial value is 0%. We’re also not interested in having the custom element inherit its value.</p> <p data-svelte-h="svelte-ril850">Finally, I don’t quite like the use of the <code>--black</code> variable to signify empty progress. It looks too stark. I’d like to create a lighter shade created from the black to ensure a more homogenous visual palette. This is something we can easily achieve using the <code>color-mix()</code> CSS function.</p> <p data-svelte-h="svelte-b7bezq">Jump back up to the <code>:root</code> CSS rule and add the following variable:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">:root</span> <span class="token punctuation">&#123;</span>
	# your other CSS variables
	<span class="token property">--grey</span><span class="token punctuation">:</span> <span class="token function">color-mix</span><span class="token punctuation">(</span>in srgb<span class="token punctuation">,</span> <span class="token function">var</span><span class="token punctuation">(</span>--black<span class="token punctuation">)</span><span class="token punctuation">,</span> transparent 60%<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-ufvswq">The <code>color-mix</code> function lets us mix two colors together. In this case, we’re mixing the color stored in our black variable with some transparency, which will result in a partially see-through grey color. You’ll need to replace the reference to the <code>--black</code> variable in the <code>conic-gradient</code> function with <code>--grey</code> to see the color change in effect.</p> <p data-svelte-h="svelte-1ozvjgg">Now that we’ve defined our custom property, the browser will be able to interpolate the correct values during the entire animation, so it should now transition smoothly from start to finish.</p> <div class="article__image" data-svelte-h="svelte-1ch1lpb"><img alt="A progress indicator playing automatically in an infinite loop" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/infinite-loading.gif"></div> <h2 data-svelte-h="svelte-ml3esm">Scroll driven animations</h2> <p data-svelte-h="svelte-1akhwci">The next stage of our animation journey is to tie our animation to the scrolling of the page.</p> <p data-svelte-h="svelte-khs1x">This should only take us a couple of lines of CSS.</p> <p data-svelte-h="svelte-1wx7ll4">You’ll need to do two things. First adjust the <code>animation</code> property in your <code>.progress</code> class to remove the <code>infinite</code> value, and to change the duration from <code>1s</code> to <code>1ms</code>. We can’t remove the value altogether because Firefox needs it for scroll animations to work.</p> <p data-svelte-h="svelte-zt0edc">Next update your <code>.progress</code> class to include the following</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.progress</span> <span class="token punctuation">&#123;</span>
  # other CSS properties
	<span class="token property">animation-timeline</span><span class="token punctuation">:</span> <span class="token function">scroll</span><span class="token punctuation">(</span>nearest block<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-13q3lqp">The <code>animation-timeline</code> property tells the browser to tie the progress of the animation with a specific timeline. In this case it’s the scroll timeline, which we specify using the <code>scroll</code> function.</p> <p data-svelte-h="svelte-8mse4f">You can see I’m providing two arguments to <code>scroll()</code>, <code>nearest</code> and <code>block</code>.</p> <p data-svelte-h="svelte-11uy1b">The <code>nearest</code> value is used to tie the animation to the nearest ancestor that has a scrollbar, in this case it’s the document. If you’re certain that you only ever want to tie the animation to the document’s scrollbar, then you can use swap out <code>nearest</code> for <code>root</code> instead.</p> <p data-svelte-h="svelte-1p9nji6">The <code>block</code> property denotes the axis that we want to tie our animation to. For most cases this will be the vertical scrollbar, but for vertical writing modes, this will be the horizontal scrollbar.</p> <p data-svelte-h="svelte-1ffc1nq">Now that you’ve hooked up the animation to your page’s scroll, you should be able to scroll up and down the page and watch how your animation changes accordingly.</p> <img alt="The basic progress indicator whose animation is tied to the progress of the page scroll" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/progress-complete.gif"> <h2 data-svelte-h="svelte-1dn6d9r">Progressively enhancing your scroll animation</h2> <p data-svelte-h="svelte-1t28coz">While it’s exciting to use these new features in the browser, the <code>animation-timeline</code> property doesn’t have universal support across browsers yet. It’s still very new in Chrome, and it’s only available in Firefox behind a feature flag. If you try opening the code in Firefox, you’ll notice that the progress ring just appears with a finished animation.</p> <p data-svelte-h="svelte-1gboq85">In cases like this, it’s important to set up a solid base experience for all browsers, and then <em>progressively enhance</em> your webpage with the newer features on compatible browsers. Because the progress indicator isn’t critical for the application to function, we can just hide it away if the browser doesn’t support the <code>animation-timeline</code> property.</p> <p data-svelte-h="svelte-1vu3ryg">We can do this by moving our <code>.wrapper</code>, <code>.progress</code>, and <code>.inner</code> classes within CSS’s <code>@supports</code> at-rule, like so:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token atrule"><span class="token rule">@supports</span> <span class="token punctuation">(</span><span class="token property">animation-timeline</span><span class="token punctuation">:</span> <span class="token function">scroll</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span></span> <span class="token punctuation">&#123;</span>
	<span class="token selector">.wrapper</span> <span class="token punctuation">&#123;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token selector">.progress</span> <span class="token punctuation">&#123;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token selector">.inner</span> <span class="token punctuation">&#123;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1eswyg1">Doing so ensures that if the browser doesn’t support <code>scroll()</code>, then it will ignore all of the styles contained within the rule.</p> <h2 data-svelte-h="svelte-1sgw3ip">Adding the indicator thumb</h2> <p data-svelte-h="svelte-2m7kmw">The final thing for us to add is a cool little indicator thumb, to both give our progress indicator a little more visual interest and to also let us play with the swanky CSS trigonometric functions.</p> <p data-svelte-h="svelte-9fqclh">To create the indicator thumb, start by writing the following CSS inside of the <code>@supports</code> block:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.progress::after</span> <span class="token punctuation">&#123;</span>
	<span class="token property">--radius</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--size<span class="token punctuation">)</span> / 2<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">--track-offset</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--track-size<span class="token punctuation">)</span> / 4<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">content</span><span class="token punctuation">:</span> <span class="token string">''</span><span class="token punctuation">;</span>
	<span class="token property">position</span><span class="token punctuation">:</span> absolute<span class="token punctuation">;</span>
	<span class="token property">aspect-ratio</span><span class="token punctuation">:</span> 1/1<span class="token punctuation">;</span>
	<span class="token property">width</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--track-size<span class="token punctuation">)</span> / 2<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">background</span><span class="token punctuation">:</span> <span class="token function">var</span><span class="token punctuation">(</span>--red-dark<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">border-radius</span><span class="token punctuation">:</span> 50%<span class="token punctuation">;</span>
	<span class="token property">left</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span>50% - <span class="token function">var</span><span class="token punctuation">(</span>--track-offset<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">top</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span>50% - <span class="token function">var</span><span class="token punctuation">(</span>--track-offset<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token property">transform</span><span class="token punctuation">:</span> <span class="token function">scale</span><span class="token punctuation">(</span>1.5<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-8yptli">This creates a new pseudo-element off of the <code>.progress</code> class, and gives it it’s visual appearance. Once added, the indicator thumb should live in the center progress element. We’re using the <code>--track-offset</code> variable to position the thumb correctly by taking into consideration the dimensions of the track.</p> <aside data-svelte-h="svelte-1f79hrp">⚠️ I’m also increasing the size of the thumb to using `scale()` so that its size in the DOM is still relative to the `--size` variable. This just means a little less maths for us to worry about when setting the value for `--track-offset`. Using `scale()` makes it easy to change the size of the element without causing a shift in the DOM.</aside> <p data-svelte-h="svelte-169rrzu">The next step is to use the <code>color-mix()</code> function again to create a dark red from the base red color. Add the following to your <code>:root</code> rule.</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">:root</span> <span class="token punctuation">&#123;</span>
	# your other CSS variables
	<span class="token property">--red-dark</span><span class="token punctuation">:</span> <span class="token function">color-mix</span><span class="token punctuation">(</span>in srgb<span class="token punctuation">,</span> <span class="token function">var</span><span class="token punctuation">(</span>--red<span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token function">var</span><span class="token punctuation">(</span>--black<span class="token punctuation">)</span> 60%<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1h5xqdf">Your progress indicator should look less like a UI widget and more like a dartboard:</p> <div class="article__image" data-svelte-h="svelte-na594"><img alt="the thumb is in the center of the progress indicator" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/bullseye.png"></div> <p data-svelte-h="svelte-1ywvfcp">Let’s position the thumb on to the track.</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.progress::before</span> <span class="token punctuation">&#123;</span>
  # rest of properties
	<span class="token property">translate</span><span class="token punctuation">:</span> <span class="token function">calc</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--radius<span class="token punctuation">)</span> - <span class="token function">var</span><span class="token punctuation">(</span>--track-offset<span class="token punctuation">)</span><span class="token punctuation">)</span> * <span class="token function">cos</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--angle<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
      <span class="token function">calc</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--radius<span class="token punctuation">)</span> - <span class="token function">var</span><span class="token punctuation">(</span>--track-offset<span class="token punctuation">)</span><span class="token punctuation">)</span> * <span class="token function">sin</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--angle<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
</code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-3fz6fv">This is probably the gnarliest piece of CSS in this entire article. It isn’t anywhere near as complex if we break it down in half. Here’s the first half:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token function">calc</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--radius<span class="token punctuation">)</span> - <span class="token function">var</span><span class="token punctuation">(</span>--track-offset<span class="token punctuation">)</span><span class="token punctuation">)</span> * <span class="token function">cos</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--angle<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-4dmfzd">This uses a little trigonometry to calculate the position of the thumb based on the current angle (which will be tied to the scroll progress) and the radius of the circle. The <code>cos()</code> function is used to determine the horizontal value of the position.</p> <p data-svelte-h="svelte-1nliqkj">The second half of the value is identical, except we’re using the <code>sin()</code> function to determine the vertical position of the indicator:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token function">calc</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--radius<span class="token punctuation">)</span> - <span class="token function">var</span><span class="token punctuation">(</span>--track-offset<span class="token punctuation">)</span><span class="token punctuation">)</span> * <span class="token function">sin</span><span class="token punctuation">(</span><span class="token function">var</span><span class="token punctuation">(</span>--angle<span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">)</span></code><!-- HTML_TAG_END --></pre> <aside data-svelte-h="svelte-2k3eg4">⚠️ I’m not going to use this article as an introduction into trigonometry, but I can point you in the direction of some amazing resources:
<li><a href="https://web.dev/articles/css-trig-functions">Trigonometric functions in CSS</a></li> <li><a href="https://tympanus.net/codrops/2021/06/04/trigonometry-in-css-and-javascript-beyond-triangles/">Trigonometric functions in CSS and JavaScript: Beyond Triangles</a></li></aside> <p data-svelte-h="svelte-1swg1t">You may have noticed that I’ve specified a variable, <code>--angle</code> that I haven’t yet defined. Because we’ll be animating the <code>--angle</code> we need to explicitly define it using the <code>@property</code> rule, much like we did for the <code>--progress</code> property. The only difference is that we’ll need to specify a different syntax value. Instead of <code>&lt;percentage&gt;</code> the value will need to be <code>&lt;angle&gt;</code> .</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token atrule"><span class="token rule">@property</span> --angle</span> <span class="token punctuation">&#123;</span>
	<span class="token property">syntax</span><span class="token punctuation">:</span> <span class="token string">'&lt;angle>'</span><span class="token punctuation">;</span>
	<span class="token property">inherits</span><span class="token punctuation">:</span> false<span class="token punctuation">;</span>
	<span class="token property">initial-value</span><span class="token punctuation">:</span> -90deg<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-vjybz5">By setting the initial value to <code>-90deg</code> we ensure that thumb is placed at the 12 o’clock position on the progress indicator.</p> <p data-svelte-h="svelte-10bvfpp">Your indicator should now look like this:</p> <div class="article__image" data-svelte-h="svelte-1g25nl3"><img alt="The thumb is positioned at the top center of the progress indicator" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/positioned-thumb.png"></div> <p data-svelte-h="svelte-eckcfe">The next step is to create the animation for the thumb and then bind the animation timeline to the scroll position of the page.</p> <p data-svelte-h="svelte-1c8616g">Let’s start by creating a new animation:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token atrule"><span class="token rule">@keyframes</span> rotate</span> <span class="token punctuation">&#123;</span>
	<span class="token selector">0%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">--angle</span><span class="token punctuation">:</span> -90deg<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
	<span class="token selector">100%</span> <span class="token punctuation">&#123;</span>
		<span class="token property">--angle</span><span class="token punctuation">:</span> 270deg<span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-z918mz">Over the course of the entire animation, the thumb will rotate 360 degrees, performing a full revolution over the progress element.</p> <p data-svelte-h="svelte-1ihrqt6">Finally we need to add the following two properties to the thumb:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">.progress::after</span> <span class="token punctuation">&#123;</span>
	# other CSS properties
	<span class="token property">animation</span><span class="token punctuation">:</span> rotate linear 1ms<span class="token punctuation">;</span>
	<span class="token property">animation-timeline</span><span class="token punctuation">:</span> <span class="token function">scroll</span><span class="token punctuation">(</span>nearest block<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1efa9be">Doing so applies the rotate animation to our thumb and binds it to the scroll position.</p> <p data-svelte-h="svelte-ojznp5">Everything should now work flawlessly:</p> <img alt="The completed progress indicator UI" src="https://component-odyssey.com/images/articles/05-using-heaps-of-cutting-edge-css-to-build-a-progress-indicator/thumb-complete.gif"> <h2 data-svelte-h="svelte-f5dp01">Wrapping up</h2> <p data-svelte-h="svelte-x959n7">I created this progress indicator specifically to become more familiar with the amazing tools that CSS has shipped in the last couple years. Hopefully you learnt just as much from this lesson as I did making it.</p> <p data-svelte-h="svelte-la2esp">There were other CSS features I wanted to explore, like <code>popover</code> and <code>:has</code> but I couldn’t find a way to fit them in with this animation. If people find this article interesting, I might try and create more little changes to the Component Odyssey platform, using cutting-edge CSS features.</p> <p data-svelte-h="svelte-1pr8sd9">By wary, that because a lot of the CSS features I’ve covered are still very new, check the browser support before using them in production. If they’re not supported in one or more browsers, but you’re desperate to use them, then use a <strong>progressive enhancement</strong> strategy to ensure that those with compatible browsers get the full experience, while still offering users of unsupported browsers a solid baseline experience.</p> <h2 data-svelte-h="svelte-jeimfp">Resources</h2> <p data-svelte-h="svelte-9bvlsg"><a href="https://developer.chrome.com/docs/css-ui/scroll-driven-animations#getting_practical_with_scroll_progress_timelines" rel>Getting practical with scroll progress timelines</a></p> <p data-svelte-h="svelte-12j6ugo"><a href="https://dev.to/afif/we-can-finally-animate-css-gradient-kdk" rel>We can finally animate css gradients</a></p> <p data-svelte-h="svelte-6omyk5"><a href="https://codepen.io/LukyVj/pen/rNqvowZ" rel>Fitness inspired loaders</a></p> <p data-svelte-h="svelte-rzsuf5"><a href="https://drafts.css-houdini.org/css-properties-values-api-1/#at-property-rule" rel>MDN: @property at-rule</a></p> <p data-svelte-h="svelte-2ttq7g"><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timeline" rel>MDN: Animation Timeline</a></p>
]]></content>
<pubDate>Fri, 05 Jan 2024 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/04-autosize-textarea</guid>
<title>autosize-textarea Web Component</title>
<link>https://www.component-odyssey.com/articles/04-autosize-textarea</link>
<description>A quick and simple HTML web component to give your textareas the ability to grow with its value.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-4j61w1">At work, I was tasked with creating a text input that grew vertically to match the internal content.</p> <p data-svelte-h="svelte-1ml5mop">I was hoping there was a handy HTML attribute I could apply that would magically solve the problem for me.</p> <p data-svelte-h="svelte-1grn7u1">Spoilers: There wasn’t</p> <p data-svelte-h="svelte-39bwo5">After having a quick Google, it was apparent that I needed to tap into some JS to get this working.</p> <p data-svelte-h="svelte-2gdfde">The two existing solutions that stuck with me were the following</p> <ul data-svelte-h="svelte-1k3vl03"><li><a href="https://css-tricks.com/the-cleanest-trick-for-autogrowing-textareas/" rel>This genius CSS grid hack by Chris Coyier</a></li> <li><a href="https://github.com/jackmoore/autosize/tree/master" rel>This handy autosize library by Jack Moore</a></li></ul> <p data-svelte-h="svelte-1fdroap">I was tempted to drop in Jack’s library, but I didn’t like the idea of having the state of all the textareas managed by a singleton. I’d prefer to instead create and manage an instance per textarea. I wanted to supplement the existing behaviour of the textarea, and so a little web component felt like the best solution for this problem.</p> <p data-svelte-h="svelte-1hx3e5t">This is what it looks like in action:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>autosize-textarea</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>textarea</span> <span class="token attr-name">placeholder</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Type something here...<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>textarea</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>autosize-textarea</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <img alt="the textarea growing vertically as more content is added" src="https://component-odyssey.com/images/articles/04-autosize-textarea/demo.gif"> <p data-svelte-h="svelte-jqpi86">You start with your textarea element, and give it whatever attributes you want. You then wrap it with the <code>autosize-textarea</code> which gives it the additional autosize functionality.</p> <p data-svelte-h="svelte-2a7a9n">For the implementation, I decided to omit the shadow DOM for a few reasons:</p> <ul data-svelte-h="svelte-f6y6zg"><li>I wanted easy access to the <code>textarea</code> element, so I can adjust the styles and attributes.</li> <li>I wanted the <code>textarea</code> to be part of the light DOM, so that it inherits the document’s styles, and the user can apply the standard HTML attributes to it.</li></ul> <p data-svelte-h="svelte-lhydz9">The <code>autosize-textarea</code> also progressively enhances the standard <code>textarea</code>. If something goes wrong with the loading of the web component, then the textarea will still render and function as expected.</p> <p data-svelte-h="svelte-1pv08y">In other words, we start with a standard textarea, and progressively enhance to use the autosize textarea when the JS loads and the component is registered.</p> <p data-svelte-h="svelte-1w9xrf3">Very handy!</p>
]]></content>
<pubDate>Mon, 04 Dec 2023 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/03-announcing-component-odyssey</guid>
<title>Navigating Your Component Journey with Component Odyssey</title>
<link>https://www.component-odyssey.com/articles/03-announcing-component-odyssey</link>
<description>There are dozens reasons to build a component library, but it's not an easy task. Component Odyssey will help you navigate your component library journey.</description>
<content type="html"><![CDATA[
 <h2 data-svelte-h="svelte-pvlcsl">The Complexities of Building Your Own Component Library</h2> <p data-svelte-h="svelte-m2b26y">At some point, every web developer has thought about creating their own component library, and for good reason.</p> <p data-svelte-h="svelte-16o99cd">Building a library is an opportunity to express your creativity, learn to develop more accessible web experiences, contribute to the open source community, upskill yourself for a better-paid role, or simply become a more well-rounded web developer.</p> <p data-svelte-h="svelte-1tm4ilg">A component library is also a valuable tool to have in your team, as reusing the same components over several projects is a great way of saving your team lots of time and effort.</p> <p data-svelte-h="svelte-1kxpu81">But building a component library is no easy task in part due to how complex the web development landscape has gotten over the years. With so many frameworks and runtimes to choose from, how do you know which is the best to pick for your component library? Picking one may very well lock your components out from being used with others.</p> <p data-svelte-h="svelte-1y3h3tk">Ultimately, you want your end-users to have enjoyable web experiences, you want your library consumers to easily build interfaces with your library, and you want a smooth development experience to build, test, and publish your library.</p> <p data-svelte-h="svelte-10f8nsm">That’s what Component Odyssey will teach you to do.</p> <h2 data-svelte-h="svelte-a3r6vj">Introducing Component Odyssey</h2> <p data-svelte-h="svelte-qbntw5">Component Odyssey will help you navigate your component library journey.</p> <p data-svelte-h="svelte-kcoz3d">In Component Odyssey, I’ll be teaching you how to build a component library with a minimal tech stack. You’ll learn how to avoid locking yourself into the shiny framework of the month, and you’ll write components that work across any JavaScript framework.</p> <p data-svelte-h="svelte-165d6cq">So why should you embark on your Component Odyssey?</p> <h3 data-svelte-h="svelte-mkfffv">You’ll become a more future-proof web developer</h3> <p data-svelte-h="svelte-z6kzzs">The core technologies introduced in Component Odyssey are baked into the browser, meaning that as you become more familiar with these tools, you’ll also become more familiar with building for the browser as a whole. The skills you learn in this course will serve you in almost any front-end project you work on in the future.</p> <h3 data-svelte-h="svelte-ywv2cc">You’ll build components that your users will love</h3> <p data-svelte-h="svelte-12ymbtl">You won’t just be writing components in Component Odyssey, you’ll learn how to style, test, type, and publish them. These are all important in ensuring that the components you ship are robust and user-friendly.</p> <h3 data-svelte-h="svelte-af9bt3">You’ll boost your career opportunities</h3> <p data-svelte-h="svelte-n2ilik">Building a component library is an excellent way to contribute to the open-source community, which improves your chances of working on other cool projects, or landing some wonderful job roles. Just sharing the library you’ve built from scratch with a prospective job employer will help you stand out from the crowd of applicants.</p> <p data-svelte-h="svelte-7cnl4x">I did just this when I interviewed for my current job, and the interviewers loved my component library.</p> <img src="https://component-odyssey.com/images/articles/03-announcing-component-odyssey/a2k-docs.png" alt="Documentation for A2K component library"> <h3 data-svelte-h="svelte-1tyrgys">You’ll learn to do more with less</h3> <p data-svelte-h="svelte-1t9fl5c">The components you’ll be building in Component Odyssey are built using web components, the browser’s built-in way to create reusable components. You don’t need a framework to write and publish them, and as a result, you’ll be able to deliver components that work across the web.</p> <p data-svelte-h="svelte-1obazby">Web components aren’t new or radical, loads of large companies use web components to power their web experiences, like Microsoft, Adobe, and NASA.</p> <img src="https://component-odyssey.com/images/articles/03-announcing-component-odyssey/adobe.png" alt="Adobe software, which uses web components"> <p data-svelte-h="svelte-17hrma6">You’ll also be introduced to other tools and technologies that lean into the browser’s built-in capabilities, which means that you, and your library consumers, can avoid complex build systems to run your code.</p> <h2 data-svelte-h="svelte-1ogii0j">The Component Odyssey platform</h2> <p data-svelte-h="svelte-11y74pn">Component Odyssey is a self-paced and highly interactive course, so there’ll be plenty of hands-on coding for you to do. There are also no deadlines, so you can go through the entire course on your own time.</p> <p data-svelte-h="svelte-15u0y5n">Every lesson is accompanied by written content and a video, and the course is jam-packed with code examples, exercises, and projects.</p> <p data-svelte-h="svelte-1c617k1">Most lessons contain some interactive runnable code like the one below:</p>  <div id="wrapper" data-fullscreen="false" class="svelte-llm5qm"><div class="toolbar svelte-llm5qm"><button class="small"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button></div> <sandpack-preset></sandpack-preset> </div> <p data-svelte-h="svelte-jwmejm">Other lessons contain in-depth exercises for you to download and run locally on your computers.</p> <img src="https://component-odyssey.com/images/articles/03-announcing-component-odyssey/album-odyssey-exercise.png" alt="Example for a downloadable exercise, with interactive element, and unit tests."> <p data-svelte-h="svelte-zs9mhf">Most importantly, throughout the entire course, you’ll be slowly building out a functioning component library, with multiple components, a testing strategy, and some handy workflow automation.</p> <p data-svelte-h="svelte-haonjc">You won’t be alone either, starting Component Odyssey will also give you access to a Discord community. You’ll be able to share the amazing things you’ve built, get help on any tough challenges you’re facing, and meet other developers on their journeys.</p> <h2 data-svelte-h="svelte-kfvyta">Who should take Component Odyssey?</h2> <p data-svelte-h="svelte-11wwrq0">You don’t need to be an expert web developer to take this course, it’s designed for anyone with some working HTML, CSS, and JavaScript experience. If you’ve built a few interactive websites and have a few months of web development experience, then you’re golden.</p> <p data-svelte-h="svelte-lytpgu">Component Odyssey doesn’t cover the absolute basics of HTML, CSS, and JavaScript, but it does build on top of those browser fundamentals, so you can build great components without a framework.</p> <p data-svelte-h="svelte-jaqpip">Is Component Odyssey worth taking if you’re a seasoned developer? Absolutely, there’ll still be so much for you to gain, as you’ll be diving deep into web components, and you’ll learn how to style, test, and publish them.</p> <h2 data-svelte-h="svelte-1m5bb3f">About me</h2> <p data-svelte-h="svelte-1ixsp43">As for me, I’m Andrico, a web developer based in London. I’ve been a professional web developer for the last 7 years and have worked across a bunch of startups. I’m currently building design-to-code automation and design system automation at Anima.</p> <p data-svelte-h="svelte-c79yga">In previous roles, I was a front-end champion, where I ran workshops about front-end development, web accessibility, and front-end testing.</p> <p data-svelte-h="svelte-10a52p3">I’ve also built a few personal projects on the side like Cali Skills, a bodyweight fitness tracker, and Handstand Journey, a popular mobile application designed as a fun introduction to the exciting world of arm balances.</p> <p data-svelte-h="svelte-1vi1hep">I’m also the creator of a2k, the Windows 2000-inspired web component library. I’ve also contributed to several open-source projects, most notably the Open UI, where I led the site rewrite from Gatsby to Astro.</p> <p data-svelte-h="svelte-1lca97r">Component Odyssey is everything I’ve learnt about web development and component library development condensed down into a fun and highly interactive course.</p> <p data-svelte-h="svelte-1tufnmq">Fun fact: Before starting my career as a web developer, I worked in the family chip shop in South-East London (it’s still going strong, so stop by for some fish and chips!).</p>
]]></content>
<pubDate>Sat, 25 Nov 2023 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/02-hermes-wc-a-feedback-widget-built-on-web-components</guid>
<title>Gather User Feedback On Any Website with Hermes WC</title>
<link>https://www.component-odyssey.com/articles/02-hermes-wc-a-feedback-widget-built-on-web-components</link>
<description>Nothing is more valuable than direct feedback from your users. Hermes WC is an open source package built on web component that offers you a quick and easy way to learn what your users are thinking.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-1lkzk2v">Nothing’s more important for indie developers than gathering user feedback, especially for early-stage projects that are likely to undergo massive changes regularly. At the same time, many developers don’t need the kind of enterprise-level feature set that many of the most well-known customer platforms offer.</p> <p data-svelte-h="svelte-x2194x">For the last few months, I’ve been creating Component Odyssey, a course designed to help developers build and publish components that work everywhere. As I’m gearing up to open my platform to beta testers I need a free, quick, and easy mechanism to gather user feedback.</p> <p data-svelte-h="svelte-6v657h">I want an unintrusive widget that I could drop into my page which students could use to send feedback at any point during the course to flag bugs and unclear course content. Given that the Component Odyssey platform is built on top of SvelteKit, it would be easy for me to create a Svelte component that fires data to an endpoint.</p> <p data-svelte-h="svelte-1dflc2l">But I wanted to practice what I teach, and a form widget feels like a great candidate for a web component as the browser already has great support for building forms. On top of that, a form widget isn’t a novel piece of functionality and certainly shouldn’t rely on a specific framework to work. The idea of writing a simple, but very useful component, that I can’t then use in my React and VanillaJS projects feels like a waste of energy.</p> <p data-svelte-h="svelte-11z539">That’s what led me to build <a href="https://github.com/andrico1234/hermes-wc" rel>Hermes WC</a>. With Hermes WC, you can easily add an interactive form that dispatches the form data to a location of your choice.</p> <p data-svelte-h="svelte-1bceu69">Here’s a demo of Hermes WC in action, sending feedback to Discord, Slack, and an HTTP endpoint.</p> <video controls loop autoplay data-svelte-h="svelte-8tyjhz"><source src="https://component-odyssey.com/images/articles/02-hermes-wc-a-feedback-widget-built-on-web-components/hermes-wc-demo.mp4" type="video/mp4"></video> <p data-svelte-h="svelte-1uk7lj2">So let’s see how you can add Hermes WC to your own projects</p> <h2 data-svelte-h="svelte-cfzo00">Step 1: Installing Hermes WC</h2> <p data-svelte-h="svelte-ryidl9">Begin by installing Hermes WC:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html">npm install hermes-wc</code><!-- HTML_TAG_END --></pre> <h2 data-svelte-h="svelte-1b7mpi">Step 2: Adding the Hermes WC markup</h2> <p data-svelte-h="svelte-14482bj">Once you’ve done that, you can update your webpage with the following markup:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>hermes-wrapper</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>form</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>hermes-stack<span class="token punctuation">"</span></span> <span class="token attr-name">data-hermes</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>form<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>sl-input</span> <span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>feedback<span class="token punctuation">"</span></span> <span class="token attr-name">label</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Feedback<span class="token punctuation">"</span></span> <span class="token attr-name">placeholder</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>e.g., Not clear enough<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>sl-input</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>hermes-score-input</span>
			<span class="token attr-name">name</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>score<span class="token punctuation">"</span></span>
			<span class="token attr-name">label</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Score<span class="token punctuation">"</span></span>
			<span class="token attr-name">score-count</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>5<span class="token punctuation">"</span></span>
			<span class="token attr-name">start-helper-text</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>Low Score<span class="token punctuation">"</span></span>
			<span class="token attr-name">end-helper-text</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>High score<span class="token punctuation">"</span></span>
		<span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>hermes-score-input</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>hermes-row<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>sl-button</span> <span class="token attr-name">data-hermes</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>close<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Close<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>sl-button</span><span class="token punctuation">></span></span>
			<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>sl-button</span> <span class="token attr-name">variant</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>primary<span class="token punctuation">"</span></span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>submit<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Submit<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>sl-button</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span> <span class="token attr-name">data-hermes</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>helper-text<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>form</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>hermes-wrapper</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1bt74y5">There’s heaps of stuff going on here, so let’s break it down, element by element.</p> <p data-svelte-h="svelte-1gtcsq2"><strong>Hermes Wrapper</strong></p> <p data-svelte-h="svelte-4ijvwy">This is the component that’s responsible for handling the layout of the Hermes form. It mainly handles the form’s open and close states, while also placing a button on the right hand side of the page.</p> <p data-svelte-h="svelte-16xg0jz"><strong>Form</strong></p> <p data-svelte-h="svelte-32kzy1">This is the form element that’s in charge of listening and reacting to the submit event. A form element with the attribute <code>data-hermes=&quot;form&quot;</code> is required.</p> <p data-svelte-h="svelte-1j7k930"><strong>SL Input</strong></p> <p data-svelte-h="svelte-1t54vdh">Because Hermes WC uses a standard HTML form element, we can use any old HTML form controls as children and their values will be captured in the submit event. As a result, I’m using the Shoelace library to render some pre-styled and accessible components.</p> <div class="article__image" data-svelte-h="svelte-xrfa6t"><img src="https://component-odyssey.com/images/articles/02-hermes-wc-a-feedback-widget-built-on-web-components/hermes-input.png" alt="A Shoelace input component"></div> <p data-svelte-h="svelte-78ki0p"><strong>Hermes Score Input</strong></p> <p data-svelte-h="svelte-163bkh6">This is an additional web component that Hermes WC provides. It renders a horizontal radio button group with some attributes for helper text.</p> <div class="article__image" data-svelte-h="svelte-1durusi"><img src="https://component-odyssey.com/images/articles/02-hermes-wc-a-feedback-widget-built-on-web-components/hermes-radio-group.png" alt="The Hermes WC Score Input component"></div> <p data-svelte-h="svelte-1mk5j1s"><strong>SL Button</strong></p> <p data-svelte-h="svelte-7gitl5">This is a button provided to us by Shoelace. The button on the left has a <code>data-hermes=&quot;close&quot;</code> attribute, which is used to close the feedback widget.</p> <p data-svelte-h="svelte-17qupng">The button on the right has an attribute <code>type=&quot;submit&quot;</code> and is used to submit the form when it’s clicked.</p> <div class="article__image" data-svelte-h="svelte-bv3uwe"><img src="https://component-odyssey.com/images/articles/02-hermes-wc-a-feedback-widget-built-on-web-components/hermes-buttons.png" alt="Two Shoelace button components"></div> <p data-svelte-h="svelte-ziloxt"><strong>Whatever else you want…</strong></p> <p data-svelte-h="svelte-1s5yyc1">Like I mentioned earlier, because Hermes WC works with HTML forms, you can use any HTML form control to build your form.</p> <h2 data-svelte-h="svelte-e3qmy3">Step 3: Import the styles into your page</h2> <p data-svelte-h="svelte-1ppli0k">To apply the default styles to Hermes WC, go ahead and import the styles into your project:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>link</span> <span class="token attr-name">rel</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>stylesheet<span class="token punctuation">"</span></span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>path/to/node_modules/hermes-wc/src/style.css<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span></code><!-- HTML_TAG_END --></pre> <h2 data-svelte-h="svelte-1aaov2i">Step 4: Initializing the Hermes WC form</h2> <p data-svelte-h="svelte-v8ag19">With the markup written, you’ll need to add a small splash of JavaScript to initialize the form.</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">import</span> <span class="token punctuation">&#123;</span> DiscordSubmissionAdapter <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">'hermes-wc/src/submission-adapters/discord.js'</span>
<span class="token keyword">import</span> <span class="token punctuation">&#123;</span> initializeHermesForm <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">'hermes-wc/src/index.js'</span>
<span class="token function">initializeHermesForm</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span>
  <span class="token literal-property property">submissionAdapters</span><span class="token operator">:</span> <span class="token punctuation">[</span><span class="token keyword">new</span> <span class="token class-name">DiscordSubmissionAdapter</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span>
    <span class="token literal-property property">webhookUrl</span><span class="token operator">:</span> <span class="token string">'your webhook url'</span>
  <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">,</span>
  <span class="token function-variable function">submissionCompleteCallback</span><span class="token operator">:</span> <span class="token punctuation">(</span><span class="token parameter">response</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span> <span class="token comment">// handle the response &#125;</span>
<span class="token punctuation">&#125;</span><span class="token punctuation">)</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-189yqu8">Running <code>initializeHermesForm</code> will do a few things under-the-hood, like set up event listeners and register the web components.</p> <p data-svelte-h="svelte-1owkj2k">You can then provide one or more <strong><em>submission adapters</em></strong> which send your data to a destination of your choice. As of now, Hermes WC supports sending feedback to Slack, Discord, or an HTTP GET endpoint. You can even create your own adapters.</p> <p data-svelte-h="svelte-kmk0as">You can also pass a function through to the <code>submissionCompleteCallback</code> option, which gets fired when all of the submission requests are settled. You’ll be given the response of all the promises, which you can use to display a success or error message to your users.</p> <h2 data-svelte-h="svelte-1dj9woh">Wrapping Up</h2> <p data-svelte-h="svelte-1f7iufv">I hope you find a tool like Hermes WC useful. I plan to open source a bunch of the tools I create for Component Odyssey. Other tools include <a href="https://github.com/andrico1234/sandpack-lit" rel>Sandpack Lit</a>.</p>
]]></content>
<pubDate>Tue, 14 Nov 2023 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/01-writing-components-that-work-in-any-framework</guid>
<title>Writing Components That Work In Any Frontend Framework</title>
<link>https://www.component-odyssey.com/articles/01-writing-components-that-work-in-any-framework</link>
<description>Web components let developers write interoperable components, but at the cost of lots of boilerplate. Learn how you can write components that work in Svelte, Vue, React, and other frameworks, with minimal boilerplate.</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-1dehvzl">The browser has a built-in way of writing reusable components in the form of <strong>web components</strong>. They’re an excellent choice for building interactive, and reusable components that work in any frontend framework. With that said, writing highly interactive and robust web components isn’t simple. They require a lot of boilerplate and feel much less intuitive than the components you may have written in frameworks like React, Svelte, and Vue.</p> <p data-svelte-h="svelte-x802aa">In this article, I’ll give you an example of an interactive component written as a web component, and then refactor it using a library that softens the edges and removes heaps of boilerplate.</p> <p data-svelte-h="svelte-xwisfy">Don’t sweat if you’re not familiar with web components. In the next section, I’ll do a (very brief and limited) overview of what web components are, and what they’re made out of. If you have some basic experience with them, you can skip the next section.</p> <div class="aside-wrapper svelte-12vh5ck" data-svelte-h="svelte-1bkzujq"><aside>If you want to learn how to build web components by building your own resilient component
		library, why not check out <a href="/">Component Odyssey </a>?</aside> </div> <h2 data-svelte-h="svelte-1dna6jd">What are web components?</h2> <p data-svelte-h="svelte-1j2rlte">Before web components, the browser didn’t have a standard way of writing reusable components. Many libraries solve this problem, but they often run into limitations like performance, interoperability, and issues with web standards.</p> <p data-svelte-h="svelte-4px37t">They’re a technology made up of 3 different browser features:</p> <ul data-svelte-h="svelte-1jv4rbz"><li>Custom elements</li> <li>Shadow DOM</li> <li>HTML Templates</li></ul> <p data-svelte-h="svelte-144zqkc">We’ll do a quick crash course of these technologies, but it’s by no means a comprehensive breakdown.</p> <h3 data-svelte-h="svelte-mzg9ku">Custom Elements</h3> <p data-svelte-h="svelte-mw0m5h">With Custom Elements you can author your own custom HTML elements that you can reuse across your site. They can be as simple as text, images, or visual decorations. You can push them further and build interactive components, complex widgets, or entire web applications.</p> <p data-svelte-h="svelte-19ukmlk">You’re not just limited to using them in your projects, but you can publish them and allow other developers to use them on their sites.</p> <p data-svelte-h="svelte-xc5383">Here are some of the reusable components from my library <a href="https://a2000-docs.netlify.app/" rel>A2K</a>. You can see that they come in all shapes and sizes, and have a range of different functionalities. Using them in your projects is similar to using any old HTML element.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/01-writing-components-that-work-in-any-framework/web-components.png" alt="A small collection of web components from the A2K library"></div> </p> <p data-svelte-h="svelte-1im4c5k">Here’s how you’d use the progress element in your project:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token doctype"><span class="token punctuation">&lt;!</span><span class="token doctype-tag">DOCTYPE</span> <span class="token name">html</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>html</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>head</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>title</span><span class="token punctuation">></span></span>Quick Start<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>title</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>meta</span> <span class="token attr-name">charset</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>UTF-8<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>head</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
		<span class="token comment">&lt;!-- Use web components in your HTML like regular built-in elements. --></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a2k-progress</span> <span class="token attr-name">progress</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>50<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span>
		<span class="token comment">&lt;!-- a2k web components use standard JavaScript modules. --></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>module<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token script"><span class="token language-javascript">
			<span class="token keyword">import</span> <span class="token string">'https://cdn.jsdelivr.net/npm/@a2000/progress@0.0.5/lib/src/a2k-progress.js'</span><span class="token punctuation">;</span>
		</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>html</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-bjfs2s">Once you’ve imported the third-party scripts, you can start using the component, <code>a2k-progress</code> in this case, just like any other HTML element.</p> <p data-svelte-h="svelte-bgoaf8">If you’re building your own web components, there’s virtually no limit to how complex you can make your custom elements. I recently created a web component that renders a CodeSandbox code editor in the browser. And because it’s a web component, you can use it in any framework you like! If you’d like to learn a little more about that, <a href="/articles/00-sandpack-lit-universal">you can read more here</a>.</p> <h3 data-svelte-h="svelte-1bygji0">Shadow DOM</h3> <p data-svelte-h="svelte-1g1ma5">If you have a working knowledge of CSS, you’ll know that vanilla CSS is scoped globally. Writing something like this in your global.css:</p> <pre class="language-css"><!-- HTML_TAG_START --><code class="language-css"><span class="token selector">p</span> <span class="token punctuation">&#123;</span>
	<span class="token property">color</span><span class="token punctuation">:</span> tomato<span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-l5d5q6">Will give all <code>p</code> elements a nice orange/red color, assuming that no other, more specific CSS selectors are applied to a <code>p</code> element.</p> <p data-svelte-h="svelte-1am76yl">Take this select menu for example:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/01-writing-components-that-work-in-any-framework/a2k-select-menu.png" alt="A select menu component with a visual design reminiscent of the old Windows operating systems"></div> </p> <p data-svelte-h="svelte-14wfzgp">It has a distinct character which is driven by the visual design. You might want to use this component, but if your global styles affect things like the font family, the color, or the font size, it could cause issues with the appearance of the component:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>head</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>style</span><span class="token punctuation">></span></span>
		body &#123;
			color: blue;
			font-size: 12px;
			font-family: system-ui;
		&#125;
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>style</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>head</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a2k-select</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a2k-select</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/01-writing-components-that-work-in-any-framework/a2k-select-menu-2.png" alt="The same select menu, but with a lot of its defining characteristics overridden by global CSS."></div> </p> <p data-svelte-h="svelte-1d079ft">This is where the Shadow DOM comes in. The Shadow DOM is an encapsulation mechanism that prevents the rest of the DOM from interfering with your web component, this ensures that the global styles of the web application don’t interfere with any components that you consume. It also means that component library developers can author their components with the confidence that they’ll look and behave as expected across different web applications.</p> <p data-svelte-h="svelte-m80p6n">There’s a lot more nuance when it comes to the Shadow DOM, as well as other features that we’re not going to touch on in this article. If you’d like to learn more about web components though, I have an entire course (<a href="/">Component Odyssey</a>) dedicated to teaching you how to build reusable components that work in any framework.</p> <h3 data-svelte-h="svelte-kjxkxm">HTML Templates</h3> <p data-svelte-h="svelte-lhc3q1">The last feature in our whistle-stop tour of web components features is HTML Templates.</p> <p data-svelte-h="svelte-zjmc50">What makes this HTML element different from other elements, is that the browser doesn’t render its content to the page. If you were to write the following HTML you wouldn’t see the text “I’m a header” displayed on the page:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>template</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>I'm a header<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>template</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1tkc23w">Instead of being used to render the content directly, the content of the template is designed to be copied. The copied template can then be used to render content to the page. You can think of the template element much like the template for a 3D print. The template isn’t a physical entity, but it’s used to create real-life clones.</p> <p data-svelte-h="svelte-1s2sucz">You would then reference the template element in your web component, clone it, and render the clone as the markup for your component.</p> <p data-svelte-h="svelte-1qfriol">I won’t spend any more time on these web component features, but you’ve probably already noticed that to write vanilla web components, there are a lot of new browser features that you need to know and understand. You’ll see in the next section that the mental model for building web components doesn’t feel as streamlined as it does for other component frameworks.</p> <h2 data-svelte-h="svelte-6k2qoa">A Basic Web Component</h2> <p data-svelte-h="svelte-udsmjz">Now that we’ve briefly covered the fundamental technologies powering a web component, here’s how to build a <em>hello world</em> component:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">const</span> template <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">createElement</span><span class="token punctuation">(</span><span class="token string">'template'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
template<span class="token punctuation">.</span>innerHTML <span class="token operator">=</span> <span class="token template-string"><span class="token template-punctuation string">&#96;</span><span class="token string">&lt;p>Hello World&lt;/p></span><span class="token template-punctuation string">&#96;</span></span><span class="token punctuation">;</span>
<span class="token keyword">class</span> <span class="token class-name">HelloWorld</span> <span class="token keyword">extends</span> <span class="token class-name">HTMLElement</span> <span class="token punctuation">&#123;</span>
	<span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">attachShadow</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span> <span class="token literal-property property">mode</span><span class="token operator">:</span> <span class="token string">'open'</span> <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">this</span><span class="token punctuation">.</span>shadowRoot<span class="token punctuation">.</span><span class="token function">append</span><span class="token punctuation">(</span>template<span class="token punctuation">.</span>content<span class="token punctuation">.</span><span class="token function">cloneNode</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>
<p>customElements<span class="token punctuation">.</span><span class="token function">define</span><span class="token punctuation">(</span><span class="token string">‘hello-world’</span><span class="token punctuation">,</span> HelloWorld<span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-tomn4c">This is the most simple component one could write, but there’s already so much going on. For someone completely new to web components, and without the background knowledge I provided above, they’re going to be left with a lot of questions, and a lot of confusion.</p> <p data-svelte-h="svelte-171g9k4">For me, there are at least two key reasons why web components can be challenging to write, at least within the context of the hello world examples.</p> <h3 data-svelte-h="svelte-iprs94">The markup is decoupled from the component logic</h3> <p data-svelte-h="svelte-lwib05">In many frameworks, the markup of the component is often treated as a first-class citizen. It’s often the content that gets returned from the component function, or has direct access to the component’s state, or has built-in utilities to help manipulate markup (like loops, conditionals, etc).</p> <p data-svelte-h="svelte-11f0aj8">This isn’t the case for web components. In fact, the markup is often defined outside of the component’s class. There’s also no built-in way for the template to reference the current state of the component. This becomes a cumbersome limitation as the complexity of a component grows.</p> <p data-svelte-h="svelte-1ermqsd">In the world of frontend, components are designed to help developers reuse markup in several pages. As a result, the markup and the component logic are inextricably linked, and so they should be colocated with one another.</p> <h3 data-svelte-h="svelte-nqennl">Writing a web component requires understanding all of its underlying technologies</h3> <p data-svelte-h="svelte-w2ui4a">As we saw above, web components are made up of three technologies. You can also see in the hello world code snippet, that we explicitly need to know and understand these three technologies.</p> <ol data-svelte-h="svelte-1i5xnpp"><li>We’re creating a <strong>template element</strong> and setting its inner HTML</li> <li>We’re creating a <strong>shadow root</strong>, and explicitly setting its mode to ‘open’.</li> <li>We’re cloning our <strong>template</strong> and appending it to our <strong>shadow root</strong></li> <li>We’re registering a new <strong>custom element</strong> to the document</li></ol> <p data-svelte-h="svelte-1lvv3gw">There’s nothing inherently wrong with this, since web components are supposed to be a “lower-level” browser API, making them prime for building abstractions on top of. But for a developer coming from a React or a Svelte background, having to understand these new browser features, and then having to write components with them can feel like too much friction.</p> <h2 data-svelte-h="svelte-jvg0qz">A more advanced web component</h2> <p data-svelte-h="svelte-yry6d1">Let’s take a look at a more advanced web component, a counter button.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/01-writing-components-that-work-in-any-framework/counter-button.png" alt="A simple counter button. There's a clickable button, and some text showing how many times the button has been clicked"></div> </p> <p data-svelte-h="svelte-n9mvbu">You click the button, and the counter increments.</p> <p data-svelte-h="svelte-135duiz">The following example contains a few extra web component concepts, like lifecycle functions and observable attributes. You don’t need to understand everything going on in the code snippet. This example is really only used to illustrate how much boilerplate is required for the most basic of interactive interfaces, a counter button:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">const</span> templateEl <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">createElement</span><span class="token punctuation">(</span><span class="token string">“template”</span><span class="token punctuation">)</span><span class="token punctuation">;</span></p>
<p>templateEl<span class="token punctuation">.</span>innerHTML <span class="token operator">=</span> <span class="token template-string"><span class="token template-punctuation string">`</span><span class="token string">
<button>Press me!</button>
<p>You pressed me 0 times.</p></p>
</span><span class="token template-punctuation string">&#96;</span></span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">OdysseyButton</span> <span class="token keyword">extends</span> <span class="token class-name">HTMLElement</span> <span class="token punctuation">&#123;</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">attachShadow</span><span class="token punctuation">(</span><span class="token punctuation">&#123;</span> <span class="token literal-property property">mode</span><span class="token operator">:</span> <span class="token string">"open"</span> <span class="token punctuation">&#125;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>shadowRoot<span class="token punctuation">.</span><span class="token function">appendChild</span><span class="token punctuation">(</span>templateEl<span class="token punctuation">.</span>content<span class="token punctuation">.</span><span class="token function">cloneNode</span><span class="token punctuation">(</span><span class="token boolean">true</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>button <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>shadowRoot<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">"button"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>p <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>shadowRoot<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">"p"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">"count"</span><span class="token punctuation">,</span> <span class="token string">"0"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
	<span class="token comment">// Note: Web components have lifecycle methods,</span>
  <span class="token comment">// If we're setting event listeners when the component is added to the DOM, it's our job to clean</span>
  <span class="token comment">// them up when it gets removed from the DOM</span>
  <span class="token function">connectedCallback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>button<span class="token punctuation">.</span><span class="token function">addEventListener</span><span class="token punctuation">(</span><span class="token string">"click"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>handleClick<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token function">disconnectedCallback</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>button<span class="token punctuation">.</span><span class="token function">removeEventListener</span><span class="token punctuation">(</span><span class="token string">"click"</span><span class="token punctuation">,</span> <span class="token keyword">this</span><span class="token punctuation">.</span>handleClick<span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token comment">// Unlike frameworks like React, Web Components don't automatically rerender when a prop (or attribute)</span>
  <span class="token comment">// changes. Instead, we need to explicitly define which attributes we want to observe.</span>
  <span class="token keyword">static</span> observedAttributes <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token string">"disabled"</span><span class="token punctuation">,</span> <span class="token string">"count"</span><span class="token punctuation">]</span><span class="token punctuation">;</span>
  <span class="token comment">// When one of the above attributes change, this lifecycle method runs, and we can</span>
  <span class="token comment">// react to the new attribute's value accordingly.</span>
  <span class="token function">attributeChangedCallback</span><span class="token punctuation">(</span><span class="token parameter">name<span class="token punctuation">,</span> _<span class="token punctuation">,</span> newVal</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>name <span class="token operator">===</span> <span class="token string">"count"</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>p<span class="token punctuation">.</span>innerHTML <span class="token operator">=</span> <span class="token template-string"><span class="token template-punctuation string">&#96;</span><span class="token string">You pressed me </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span>newVal<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token string"> times.</span><span class="token template-punctuation string">&#96;</span></span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
    <span class="token keyword">if</span> <span class="token punctuation">(</span>name <span class="token operator">===</span> <span class="token string">"disabled"</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
      <span class="token keyword">this</span><span class="token punctuation">.</span>button<span class="token punctuation">.</span>disabled <span class="token operator">=</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">&#125;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token comment">// In HTML, attribute values are always strings. This means that it's our job to</span>
  <span class="token comment">// convert types. You can see below that we're converting a string -> number, and then back to a string</span>
  <span class="token function-variable function">handleClick</span> <span class="token operator">=</span> <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=></span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">const</span> counter <span class="token operator">=</span> <span class="token function">Number</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">getAttribute</span><span class="token punctuation">(</span><span class="token string">"count"</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">setAttribute</span><span class="token punctuation">(</span><span class="token string">"count"</span><span class="token punctuation">,</span> <span class="token template-string"><span class="token template-punctuation string">&#96;</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span>counter <span class="token operator">+</span> <span class="token number">1</span><span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token template-punctuation string">&#96;</span></span><span class="token punctuation">)</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-im1rer">As web component authors, we need to consider a lot of things:</p> <ul data-svelte-h="svelte-1tsis2x"><li>Setting up the shadow DOM</li> <li>Setting up the HTML templates</li> <li>Cleaning up event listeners</li> <li>Defining properties that we want to observe</li> <li>Reacting to properties when they change</li> <li>Handling type conversions for attributes</li></ul> <p data-svelte-h="svelte-11tdcby">And there are still so many other things to consider that I haven’t touched on in this article.</p> <p data-svelte-h="svelte-14ksymt">That isn’t to say that web components are bad and that you shouldn’t write them, in fact, I’d argue that you learn so much about the browser platform by building with them. However, I feel that there are better ways to write components if your priority is to write interoperable components in a much more streamlined and ergonomic way.</p> <h2 data-svelte-h="svelte-lyrmwa">Writing web components with less boilerplate</h2> <p data-svelte-h="svelte-19j4ht8">As I mentioned earlier, there are a lot of tools out there to help make writing web components much easier. One such tool is called Lit, which is developed by a team at Google. <a href="https://lit.dev/" rel>Lit</a> is a lightweight library designed to make writing web components simple, by removing the need for the boilerplate we’ve already seen above.</p> <p data-svelte-h="svelte-qs9pfl">As we’ll see, Lit does a lot of heavy lifting under-the-hood to help cut down the total lines of code by nearly half! And because Lit is a wrapper around web components and other native browser features, all your existing knowledge about web components is transferable.</p> <p data-svelte-h="svelte-ossgkq">To start seeing how Lit simplifies your web components, here’s the <strong>hello world</strong> example from earlier, but refactored to use Lit instead of a vanilla web component:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">import</span> <span class="token punctuation">&#123;</span> LitElement<span class="token punctuation">,</span> html <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">"lit"</span><span class="token punctuation">;</span>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">HelloWorld</span> <span class="token keyword">extends</span> <span class="token class-name">LitElement</span> <span class="token punctuation">&#123;</span>
  <span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">return</span> html<span class="token template-string"><span class="token template-punctuation string">&#96;</span><span class="token string">&lt;p>Hello World!&lt;/p></span><span class="token template-punctuation string">&#96;</span></span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>&#96;
<p>customElements<span class="token punctuation">.</span><span class="token function">define</span><span class="token punctuation">(</span><span class="token string">‘hello-world’</span><span class="token punctuation">,</span> HelloWorld<span class="token punctuation">)</span><span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-h11gz">There’s a lot less boilerplate with the Lit component, and Lit handles the two problems I mentioned earlier, a little bit differently. Let’s see how:</p> <ol data-svelte-h="svelte-1j1q5uc"><li>The markup is directly defined from within the component class. While you can define your templates outside of the class, it’s common practice to return the template from the <code>render</code> function. This is more in line with the mental model presented in other UI frameworks, where the UI is a function of the state.</li> <li>Lit also doesn’t require developers to attach the shadow DOM, or create template and clone template elements. While having an understanding of the underlying web component features will help when developing Lit components, they’re not required for getting started, so the barrier for entry is much lower.</li></ol> <p data-svelte-h="svelte-19b9uju">So now for the big finale, what does the counter component look like once we’ve migrated it over to Lit?</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">import</span> <span class="token punctuation">{</span> LitElement<span class="token punctuation">,</span> html <span class="token punctuation">}</span> <span class="token keyword">from</span> <span class="token string">“lit”</span><span class="token punctuation">;</span></p>
<span class="token keyword">export</span> <span class="token keyword">class</span> <span class="token class-name">OdysseyCounter</span> <span class="token keyword">extends</span> <span class="token class-name">LitElement</span> <span class="token punctuation">&#123;</span>
  <span class="token keyword">static</span> properties <span class="token operator">=</span> <span class="token punctuation">&#123;</span>
		<span class="token comment">// We define the component's properties as well as their type.</span>
		<span class="token comment">// These properties will trigger the component to re-render when their values change.</span>
		<span class="token comment">// While they're not the same, you can think of these "properties" as being</span>
		<span class="token comment">// Lit's alternatives to "observed attributes"</span>
		<span class="token comment">// If the value is passed down as an attribute, Lit converts the value</span>
		<span class="token comment">// to the correct type</span>
    <span class="token literal-property property">count</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span> <span class="token literal-property property">type</span><span class="token operator">:</span> Number <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
    <span class="token literal-property property">disabled</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span> <span class="token literal-property property">type</span><span class="token operator">:</span> Boolean <span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
  <span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
  <span class="token function">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token comment">// There's no need to create a shadow DOM, clone the template,</span>
		<span class="token comment">// or store references to our DOM nodes.</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token function">onCount</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
    <span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">=</span> <span class="token keyword">this</span><span class="token punctuation">.</span>count <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
  <span class="token function">render</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
		<span class="token comment">// Instead of using the attributeChangedCallback lifecycle, the</span>
		<span class="token comment">// render function has access to all of the component's properties,</span>
		<span class="token comment">// which simplifies the process of manipulating our templates.</span>
    <span class="token keyword">return</span> html<span class="token template-string"><span class="token template-punctuation string">&#96;</span><span class="token string">
      &lt;button ?disabled=</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span><span class="token keyword">this</span><span class="token punctuation">.</span>disabled<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token string"> @click=</span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span><span class="token keyword">this</span><span class="token punctuation">.</span>onCount<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token string">>
        Press me!
      &lt;/button>
      &lt;p>You pressed me </span><span class="token interpolation"><span class="token interpolation-punctuation punctuation">$&#123;</span><span class="token keyword">this</span><span class="token punctuation">.</span>count<span class="token interpolation-punctuation punctuation">&#125;</span></span><span class="token string"> times.&lt;/p>
    </span><span class="token template-punctuation string">&#96;</span></span><span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span>
<span class="token punctuation">&#125;</span>&#96;</code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1voiica">The amount of code we’re writing is cut down by almost half! And this difference becomes more noticeable when creating more complex user interfaces.</p> <h2 data-svelte-h="svelte-1jtigr1">Why am I going on about Lit?</h2> <p data-svelte-h="svelte-gr2fn5">I’m a big believer in web components, but I recognise that the barrier of entry is high for many developers. Writing complex web components requires understanding heaps of browser features and the education around web components isn’t as comprehensive as other technologies, like React or Vue.</p> <p data-svelte-h="svelte-1yehzyl">This is why I think it’s important to use tools like Lit can make writing performant and interoperable web components much easier. This is great if you want your components to work within any frontend framework.</p> <p data-svelte-h="svelte-s1ona0">If you’d like to learn even more, this is the approach I teach in my upcoming course <a href="/">Component Odyssey</a>. This course is excellent for anyone who wants to understand how to write components that work in any framework. I do this by covering the absolute basics of web components, before moving on to tools like Lit that simplify the process of writing web components without complicating your development environment. By the end, you’ll learn how to build and publish a component library that works across any frontend framework.</p> <p data-svelte-h="svelte-1xqzng6">If you want early-bird discount codes for Component Odyssey, then head on <a href="/subscribe">over to the site to get notified</a>.</p>
]]></content>
<pubDate>Sun, 05 Nov 2023 00:00:00 GMT</pubDate>
</item><item>
<guid>https://www.component-odyssey.com/articles/00-sandpack-lit-universal</guid>
<title>Introducing Sandpack Lit: The Universal CodeSandbox</title>
<link>https://www.component-odyssey.com/articles/00-sandpack-lit-universal</link>
<description>Learn how you can run entire web applications within your own web apps, regardless of whether you're using Svelte, Vue, React, or any other JavaScript framework</description>
<content type="html"><![CDATA[
 <p data-svelte-h="svelte-lf4xf2">Sandpack was a game-changer back when the team at CodeSandbox officially released it. Thanks to Sandpack, running a CodeSandbox in your browser-based projects was easier than ever. With it, you could open up a little window inside of your application that runs an entirely different application. And you weren’t limited to running simple sites, but entire web applications or Node servers.</p> <p data-svelte-h="svelte-1svlbtz">If you haven’t directly used Sandpack yourself, you’ve probably been on a site that has for displaying runnable code snippets or code exercises. In fact, the React docs site uses Sandpack for its code exercises.</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/00-sandpack-lit-universal/react-docs.gif" alt="Runnable code examples in the React docs site"></div> </p> <p data-svelte-h="svelte-1fukjk4">However, there’s one major problem… CodeSandbox only officially provides a React wrapper for Sandpack. If you wanted to run a CodeSandox from within your project, you’d need to either:</p> <ul data-svelte-h="svelte-1u6kr7q"><li>Create your project in React</li> <li>Create your own wrapper around the sandpack-core library</li></ul> <h2 data-svelte-h="svelte-1vkimja">Introducing Sandpack Lit</h2> <p data-svelte-h="svelte-15i2enn">With more frameworks than ever to build web applications, it makes sense to offer a drop-in Sandpack solution for frameworks that aren’t React.</p> <p data-svelte-h="svelte-fz779x">Developers could build their own Sandpack wrapper around their favourite frameworks, or the team at CodeSandbox could release official wrappers around each framework, but that feels like a lot of work for a lot of developers.</p> <p data-svelte-h="svelte-191ixzy">That’s where Sandpack Lit comes in.</p> <p data-svelte-h="svelte-9463w3">Sandpack Lit is a standalone web component that allows you to add a CodeSandbox to any client-side web application. Let’s see it in action!</p> <h2 data-svelte-h="svelte-15ab1sr">Sandpack Lit in action</h2> <p data-svelte-h="svelte-dzlt44">You’ll see just how easy it is to render a CodeSandbox inside of different projects using different frameworks. I’ll render the same interactive theme picker inside the sandbox</p> <p data-svelte-h="svelte-1q23td6">If you want to go ahead and use it yourself, you can begin by installing <code>sandpack-lit</code>:</p> <pre class="language-bash"><!-- HTML_TAG_START --><code class="language-bash"><span class="token function">npm</span> <span class="token function">install</span> sandpack-lit</code><!-- HTML_TAG_END --></pre> <h3 data-svelte-h="svelte-ih40cn">Svelte</h3> <p data-svelte-h="svelte-p0y0cg">If you’re using Svelte, create the following component:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span><span class="token punctuation">></span></span><span class="token plain-text">
  import "sandpack-lit/dist/presets/sandpack";
  import "sandpack-lit/dist/themes/odyssey.css";
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>main</span><span class="token punctuation">></span></span><span class="token plain-text">
  </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span><span class="token plain-text">Svelte</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span><span class="token plain-text">
  </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>container<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token plain-text">
    &lt;sandpack-preset
      options=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span>
        <span class="token literal-property property">closableTabs</span><span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
        <span class="token literal-property property">files</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span> <span class="token comment">/** files go here */</span><span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
        <span class="token literal-property property">customSetup</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
          <span class="token string-property property">"dependencies"</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
            <span class="token string-property property">"lit"</span><span class="token operator">:</span> <span class="token string">"2.6.1"</span>
          <span class="token punctuation">&#125;</span>
        <span class="token punctuation">&#125;</span>
      <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token plain-text">
    />
  </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span><span class="token plain-text">
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>main</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>style</span><span class="token punctuation">></span></span><span class="token plain-text">
  .container </span><span class="token punctuation">&#123;</span>
    <span class="token literal-property property">width</span><span class="token operator">:</span> 900px<span class="token punctuation">;</span>
  <span class="token punctuation">&#125;</span><span class="token plain-text">
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>style</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-fdl06r">Run and open your development server, and you should see Sandpack working:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/00-sandpack-lit-universal/svelte.png" alt="Sandpack Lit running in Svelte"></div> </p> <h3 data-svelte-h="svelte-1vji13y">Vue</h3> <p data-svelte-h="svelte-l8e3bf">If you’re using Vue, create the following component:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">setup</span><span class="token punctuation">></span></span><span class="token plain-text">
import "sandpack-lit/dist/presets/sandpack";
import "sandpack-lit/dist/themes/odyssey.css";
<p>const files = { /*<em> files go here </em>/ }</p>
<p>const dependencies = {
lit: “2.6.1”,
};</p>
<p>const options = {
closableTabs: false,
files,
customSetup: {
dependencies,
},
};</p>
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>template</span><span class="token punctuation">></span></span><span class="token plain-text">
  </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span><span class="token plain-text">Vue</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span><span class="token plain-text">
  </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">style</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>width: 900px<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token plain-text">
    </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>sandpack-preset</span> <span class="token attr-name"><span class="token namespace">v-bind:</span>options</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span>options</span> <span class="token punctuation">/></span></span><span class="token plain-text">
  </span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span><span class="token plain-text">
</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>template</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-1nienbk">Kick off your dev server, and you should see Sandpack working:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/00-sandpack-lit-universal/vue.png" alt="Sandpack Lit running in Vue"></div> </p> <h3 data-svelte-h="svelte-x1gk57">React</h3> <p data-svelte-h="svelte-1djp9jh">Consuming web components in a React project is a little different to the others, since React doesn’t offer out-of-the-box support for web components. Luckily Sandpack Lit offers a exports a React component that you can use instead:</p> <pre class="language-jsx"><!-- HTML_TAG_START --><code class="language-jsx"><span class="token keyword">import</span> <span class="token punctuation">&#123;</span> SandpackLitComponent <span class="token punctuation">&#125;</span> <span class="token keyword">from</span> <span class="token string">'sandpack-lit/dist/presets/sandpack-react'</span><span class="token punctuation">;</span>
<span class="token keyword">import</span> <span class="token string">'sandpack-lit/dist/themes/odyssey.css'</span><span class="token punctuation">;</span>
<span class="token keyword">function</span> <span class="token function">App</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">&#123;</span>
	<span class="token keyword">return</span> <span class="token punctuation">(</span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">style</span><span class="token script language-javascript"><span class="token script-punctuation punctuation">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> <span class="token literal-property property">width</span><span class="token operator">:</span> <span class="token string">'900px'</span> <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span></span><span class="token punctuation">></span></span><span class="token plain-text">
			</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span> <span class="token attr-name">style</span><span class="token script language-javascript"><span class="token script-punctuation punctuation">=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span> <span class="token literal-property property">textAlign</span><span class="token operator">:</span> <span class="token string">'center'</span> <span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span></span><span class="token punctuation">></span></span><span class="token plain-text">React</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span><span class="token plain-text">
			&lt;SandpackLitComponent
				options=</span><span class="token punctuation">&#123;</span><span class="token punctuation">&#123;</span>
					<span class="token literal-property property">closableTabs</span><span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
					<span class="token literal-property property">files</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
						<span class="token comment">/** files go here */</span>
					<span class="token punctuation">&#125;</span><span class="token punctuation">,</span>
					<span class="token literal-property property">customSetup</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
						<span class="token literal-property property">dependencies</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
							<span class="token literal-property property">lit</span><span class="token operator">:</span> <span class="token string">'2.6.1'</span>
						<span class="token punctuation">&#125;</span>
					<span class="token punctuation">&#125;</span>
				<span class="token punctuation">&#125;</span><span class="token punctuation">&#125;</span><span class="token plain-text">
			/>
		</span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token punctuation">)</span><span class="token punctuation">;</span>
<span class="token punctuation">&#125;</span>
<span class="token keyword">export</span> <span class="token keyword">default</span> App<span class="token punctuation">;</span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-fdl06r">Run and open your development server, and you should see Sandpack working:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/00-sandpack-lit-universal/react.png" alt="Sandpack Lit running in React"></div> </p> <h3 data-svelte-h="svelte-10v4xk3">Vanilla</h3> <p data-svelte-h="svelte-u0scf0">If you’re opting to not use a framework at all, you can add Sandpack Lit to your project using the following:</p> <pre class="language-html"><!-- HTML_TAG_START --><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>body</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">id</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>app<span class="token punctuation">"</span></span> <span class="token attr-name">style</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>width:900px<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span> <span class="token attr-name">style</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>text-align: center; color: black;<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>VanillaJS<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span>
		<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>sandpack-preset</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>sandpack-preset</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span>
	<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation attr-equals">=</span><span class="token punctuation">"</span>module<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token script"><span class="token language-javascript">
		<span class="token keyword">import</span> <span class="token string">"sandpack-lit/dist/presets/sandpack"</span><span class="token punctuation">;</span>
		<span class="token keyword">import</span> <span class="token string">"sandpack-lit/dist/themes/odyssey.css"</span><span class="token punctuation">;</span>
		<span class="token keyword">const</span> files <span class="token operator">=</span> <span class="token comment">/** your files here */</span>
		<span class="token keyword">const</span> sandpackEl <span class="token operator">=</span> document<span class="token punctuation">.</span><span class="token function">querySelector</span><span class="token punctuation">(</span><span class="token string">'sandpack-preset'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
		<span class="token keyword">const</span> options <span class="token operator">=</span> <span class="token punctuation">&#123;</span>
		  <span class="token literal-property property">closableTabs</span><span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
		  files<span class="token punctuation">,</span>
		  <span class="token literal-property property">customSetup</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
		    <span class="token string-property property">"dependencies"</span><span class="token operator">:</span> <span class="token punctuation">&#123;</span>
		      <span class="token string-property property">"lit"</span><span class="token operator">:</span> <span class="token string">"2.6.1"</span>
		    <span class="token punctuation">&#125;</span>
		  <span class="token punctuation">&#125;</span>
		<span class="token punctuation">&#125;</span><span class="token punctuation">;</span>
<p>		sandpackEl<span class="token punctuation">.</span>options <span class="token operator">=</span> options</p>
	</span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span>
<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>body</span><span class="token punctuation">></span></span></code><!-- HTML_TAG_END --></pre> <p data-svelte-h="svelte-nkoocs">Run your local development server, and you can see Sandpack Lit working without a framework:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/00-sandpack-lit-universal/vanilla.png" alt="Sandpack Lit running in VanillaJS"></div> </p> <p data-svelte-h="svelte-185hd3e">So how does Sandpack Lit work across all frameworks? Instead of being built using a framework, I’ve instead opted to use a handy native browser feature called <strong>web components</strong>.</p> <h2 data-svelte-h="svelte-1rsjavv">What the Heck are Web Components?</h2> <p data-svelte-h="svelte-rfvtdn">The browser offers developers a way to write reusable components without needing an external framework. They can create a custom element (with styles, attributes, and more), and use it like any other HTML element.</p> <p data-svelte-h="svelte-17uxvgm">You can even import and use web components made by other developers!</p> <p data-svelte-h="svelte-122z4ri"><a href="https://nolanlawson.com/2023/08/23/use-web-components-for-what-theyre-good-at/" rel>Nolan Lawson recently wrote</a> about the use cases that web components are best for:</p> <blockquote data-svelte-h="svelte-wuudhr"><p>You have some component at the leaf of the DOM tree, it doesn’t need to be rendered server-side, and it doesn’t <code>&lt;slot&gt;</code> any content inside of it. Examples include: a rich text editor, a calendar widget, a color picker, etc. To me, this is the most unambiguously slam-dunk use case for web components.</p></blockquote> <p data-svelte-h="svelte-1d6chfm">I feel that this applies perfectly to an embedded code editor, like Sandpack, since a code editor is a highly interactive client-side component that doesn’t rely on the consumer passing down child content.</p> <h2 data-svelte-h="svelte-hvccsc">Real-world usages of Sandpack Lit (Component Odyssey)</h2> <p data-svelte-h="svelte-16ie3h">While Sandpack Lit is still new, I’ve been using it over the last few months to build the exercises and code examples in my web development course <a href="/">Component Odyssey</a>. Component Odyssey is dedicated to helping developers learn the ins-and-outs of component library development.</p> <p data-svelte-h="svelte-498z14">I’m using Sandpack Lit to run browser-based code in the browser:</p> <p> <div class="small-image-wrapper svelte-1yqbv7r"><button class="fullscreen-icon small svelte-1yqbv7r" aria-label="Display full size image"><svg fill="var(--black)" width="16px" height="16px" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14 3.414L9.414 8 14 12.586v-2.583h2V16h-6v-1.996h2.59L8 9.414l-4.59 4.59H6V16H0v-5.997h2v2.583L6.586 8 2 3.414v2.588H0V0h16v6.002h-2V3.414zm-1.415-1.413H10V0H6v2H3.415L8 6.586 12.585 2z" fill-rule="evenodd"></path></svg></button> <img src="https://component-odyssey.com/images/articles/00-sandpack-lit-universal/component-odyssey.gif" alt="Sandpack Lit used in Component Odyssey to run a code exercise in the browser"></div> </p> <h2 data-svelte-h="svelte-11ql4ny">Learn more about Sandpack Lit</h2> <p data-svelte-h="svelte-1dhjhml">You may have noticed that I used the <code>sandpack-preset</code> web component. This is a component that renders a preset configuration of some additional components, ones that render the code editor, ones that render the preview, and one that sets up the shared context. Sandpack Lit also exports these components, so you can have more flexibility. If you’d like to learn more, you can check out the <a href="https://github.com/andrico1234/sandpack-lit" rel>Sandpack Lit GitHub repo</a>.</p> <h2 data-svelte-h="svelte-12kjvsr">What’s next for Sandpack Lit?</h2> <p data-svelte-h="svelte-4hsyq3">Sandpack Lit is still in early days, if there are features that you’d like to see added, please add an issue in the GitHub, or try your hand at implementing it yourself. If you like the look of Sandpack Lit, then please leave a GitHub star and share online!</p>
]]></content>
<pubDate>Mon, 23 Oct 2023 00:00:00 GMT</pubDate>
</item>
</channel>
</rss>
