<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://guilhermesimoes.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://guilhermesimoes.github.io/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-11-02T00:09:22+00:00</updated><id>https://guilhermesimoes.github.io/feed.xml</id><title type="html">Guilherme Simões</title><subtitle>The writings, experiments and assorted output of Guilherme Simões.</subtitle><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><entry><title type="html">Nullish Coalescing Operator Chart</title><link href="https://guilhermesimoes.github.io/blog/when-to-use-nullish-coalescing-operator-chart" rel="alternate" type="text/html" title="Nullish Coalescing Operator Chart" /><published>2026-10-21T20:11:44+00:00</published><updated>2026-10-21T20:11:44+00:00</updated><id>https://guilhermesimoes.github.io/blog/when-to-use-nullish-coalescing-operator-chart</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/when-to-use-nullish-coalescing-operator-chart"><![CDATA[<svg xmlns="http://www.w3.org/2000/svg" width="100%" class="mermaid-flowchart" viewBox="0 0 972 1590">
  <marker id="a" class="marker flowchart-v2" markerHeight="8" markerUnits="userSpaceOnUse" markerWidth="8" orient="auto" refX="5" refY="5" viewBox="0 0 10 10">
    <path d="m0 0 10 5-10 5z" class="a" />
  </marker>
  <g marker-end="url(#a)" class="edgePaths">
    <path d="M311.4 110v46" class="flowchart-link" />
    <path d="M272.73 318.43c-11.65 24.96-23.29 49.91-29.11 67.82s-5.82 28.77-5.82 34.2v5.43" class="flowchart-link" />
    <path d="M284 294l315 124c268 105 254 79 256 266v666.29c.42 43.7.42 87.41-1.04 114.72-1.45 27.3-4.36 38.2-5.81 43.66l-1.45 5.45" class="flowchart-link" />
    <path d="M190.79 578.15c-25.88 27.87-51.76 55.74-64.69 86.28-12.94 30.56-12.94 63.8-12.94 79v16.62" class="flowchart-link" />
    <path d="M284.81 578.15c25.88 27.87 51.76 55.74 64.69 75.1s12.94 30.22 13.5 34.5v5.43" class="flowchart-link" />
    <path d="M315.23 839.37c-28.11 27.93-56.21 55.87-70.27 89.33-14.05 33.47-14.05 72.47-14.05 91v19.5" class="flowchart-link" />
    <path d="M409.65 839.37c28.11 27.93 56.22 55.87 70.27 75.27s14.06 30.25 14.5 52v5.43" class="flowchart-link" />
    <path d="M454.5 1115.5c-39.31 43.34-65.73 73.03-78.94 104.56s-13.21 64.9-13.21 81.58v16.68" class="flowchart-link" />
    <path d="M539.5 1120c33.98 38.2 60.4 67.89 73.61 88.16s13.21 31.14 13.21 36.57v5.43" class="flowchart-link" />
    <path d="M594 1413.23c-11.4 22.73-22.82 45.46-31 66.77-5.71 16.8-5.71 27.66-5.71 33.09v5.43" class="flowchart-link" />
    <path d="M674.37 1396.18a8989 8989 0 0081.84 76.7 1766 1766 0 0041.13 36.84l6.52 5.66" class="flowchart-link" />
  </g>
  <g class="edgeLabels">
    <g class="edgeLabel">
      <path d="M224 381h28v23.2h-28z" class="background" />
      <text text-anchor="middle" transform="translate(238 398)">No</text>
    </g>
    <g class="edgeLabel">
      <path d="M520 381h28v23.2h-28z" class="background" />
      <text text-anchor="middle" transform="translate(534 398)">Yes</text>
    </g>
    <g class="edgeLabel">
      <path d="M108 650h33v23.2h-33Z" class="background" />
      <text text-anchor="middle" transform="translate(124 667)">Yes</text>
    </g>
    <g class="edgeLabel">
      <path d="M343 650h28v23.2h-28z" class="background" />
      <text text-anchor="middle" transform="translate(357 667)">No</text>
    </g>
    <g class="edgeLabel">
      <path d="M230 911h33v23.2h-33Z" class="background" />
      <text text-anchor="middle" transform="translate(246 928)">Yes</text>
    </g>
    <g class="edgeLabel">
      <path d="M474 911h28v23.2h-28z" class="background" />
      <text text-anchor="middle" transform="translate(488 928)">No</text>
    </g>
    <g class="edgeLabel">
      <path d="M360 1207h33v23.2h-33Z" class="background" />
      <text text-anchor="middle" transform="translate(377 1225)">Yes</text>
    </g>
    <g class="edgeLabel">
      <path d="M607 1207h28v23.2h-28z" class="background" />
      <text text-anchor="middle" transform="translate(621 1225)">No</text>
    </g>
    <g class="edgeLabel">
      <path d="M546 1470h33v23.2h-33Z" class="background" />
      <text text-anchor="middle" transform="translate(562 1487)">Yes</text>
    </g>
    <g class="edgeLabel">
      <path d="M751 1470h28v23.2h-28z" class="background" />
      <text text-anchor="middle" transform="translate(765 1487)">No</text>
    </g>
  </g>
  <g class="nodes">
    <g class="node">
      <path d="M181 6h260v102h-260Z" class="background" />
      <g class="label" transform="translate(200 30)">
        <foreignObject width="220" height="48">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table;max-width:220px;text-align:center;">
            <span class="nodeLabel">
              <p>
                When should you use <code class="highlighter-rouge">??</code> if you care about bundle size?
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="m311.51 356.72 97.64-97.64-97.64-97.64-97.64 97.64z" class="background" />
      <g class="label" transform="translate(252 236)">
        <foreignObject width="120" height="48">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;max-width:120px;text-align:center">
            <span class="nodeLabel">
              <p>
                Using ES2020 or above?
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="m238.3 625.17 97.64-97.64-97.64-97.64-97.64 97.64z" class="background" />
      <g class="label" transform="translate(174 515.5)">
        <foreignObject width="142" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:142px;text-align:center">
            <span class="nodeLabel">
              <p>
                Doing <code class="highlighter-rouge">num ?? 0</code>?
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="M712 1518h252v64H712Z" class="background" />
      <g class="label" transform="translate(742 1526)">
        <foreignObject width="192" height="48">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;max-width:192px;text-align:center">
            <span class="nodeLabel">
              <p>
                Sure, use <code class="highlighter-rouge">??</code> to your heart's content
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="M5 765h210v54H5Z" class="background" />
      <g class="label" transform="translate(37 780.5)">
        <foreignObject width="154" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:154px;text-align:center">
            <span class="nodeLabel">
              <p>
                Stop! Use <code class="highlighter-rouge">num || 0</code>
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="m362.95 886.58 94.12-94.12-94.12-94.13-94.13 94.13z" class="background" />
      <g class="label" transform="translate(300 781)">
        <foreignObject width="134" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:134px;text-align:center">
            <span class="nodeLabel">
              <p>
                Doing <code class="highlighter-rouge">str ?? ""</code>?
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="M128 1044h200v54h-200Z" class="background" />
      <g class="label" transform="translate(151 1059)">
        <foreignObject width="160" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:160px;text-align:center">
            <span class="nodeLabel">
              <p>
                Stop! Use <code class="highlighter-rouge">str || ""</code>
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="m494.48 1165 94.12-94.12-94.12-94.13-94.13 94.13z" class="background" />
      <g class="label" transform="translate(413 1059)">
        <foreignObject width="164" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:164px;text-align:center">
            <span class="nodeLabel">
              <p>
                Doing <code class="highlighter-rouge">bool ?? false</code>?
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="M236 1323h238v54H236Z" class="background" />
      <g class="label" transform="translate(265 1338)">
        <foreignObject width="194" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:194px;text-align:center">
            <span class="nodeLabel">
              <p>
                Stop! Use <code class="highlighter-rouge">bool || false</code>
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="m626.2 1444.83 94.55-94.53-94.54-94.54-94.53 94.54z" class="background" />
      <g class="label" transform="translate(560 1338)">
        <foreignObject width="140" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:140px;text-align:center">
            <span class="nodeLabel">
              <p>
                Doing <code class="highlighter-rouge">obj ?? {}</code>?
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
    <g class="node">
      <path d="M452 1524h204.1v54h-204.1z" class="background" />
      <g class="label" transform="translate(478 1539)">
        <foreignObject width="162" height="24">
          <div xmlns="http://www.w3.org/1999/xhtml" style="display:table-cell;white-space:nowrap;max-width:162px;text-align:center">
            <span class="nodeLabel">
              <p>
                Stop! Use <code class="highlighter-rouge">obj || {}</code>
              </p>
            </span>
          </div>
        </foreignObject>
      </g>
    </g>
  </g>
</svg>
<div class="wrapper">

  <p><a href="https://www.typescriptlang.org/play/?alwaysStrict=false&amp;target=6#code/G4QwTgBAdgrgtgGggZwC5iQIwPbYDZLaYBWA3AFDkD0VEAvA408y62+05bHBAPy8QADNVrBk5bhAA+UoZRr0OS5SoaU0kfhABE2kRDHkN02bvm1Vlq53I58fAQDMQeZAFN9hu3hMRnrj31rYNVKImIHCABvAF9PcXDfWKA">Proof</a>:</p>

  <div class="centered centered--spaced">

    <div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// source code</span>
<span class="nx">num</span> <span class="o">||</span> <span class="mi">0</span>
<span class="c1">// vs</span>
<span class="nx">num</span> <span class="o">??</span> <span class="mi">0</span>
</code></pre></div>    </div>

    <div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// code transpiled to target &lt; ES2020</span>
<span class="nx">num</span> <span class="o">||</span> <span class="mi">0</span><span class="p">;</span>
<span class="c1">// vs</span>
<span class="nx">num</span> <span class="o">!==</span> <span class="kc">null</span> <span class="o">&amp;&amp;</span> <span class="nx">num</span> <span class="o">!==</span> <span class="k">void</span> <span class="mi">0</span> <span class="p">?</span> <span class="nx">num</span> <span class="p">:</span> <span class="mi">0</span><span class="p">;</span>
</code></pre></div>    </div>

  </div>

</div>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Perf" /><category term="JavaScript" /><category term="Web" /><summary type="html"><![CDATA[No Yes Yes No Yes No Yes No Yes No When should you use ?? if you care about bundle size? Using ES2020 or above? Doing num ?? 0? Sure, use ?? to your heart's content Stop! Use num || 0 Doing str ?? ""? Stop! Use str || "" Doing bool ?? false? Stop! Use bool || false Doing obj ?? {}? Stop! Use obj || {}]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/flamingos.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/flamingos.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Making dark mode play nicely with bfcache</title><link href="https://guilhermesimoes.github.io/blog/making-dark-mode-work-with-bfcache" rel="alternate" type="text/html" title="Making dark mode play nicely with bfcache" /><published>2026-04-09T19:37:45+00:00</published><updated>2026-04-09T19:37:45+00:00</updated><id>https://guilhermesimoes.github.io/blog/making-dark-mode-work-with-bfcache</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/making-dark-mode-work-with-bfcache"><![CDATA[<p>I try to avoid making this blog be about adding features to the blog, but I recently implemented a <a href="https://bnijenhuis.nl/notes/user-friendly-dark-mode/">dark mode</a> and hit a few snags that I felt might be worth talking about.</p>

<p>In addition to the dark mode, I added a toggle button to allow the reader to choose between dark, light and <a href="https://kilianvalkhof.com/2020/design/your-dark-mode-toggle-is-broken/">system</a> themes. The button also <a href="https://www.smashingmagazine.com/2024/03/setting-persisting-color-scheme-preferences-css-javascript/">persists the user preference</a> so the reading experience is consistent across pages.</p>

<p>I thought everything was working great, until I noticed what happened when I navigated to a page, changed the theme and then pressed the browser’s back button:</p>

<video class="ratio-16-9 mb-1" src="/assets/videos/dark-mode-bf-cache.mp4" poster="/assets/images/dark-mode-bf-cache.png" loading="lazy" controls=""></video>

<p>The previous page appeared with the old theme! This was unexpected because the <code class="language-plaintext highlighter-rouge">&lt;head&gt;</code> element contained this snippet<sup id="fnref:1"><a href="#fn:1" class="footnote" rel="footnote" role="doc-noteref">1</a></sup>:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;script&gt;</span>
  <span class="kd">let</span> <span class="nx">theme</span> <span class="o">=</span> <span class="nx">localStorage</span><span class="p">.</span><span class="nf">getItem</span><span class="p">(</span><span class="dl">'</span><span class="s1">theme</span><span class="dl">'</span><span class="p">);</span>
  <span class="k">if </span><span class="p">(</span><span class="nx">theme</span><span class="p">)</span> <span class="p">{</span>
    <span class="nb">document</span><span class="p">.</span><span class="nx">documentElement</span><span class="p">.</span><span class="nx">classList</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="nx">theme</span><span class="p">}</span><span class="s2">-theme`</span><span class="p">);</span>
  <span class="p">}</span>
<span class="nt">&lt;/script&gt;</span>
</code></pre></div></div>

<p>This should be guaranteeing that the right theme was applied in each page navigation. However, the browser was retrieving the page from its <a href="https://web.dev/articles/bfcache">back-forward cache (bfcache)</a>, an optimization that enables instant navigation to previously visited pages but that can cause issues like this. Fixing this required three separate changes.</p>

<h3 id="1-switching-the-stale-theme-on-bfcache-restore"><a href="#1-switching-the-stale-theme-on-bfcache-restore"></a>1. Switching the stale theme on bfcache restore</h3>

<p>The bfcache stores a complete snapshot of each page in memory – including the DOM, CSS and JavaScript state. When navigating back, the previous page is restored from such a snapshot. Since the page is not loaded from scratch, the JavaScript code in the <code class="language-plaintext highlighter-rouge">&lt;head&gt;</code> does not run (again).</p>

<p>Even though <code class="language-plaintext highlighter-rouge">localStorage</code> is always up-to-date, when a user changes themes and then goes back in browser history, the previous page is restored with the stale theme. This stale theme issue also manifests when a user goes back in browser history, changes themes and then goes <em>forward</em> in browser history. A little far-fetched, but still a possible scenario.</p>

<p>The solution to both cases is to listen for the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event"><code class="language-plaintext highlighter-rouge">pageshow</code></a> event and re-apply the theme stored in <code class="language-plaintext highlighter-rouge">localStorage</code>:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">self</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">pageshow</span><span class="dl">'</span><span class="p">,</span> <span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">if </span><span class="p">(</span><span class="nx">event</span><span class="p">.</span><span class="nx">persisted</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">let</span> <span class="nx">theme</span> <span class="o">=</span> <span class="nx">localStorage</span><span class="p">.</span><span class="nf">getItem</span><span class="p">(</span><span class="dl">'</span><span class="s1">theme</span><span class="dl">'</span><span class="p">);</span>
    <span class="kd">let</span> <span class="nx">root</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">documentElement</span><span class="p">;</span>
    <span class="nx">root</span><span class="p">.</span><span class="nx">classList</span><span class="p">.</span><span class="nf">remove</span><span class="p">(</span><span class="dl">'</span><span class="s1">light-theme</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">dark-theme</span><span class="dl">'</span><span class="p">);</span>
    <span class="k">if </span><span class="p">(</span><span class="nx">theme</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">root</span><span class="p">.</span><span class="nx">classList</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="nx">theme</span><span class="p">}</span><span class="s2">-theme`</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">event.persisted</code> flag indicates whether the browser restored the page from the bfcache or loaded it fresh.</p>

<h3 id="2-preventing-a-flash-of-incorrect-color-theme"><a href="#2-preventing-a-flash-of-incorrect-color-theme"></a>2. Preventing a flash of incorrect color theme</h3>

<p>With the first fix in place, the theme switch happened correctly, but with a visible flash of color. The problem was that I had decided to make the theme swapping a little smoother, so I had added a CSS color transition to the page.
This now meant that when <code class="language-plaintext highlighter-rouge">pageshow</code> switched themes it would animate from the old theme to the new one.</p>

<p>To solve this, all CSS transitions were moved inside an <code class="language-plaintext highlighter-rouge">animatable</code> class, initially added to the <code class="language-plaintext highlighter-rouge">&lt;html&gt;</code> element:</p>

<div class="language-scss highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nc">.animatable</span> <span class="p">{</span>
  <span class="nt">body</span> <span class="p">{</span>
    <span class="nl">transition-property</span><span class="p">:</span> <span class="nb">color</span><span class="o">,</span> <span class="n">background-color</span><span class="p">;</span>
    <span class="nl">transition-duration</span><span class="p">:</span> <span class="m">0</span><span class="mi">.3s</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="nc">.theme-toggle</span> <span class="p">{</span>
    <span class="cm">/* Button transitions */</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Then, this class is removed when the stale theme is updated on <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/pageshow_event"><code class="language-plaintext highlighter-rouge">pageshow</code></a>:</p>

<div class="language-diff highlighter-rouge"><div class="highlight"><pre class="highlight"><code> self.addEventListener('pageshow', (event) =&gt; {
   if (event.persisted) {
     let theme = localStorage.getItem('theme');
     let root = document.documentElement;
<span class="gd">-    root.classList.remove('light-theme', 'dark-theme');
</span><span class="gi">+    root.classList.remove('light-theme', 'dark-theme', 'animatable');
</span>     if (theme) {
       root.classList.add(`${theme}-theme`);
     }
<span class="gi">+    setTimeout(() =&gt; {
+      root.classList.add('animatable');
+    });
</span>   }
 });
</code></pre></div></div>

<p>Finally, the class is added back after the browser has had a chance to paint the new theme (I opted for a <code class="language-plaintext highlighter-rouge">setTimeout</code>).<sup id="fnref:2"><a href="#fn:2" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>

<h3 id="3-ensuring-the-toggle-button-switched-to-the-right-theme"><a href="#3-ensuring-the-toggle-button-switched-to-the-right-theme"></a>3. Ensuring the toggle button switched to the right theme</h3>

<p>My initial implementation of the theme toggle button cycled through all the themes using an index stored in a JavaScript variable:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">themes</span> <span class="o">=</span> <span class="p">[</span><span class="dl">'</span><span class="s1">system</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">dark</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">light</span><span class="dl">'</span><span class="p">];</span>
<span class="kd">let</span> <span class="nx">userTheme</span> <span class="o">=</span> <span class="nx">localStorage</span><span class="p">.</span><span class="nf">getItem</span><span class="p">(</span><span class="dl">'</span><span class="s1">theme</span><span class="dl">'</span><span class="p">)</span> <span class="o">||</span> <span class="dl">'</span><span class="s1">system</span><span class="dl">'</span><span class="p">;</span>
<span class="kd">let</span> <span class="nx">themeIndex</span> <span class="o">=</span> <span class="nx">themes</span><span class="p">.</span><span class="nf">indexOf</span><span class="p">(</span><span class="nx">userTheme</span><span class="p">);</span>

<span class="nx">themeToggle</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="nx">themeIndex</span> <span class="o">=</span> <span class="p">(</span><span class="nx">themeIndex</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">%</span> <span class="nx">themes</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span>
  <span class="kd">let</span> <span class="nx">nextTheme</span> <span class="o">=</span> <span class="nx">themes</span><span class="p">[</span><span class="nx">themeIndex</span><span class="p">];</span>
  <span class="c1">// update page to use the next theme</span>
<span class="p">});</span>
</code></pre></div></div>

<p>This seemed ok, but it would swap to the wrong theme after a page was restored from the bfcache with a stale theme. On <code class="language-plaintext highlighter-rouge">pageshow</code>, the theme was updated, but the in-memory <code class="language-plaintext highlighter-rouge">themeIndex</code> was not!<sup id="fnref:3"><a href="#fn:3" class="footnote" rel="footnote" role="doc-noteref">3</a></sup> So the <code class="language-plaintext highlighter-rouge">themeIndex</code> would stop matching the currently chosen theme.</p>

<p>Rather than syncing the index variable on <code class="language-plaintext highlighter-rouge">pageshow</code>, I opted for forgoing the <code class="language-plaintext highlighter-rouge">themeIndex</code> variable and deriving the current theme index from the DOM on each button click:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">themeToggle</span><span class="p">.</span><span class="nf">addEventListener</span><span class="p">(</span><span class="dl">'</span><span class="s1">click</span><span class="dl">'</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">let</span> <span class="nx">themeIndex</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">for </span><span class="p">(</span><span class="kd">let</span> <span class="nx">className</span> <span class="k">of</span> <span class="nx">root</span><span class="p">.</span><span class="nx">classList</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">let</span> <span class="nx">match</span> <span class="o">=</span> <span class="nx">className</span><span class="p">.</span><span class="nf">match</span><span class="p">(</span><span class="sr">/</span><span class="se">(</span><span class="sr">.*</span><span class="se">)</span><span class="sr">-theme/</span><span class="p">);</span>
    <span class="kd">let</span> <span class="nx">theme</span> <span class="o">=</span> <span class="nx">match</span> <span class="o">&amp;&amp;</span> <span class="nx">match</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
    <span class="k">if </span><span class="p">(</span><span class="nx">theme</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">themeIndex</span> <span class="o">=</span> <span class="nx">themes</span><span class="p">.</span><span class="nf">indexOf</span><span class="p">(</span><span class="nx">theme</span><span class="p">);</span>
      <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">}</span>
  <span class="nx">themeIndex</span> <span class="o">=</span> <span class="p">(</span><span class="nx">themeIndex</span> <span class="o">+</span> <span class="mi">1</span><span class="p">)</span> <span class="o">%</span> <span class="nx">themes</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span>
  <span class="kd">let</span> <span class="nx">nextTheme</span> <span class="o">=</span> <span class="nx">themes</span><span class="p">[</span><span class="nx">themeIndex</span><span class="p">];</span>
  <span class="c1">// update page to use the next theme</span>
<span class="p">});</span>
</code></pre></div></div>

<p>No more stale state to worry about. The less state, the better.</p>

<hr />

<p>Making the look of this blog configurable by the reader ended up being more complex than I expected. Animating the theme change also complicated things further. If I had kept it simple (just a regular dark mode using <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/At-rules/@media/prefers-color-scheme"><code class="language-plaintext highlighter-rouge">@media (prefers-color-scheme: dark)</code></a> and <a href="https://www.bram.us/2023/10/09/the-future-of-css-easy-light-dark-mode-color-switching-with-light-dark/"><code class="language-plaintext highlighter-rouge">light-dark()</code></a>) I wouldn’t have hit so many problems.</p>

<p>Still, the issues I found were not really related to dark mode. They were just the sum of the bfcache plus a user choice that persisted across page navigations. Issues like these can surface on any multi-page site that keeps user state. An e-commerce site may show a stale shopping cart or wishlist when a user navigates back. Or a news site may display articles in a grid layout even after a user changes it to a list layout if he then navigates back.</p>

<p>The point is that while the <a href="https://web.dev/articles/bfcache">bfcache</a> makes it really fast to access previous pages, it does introduce its own set of challenges. Making dark mode work seamlessly is just one of those challenges.<sup id="fnref:4"><a href="#fn:4" class="footnote" rel="footnote" role="doc-noteref">4</a></sup></p>

<p>Incidentally, I tested my favourite tech news site, <a href="https://arstechnica.com/">Ars Technica</a>, and it has the same stale theme issue! It’s a minor quibble, but this sort of stuff might be more common than I thought. And it’s not that hard to fix!</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1">
      <p>If this snippet is included at the bottom of the page (and not in the <code class="language-plaintext highlighter-rouge">&lt;head&gt;</code> element) we run the risk of witnessing a flash of incorrect color theme. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
    <li id="fn:2">
      <p>Another option is to initially omit the <code class="language-plaintext highlighter-rouge">animatable</code> class from the <code class="language-plaintext highlighter-rouge">&lt;html&gt;</code> element, and only add it when the theme toggle button is clicked. Then remove the class after the animations end. <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
    <li id="fn:3">
      <p>Remember that the bfcache stores the <em>entire</em> page and its current state, including the JavaScript stack which contains all the local variables like <code class="language-plaintext highlighter-rouge">themeIndex</code>. <a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
    <li id="fn:4">
      <p>Another challenge is analytics. Pages restored from the bfcache don’t count as new pageviews. If we want to count those we also need to use the <code class="language-plaintext highlighter-rouge">pageshow</code> event. <a href="#fnref:4" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Web" /><category term="JavaScript" /><category term="CSS" /><summary type="html"><![CDATA[I try to avoid making this blog be about adding features to the blog, but I recently implemented a dark mode and hit a few snags that I felt might be worth talking about.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/ship-by-king-carlos-I.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/ship-by-king-carlos-I.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">The Importance Of (The Main Thread) Being Idle</title><link href="https://guilhermesimoes.github.io/blog/the-importance-of-the-main-thread-being-idle" rel="alternate" type="text/html" title="The Importance Of (The Main Thread) Being Idle" /><published>2026-03-28T08:57:09+00:00</published><updated>2026-03-28T08:57:09+00:00</updated><id>https://guilhermesimoes.github.io/blog/the-importance-of-the-main-thread-being-idle</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/the-importance-of-the-main-thread-being-idle"><![CDATA[<p><a href="https://www.youtube.com/watch?v=jySfU10IQu4&amp;t=17s">Mandatory listening for this post</a>.</p>

<p>The browser’s main thread is responsible for <em>everything</em>: running JavaScript, handling user input, laying out the page and painting the screen. It can only do one thing at a time. So when JavaScript keeps it busy everything else grinds to a halt.</p>

<p>Give the demo a try. Hit <strong>Work</strong> and see that most animations stop immediately, scrolling stops working (in some browsers), and all interactive elements (buttons, text fields, etc.) become unresponsive. The main thread is busy and has no time for you.</p>

<p>Now hit <strong>Work inside worker</strong> and see that all the animations keep running and the interactive elements keep being, well, interactive. It may seem like nothing is happening, but all the work is occurring inside a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker">Web Worker</a> – a separate thread with its own JavaScript runtime. The main thread doesn’t even notice and keeps running smoothly.</p>

<hr />

<p>If you want to understand how Web Workers work, I encourage you to look at the code. It’s about 30 lines of JavaScript. The entire Web Worker API is quite simple: <a href="https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage"><code class="language-plaintext highlighter-rouge">postMessage</code></a> to send and a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/message_event"><code class="language-plaintext highlighter-rouge">message</code></a> event listener to receive.</p>

<p>I added logs so you can open your browser’s devtools and see the conversation between the two threads play out as you click each button. If you refresh the page, you’ll also see the main thread creating the worker and the worker announcing it’s ready.</p>

<p>As for the animations, the key point is that some animations keep running despite the main thread being blocked because their properties use hardware acceleration:</p>

<ul>
  <li>The spinning square uses the <code class="language-plaintext highlighter-rouge">transform</code> property, which is GPU-accelerated.</li>
  <li>The fading square uses the <code class="language-plaintext highlighter-rouge">opacity</code> property, which is also GPU-accelerated.</li>
  <li>The moving square is <strong>incorrectly</strong> animated using the <code class="language-plaintext highlighter-rouge">left</code> and <code class="language-plaintext highlighter-rouge">top</code> properties, which are not GPU-accelerated. A correct animation should use the <code class="language-plaintext highlighter-rouge">transform: translate(x, y)</code> property instead.</li>
  <li>The color-changing square uses a combination of the <code class="language-plaintext highlighter-rouge">background-color</code> property and a custom property (<code class="language-plaintext highlighter-rouge">--hue</code>), which I was expecting to be GPU-accelerated, but aparently it is not.</li>
</ul>

<p>Reading <a href="https://web.dev/articles/animations-guide">How to create high-performance CSS animations</a> should help you understand when an animation uses hardware acceleration. And <a href="https://css-triggers.com/">CSS Triggers</a> is a great resource for information on which properties trigger layout, paint and composite steps. But this is another topic.</p>

<hr />

<p>Workers can’t touch the DOM, but they can do everything else: fetch data, crunch numbers, parse large files, run algorithms. Anything CPU-intensive that would otherwise jank your UI is a good candidate to move to a worker. Reserve the main thread for what only it can do: handling user input and rendering the UI.</p>

<p>Keep the main thread idle, and your page will feel fast and smooth.</p>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Perf" /><category term="Web" /><category term="JavaScript" /><category term="Interactive" /><summary type="html"><![CDATA[Mandatory listening for this post.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/squares.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/squares.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Web Component: Hand-drawn Checkbox</title><link href="https://guilhermesimoes.github.io/blog/web-component-hand-drawn-checkbox" rel="alternate" type="text/html" title="Web Component: Hand-drawn Checkbox" /><published>2025-12-07T01:40:25+00:00</published><updated>2025-12-07T01:40:25+00:00</updated><id>https://guilhermesimoes.github.io/blog/web-component-hand-drawn-checkbox</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/web-component-hand-drawn-checkbox"><![CDATA[<p>This is my first try at a Web Component. This one <em>progressively enhances</em> an <code class="language-plaintext highlighter-rouge">&lt;input type="checkbox" /&gt;</code>. So even if the user blocks JavaScript, a regular HTML checkbox is still rendered. The custom element can be used like this:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;handdrawn-checkbox&gt;</span>
  <span class="nt">&lt;input</span> <span class="na">type=</span><span class="s">"checkbox"</span> <span class="na">name=</span><span class="s">"box1"</span> <span class="na">checked</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/handdrawn-checkbox&gt;</span>
</code></pre></div></div>

<p>It’s a bit verbose, but it’s the only way to ensure that the progressive enhancement works. The element can also be declared this way:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;handdrawn-checkbox</span> <span class="na">name=</span><span class="s">"box2"</span><span class="nt">&gt;&lt;/handdrawn-checkbox&gt;</span>
</code></pre></div></div>

<p>This still works because this custom element adds a default checkbox in its constructor. The drawback is that this renders nothing if the user blocks JavaScript.</p>

<hr />

<p>Here’s the gist of how this Web Component works:</p>

<ol>
  <li>
    <p>Using the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/slot"><code class="language-plaintext highlighter-rouge">slot</code></a> element, we <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_templates_and_slots">create a portal in the template</a> where the original checkbox will be inserted.</p>
  </li>
  <li>
    <p>Using the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/::slotted"><code class="language-plaintext highlighter-rouge">::slotted</code></a> pseudo-element, we hide the original checkbox. We need to hide it with <code class="language-plaintext highlighter-rouge">opacity: 0</code> so that it remains interactive and accessible. We can’t hide it with <code class="language-plaintext highlighter-rouge">visibility: hidden</code> or <code class="language-plaintext highlighter-rouge">display: none</code>.</p>
  </li>
  <li>
    <p>Using the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Selectors/:host"><code class="language-plaintext highlighter-rouge">:host</code></a> pseudo-class (which targets the root of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM">shadow DOM</a>) we style the SVG element so that it has the same position and dimensions as the checkbox’s. We also use <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/pointer-events"><code class="language-plaintext highlighter-rouge">pointer-events: none</code></a> so that mouse clicks and touch events can properly reach the (invisible but still interactive) checkbox.</p>
  </li>
  <li>
    <p>Finally, using the <code class="language-plaintext highlighter-rouge">connectedCallback</code> function (which is called when the element is added to the document) we render the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_components/Using_shadow_DOM">shadow DOM</a> and listen for <code class="language-plaintext highlighter-rouge">change</code> events coming from the checkbox. That way we can redraw our SVG element when the checkbox is toggled.</p>
  </li>
</ol>

<p>And that’s it! Broken down like this it seems simple enough but it took me quite a bit to reach this solution. I quite like this <a href="https://meyerweb.com/eric/thoughts/2023/11/01/blinded-by-the-light-dom/">technique of augmenting an existing HTML element with a custom element</a>. It’s portable. It’s accessible. And it feels like magic.</p>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Web" /><category term="JavaScript" /><category term="Interactive" /><summary type="html"><![CDATA[This is my first try at a Web Component. This one progressively enhances an &lt;input type="checkbox" /&gt;. So even if the user blocks JavaScript, a regular HTML checkbox is still rendered. The custom element can be used like this:]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/hand-drawn-checkboxes.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/hand-drawn-checkboxes.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Classes considered harmful when authoring a JavaScript library</title><link href="https://guilhermesimoes.github.io/blog/classes-considered-harmful-when-authoring-a-js-lib" rel="alternate" type="text/html" title="Classes considered harmful when authoring a JavaScript library" /><published>2025-11-23T19:53:58+00:00</published><updated>2025-11-23T19:53:58+00:00</updated><id>https://guilhermesimoes.github.io/blog/classes-considered-harmful-when-authoring-a-js-lib</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/classes-considered-harmful-when-authoring-a-js-lib"><![CDATA[<p>Let me start by saying I’m the biggest <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">OOP</a> fan. I love Ruby. I have a copy of <a href="https://www.poodr.com/">POODR</a> on my bookcase. I look back fondly to the times of <code class="language-plaintext highlighter-rouge">React.createClass({ mixins: [MyMixin], ... })</code>. I loathe HOCs and hooks and whatever patterns <a href="https://en.wikipedia.org/wiki/Functional_programming">FP</a> zealots have been trying to push for the past couple of years. However, classes and OOP may not always be the best approach.</p>

<p>Also, I’m aware of the <a href="https://meyerweb.com/eric/comment/chech.html">“Considered Harmful” Essays Considered Harmful</a> essay – I’m being cheeky with the title.</p>

<p>So with that out of the way, let’s go.</p>

<hr />

<p>Performance is critical when writing a JavaScript library meant for the browser. There are two main aspects to performance on the web: the speed of the code – the faster, the better – and the size of the code – the smaller, the better. The more code gets included in a website, the more time the browser spends downloading, decompressing, parsing and executing it. So shipping less code to the browser is of the utmost importance.</p>

<p>The problem of using a class to build a JavaScript service is that it leads to the code being larger than it actually needs to be, for two reasons.</p>

<h3 id="1-classes-are-not-tree-shakeable"><a href="#1-classes-are-not-tree-shakeable"></a>1. Classes are not tree-shakeable</h3>

<p>That’s right. If we import a class with 20 methods and we only use 1 method <strong>everything gets bundled</strong>.</p>

<p>Minifiers / compressors such as <a href="https://try.terser.org/">Terser</a>, <a href="https://play.swc.rs/">SWC</a> and <a href="https://esbuild.github.io/try/">esbuild</a> (which I will simply call “bundlers”) do not tree-shake unused class methods because it is dangerous to do so. For example, a bundler could remove a class method, believing it to be unused, that some code could be calling dynamically with <code class="language-plaintext highlighter-rouge">classInstance[dynamicMethodName]()</code>. But that would result in the code blowing up with an <code class="language-plaintext highlighter-rouge">Uncaught TypeError: classInstance.dynamicMethodName is not a function</code>.
Since bundlers cannot determine whether a certain method is used or not, they do not take risks and do not tree-shake class methods.</p>

<h3 id="2-class-properties-and-methods-are-not-minifiable"><a href="#2-class-properties-and-methods-are-not-minifiable"></a>2. Class properties and methods are not minifiable</h3>

<p>For the same reasons that bundlers cannot remove properties and methods, they also cannot rename them.
Some code could be calling <code class="language-plaintext highlighter-rouge">Object.keys(classInstance)</code> to get the names of its properties. Or the code could be using <code class="language-plaintext highlighter-rouge">classInstance.hasOwnProperty(propertyName)</code> to check for a certain property. So bundlers simply can’t rename these properties and methods as they wish.</p>

<p>The same is true even for <em>private</em> properties and methods. <a href="/blog/minifying-private-properties-and-methods-with-terser">And while there are ways to minify those</a>, a lot can definitely go wrong.</p>

<hr />

<p>This is a huge issue in the JavaScript tooling ecosystem, <a href="https://marvinh.dev/blog/speeding-up-javascript-ecosystem-part-4/">as Marvin Hagemeister brilliantly explains</a>:</p>

<blockquote>
  <p>A recurring problem in various js tools is that they are composed of a couple of big classes that pull in everything instead of only the code you need. Those classes always start out small and with good intentions to be lean, but somehow they just get bigger and bigger. It becomes harder and harder to ensure that you’re only loading the code you need. This reminds me of this quote from Joe Armstrong (creator of the Erlang programming language):</p>

  <blockquote>
    <p>You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.</p>
  </blockquote>
</blockquote>

<p>And this problem isn’t exclusive to packages published on NPM. Many companies’ internal codebases have the same issue. As initial requirements change and new requirements are added, these classes mutate and grow. Inevitably this leads to huge (and slow) websites being served to users worldwide.</p>

<p>So what can we do about this? Is there an alternative, better way to author a JavaScript library?</p>

<p>Well, bundlers are already very good at <a href="https://cube.dev/blog/how-to-build-tree-shakeable-javascript-libraries">tree-shaking unused exports</a>. If we import and use 1 function from a module that exports 20 functions, only that one function gets bundled.</p>

<p>So when writing a JavaScript service we should avoid exposing its API through classes and public methods. Instead, expose it through named exports!</p>

<p>Instead of this:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// lib</span>
<span class="k">export</span> <span class="kd">class</span> <span class="nc">Chirpy</span> <span class="p">{</span>
  <span class="nf">constructor</span><span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">options</span> <span class="o">=</span> <span class="nx">options</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="nf">chirp</span><span class="p">(</span><span class="nx">message</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">options</span><span class="p">.</span><span class="nx">endpoint</span><span class="p">}</span><span class="s2">/chirp`</span><span class="p">,</span> <span class="p">{</span>
      <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
      <span class="na">body</span><span class="p">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nf">stringify</span><span class="p">(</span><span class="nx">message</span><span class="p">),</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nf">then</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">parseJson</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="nf">parseJson</span><span class="p">(</span><span class="nx">response</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">response</span><span class="p">.</span><span class="nf">json</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>
<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// usage</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">Chirpy</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">chirpy</span><span class="dl">'</span><span class="p">;</span>

<span class="kd">const</span> <span class="nx">client</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Chirpy</span><span class="p">(</span><span class="nx">config</span><span class="p">);</span>
<span class="nx">client</span><span class="p">.</span><span class="nf">chirp</span><span class="p">(</span><span class="dl">'</span><span class="s1">hello</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div></div>

<p>We can do this<sup id="fnref:1"><a href="#fn:1" class="footnote" rel="footnote" role="doc-noteref">1</a></sup><sup id="fnref:2"><a href="#fn:2" class="footnote" rel="footnote" role="doc-noteref">2</a></sup>:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// lib</span>
<span class="kd">let</span> <span class="nx">options</span><span class="p">;</span>

<span class="k">export</span> <span class="kd">function</span> <span class="nf">initialise</span><span class="p">(</span><span class="nx">opts</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">options</span> <span class="o">=</span> <span class="nx">opts</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">export</span> <span class="kd">function</span> <span class="nf">chirp</span><span class="p">(</span><span class="nx">message</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">return</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="nx">options</span><span class="p">.</span><span class="nx">endpoint</span><span class="p">}</span><span class="s2">/chirp`</span><span class="p">,</span> <span class="p">{</span>
    <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">body</span><span class="p">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nf">stringify</span><span class="p">(</span><span class="nx">message</span><span class="p">),</span>
  <span class="p">})</span>
  <span class="p">.</span><span class="nf">then</span><span class="p">(</span><span class="nx">parseJson</span><span class="p">);</span>
<span class="p">}</span>

<span class="kd">function</span> <span class="nf">parseJson</span><span class="p">(</span><span class="nx">response</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">return</span> <span class="nx">response</span><span class="p">.</span><span class="nf">json</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>
<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// usage</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">initialise</span><span class="p">,</span> <span class="nx">chirp</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">chirpy</span><span class="dl">'</span><span class="p">;</span>

<span class="nf">initialise</span><span class="p">(</span><span class="nx">config</span><span class="p">);</span>
<span class="nf">chirp</span><span class="p">(</span><span class="dl">'</span><span class="s1">hello</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div></div>

<p>This pattern <a href="/blog/service-class-vs-service-module">results in a reduced bundle size</a> due to the two reasons we observed previously. First, “private” functions like <code class="language-plaintext highlighter-rouge">parseJson</code> and “private” variables like <code class="language-plaintext highlighter-rouge">options</code> are untouchable from outside the module, so bundlers can minify them. And second, module exports that are unused can be tree-shaken by bundlers.</p>

<p>This pattern also gives us the freedom to increase the public API of our library (by adding more exported functions to the module) without having to worry about it affecting our consumers’ bundle sizes. The functions are only included in consumers’ bundles if they get imported, otherwise they are tree-shaken.</p>

<p>I call this pattern the <strong>Service Module</strong>. Use it whenever possible instead of service classes, classes with static methods or singletons. You know, it’s funny, I remember the <a href="https://web.archive.org/web/20190210024925/https://www.oreilly.com/library/view/learning-javascript-design/9781449334840/ch09s02.html">Module Pattern</a> being discussed a long, long time ago as a way to isolate and organize JavaScript modules, way before the keywords <code class="language-plaintext highlighter-rouge">import</code> and <code class="language-plaintext highlighter-rouge">export</code> were even part of modern JavaScript. Time to bring it back!</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1">
      <p>With this pattern we can still keep the previous API more or less intact by doing the following:</p>

      <div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// usage</span>
<span class="k">import</span> <span class="o">*</span> <span class="nx">as</span> <span class="nx">Chirpy</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">chirpy</span><span class="dl">'</span><span class="p">;</span>

<span class="nx">Chirpy</span><span class="p">.</span><span class="nf">initialise</span><span class="p">(</span><span class="nx">config</span><span class="p">);</span>
<span class="nx">Chirpy</span><span class="p">.</span><span class="nf">chirp</span><span class="p">(</span><span class="dl">'</span><span class="s1">hello</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div>      </div>

      <p>But <code class="language-plaintext highlighter-rouge">import * as Something</code> is not tree-shakeable, so we should avoid using it if we care about our bundle size. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
    <li id="fn:2">
      <p>A drawback of this pattern is that consumers are no longer able to create two different instances of the same class:</p>

      <div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// usage</span>
<span class="k">import</span> <span class="p">{</span> <span class="nx">Chirpy</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">chirpy</span><span class="dl">'</span><span class="p">;</span>

<span class="kd">const</span> <span class="nx">client1</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Chirpy</span><span class="p">(</span><span class="nx">config</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">client2</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">Chirpy</span><span class="p">(</span><span class="nx">anotherConfig</span><span class="p">);</span>

<span class="nx">client1</span><span class="p">.</span><span class="nf">chirp</span><span class="p">(</span><span class="dl">'</span><span class="s1">hello</span><span class="dl">'</span><span class="p">);</span>
<span class="nx">client2</span><span class="p">.</span><span class="nf">chirp</span><span class="p">(</span><span class="dl">'</span><span class="s1">hey</span><span class="dl">'</span><span class="p">);</span>
</code></pre></div>      </div>

      <p>But if creating multiple instances of the same service doesn’t make sense for your JavaScript library, then this isn’t an issue. <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Perf" /><category term="JavaScript" /><summary type="html"><![CDATA[Let me start by saying I’m the biggest OOP fan. I love Ruby. I have a copy of POODR on my bookcase. I look back fondly to the times of React.createClass({ mixins: [MyMixin], ... }). I loathe HOCs and hooks and whatever patterns FP zealots have been trying to push for the past couple of years. However, classes and OOP may not always be the best approach.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/class-system.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/class-system.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Writing metadata to CBZ files with Calibre</title><link href="https://guilhermesimoes.github.io/blog/writing-metadata-to-cbz-with-calibre" rel="alternate" type="text/html" title="Writing metadata to CBZ files with Calibre" /><published>2025-10-25T17:16:12+00:00</published><updated>2025-10-25T17:16:12+00:00</updated><id>https://guilhermesimoes.github.io/blog/writing-metadata-to-cbz-with-calibre</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/writing-metadata-to-cbz-with-calibre"><![CDATA[<p>Comic books and mangas are usually stored as comic book archives, a type of file for the purpose of sequential viewing of images. This archive file is not a distinct file format but merely a filename extension naming convention. The filename extension indicates the archive type used:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">.cb7</code> → 7z</li>
  <li><code class="language-plaintext highlighter-rouge">.cbr</code> → RAR</li>
  <li><code class="language-plaintext highlighter-rouge">.cbz</code> → ZIP</li>
</ul>

<p>I recommend sticking to <code class="language-plaintext highlighter-rouge">.cbz</code> for compatibility and speed. All images inside the archive should already be compressed (using <a href="https://github.com/oxipng/oxipng">Oxipng</a>, for example). Compressed data doesn’t compress well, so it’s unlikely that <code class="language-plaintext highlighter-rouge">.cb7</code> improves much. And an ebook reader may be slower to open such a file or not open it at all.</p>

<hr />

<p>To write metadata (such as the author or publisher) to a CBZ file, we can use <a href="https://calibre-ebook.com/">Calibre</a> with the <a href="https://github.com/dickloraine/EmbedComicMetadata">EmbedComicMetadata</a> plugin. After updating the book on Calibre, select it and click the EmbedComicMetadata icon in the toolbar to embed the metadata in the archive file. To verify that everything worked correctly, unzip the CBZ file (using <a href="https://www.7-zip.org/">7-Zip</a>, for example) and check that it contains a <code class="language-plaintext highlighter-rouge">ComicInfo.xml</code> file. Here’s an example of such a file:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cp">&lt;?xml version="1.0"?&gt;</span>
<span class="nt">&lt;ComicInfo</span> <span class="na">xmlns:xsi=</span><span class="s">"http://www.w3.org/2001/XMLSchema-instance"</span> <span class="na">xmlns:xsd=</span><span class="s">"http://www.w3.org/2001/XMLSchema"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;Title&gt;</span>Scott Pilgrim's Precious Little Life<span class="nt">&lt;/Title&gt;</span>
  <span class="nt">&lt;Series&gt;</span>Scott Pilgrim<span class="nt">&lt;/Series&gt;</span>
  <span class="nt">&lt;Number&gt;</span>1.0<span class="nt">&lt;/Number&gt;</span>
  <span class="nt">&lt;Year&gt;</span>2004<span class="nt">&lt;/Year&gt;</span>
  <span class="nt">&lt;Month&gt;</span>8<span class="nt">&lt;/Month&gt;</span>
  <span class="nt">&lt;Day&gt;</span>15<span class="nt">&lt;/Day&gt;</span>
  <span class="nt">&lt;Writer&gt;</span>Bryan Lee O'Malley<span class="nt">&lt;/Writer&gt;</span>
  <span class="nt">&lt;Publisher&gt;</span>Oni Press<span class="nt">&lt;/Publisher&gt;</span>
<span class="nt">&lt;/ComicInfo&gt;</span>
</code></pre></div></div>

<p>This file spec originated from the ComicRack application, which is not developed anymore. For the longest time there was no standards body responsible for maintaining this spec, but a coalition of players in the comic book space have joined forces to do <a href="https://github.com/anansi-project/comicinfo">just that</a>.</p>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Ebooks" /><summary type="html"><![CDATA[Comic books and mangas are usually stored as comic book archives, a type of file for the purpose of sequential viewing of images. This archive file is not a distinct file format but merely a filename extension naming convention. The filename extension indicates the archive type used:]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/bookcase.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/bookcase.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Narrowing TypeScript Unions without the `in` operator</title><link href="https://guilhermesimoes.github.io/blog/narrowing-typescript-unions-without-the-in-operator" rel="alternate" type="text/html" title="Narrowing TypeScript Unions without the `in` operator" /><published>2025-10-18T22:17:15+00:00</published><updated>2025-10-18T22:17:15+00:00</updated><id>https://guilhermesimoes.github.io/blog/narrowing-typescript-unions-without-the-in-operator</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/narrowing-typescript-unions-without-the-in-operator"><![CDATA[<p>When using a <a href="/blog/simplifying-typescript-code-with-union-types">Union Type</a> such as this:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">interface</span> <span class="nx">BaseAnimal</span> <span class="p">{</span>
  <span class="nl">weight</span><span class="p">:</span> <span class="kr">number</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">export</span> <span class="kr">interface</span> <span class="nx">Bird</span> <span class="kd">extends</span> <span class="nx">BaseAnimal</span> <span class="p">{</span>
  <span class="nl">fly</span><span class="p">:</span> <span class="nb">Function</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">export</span> <span class="kr">interface</span> <span class="nx">Fish</span> <span class="kd">extends</span> <span class="nx">BaseAnimal</span> <span class="p">{</span>
  <span class="nl">fins</span><span class="p">:</span> <span class="kr">number</span><span class="p">;</span>
  <span class="nl">swim</span><span class="p">:</span> <span class="nb">Function</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">export</span> <span class="kd">type</span> <span class="nx">Animal</span> <span class="o">=</span> <span class="nx">Bird</span> <span class="o">|</span> <span class="nx">Fish</span><span class="p">;</span>
</code></pre></div></div>

<p>TypeScript does not let us write code like this:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">animal</span><span class="p">:</span> <span class="nx">Animal</span><span class="p">;</span>

<span class="k">if </span><span class="p">(</span><span class="nx">animal</span><span class="p">.</span><span class="nx">swim</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// Error!</span>
  <span class="nx">animal</span><span class="p">.</span><span class="nf">swim</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>TypeScript errors out with <code class="language-plaintext highlighter-rouge">Property 'swim' does not exist on type 'Bird'</code>.</p>

<p>Instead, we are “forced” to use the <code class="language-plaintext highlighter-rouge">in</code> operator:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">animal</span><span class="p">:</span> <span class="nx">Animal</span><span class="p">;</span>

<span class="k">if </span><span class="p">(</span><span class="dl">'</span><span class="s1">swim</span><span class="dl">'</span> <span class="k">in</span> <span class="nx">animal</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// TypeScript is ok with this</span>
  <span class="nx">animal</span><span class="p">.</span><span class="nf">swim</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>But if we really want to avoid the <code class="language-plaintext highlighter-rouge">in</code> operator, for whatever reason, there is a type “trick” we can use:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">export</span> <span class="kr">interface</span> <span class="nx">Bird</span> <span class="kd">extends</span> <span class="nx">BaseAnimal</span> <span class="p">{</span>
  <span class="nl">fly</span><span class="p">:</span> <span class="nb">Function</span><span class="p">;</span>
  <span class="nl">swim</span><span class="p">?:</span> <span class="kc">undefined</span><span class="p">;</span> <span class="c1">// hack</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We can type that same property as <code class="language-plaintext highlighter-rouge">undefined</code>, and now TypeScript no longer complains:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">let</span> <span class="nx">animal</span><span class="p">:</span> <span class="nx">Animal</span><span class="p">;</span>

<span class="k">if </span><span class="p">(</span><span class="nx">animal</span><span class="p">.</span><span class="nx">swim</span><span class="p">)</span> <span class="p">{</span> <span class="c1">// All good!</span>
  <span class="nx">animal</span><span class="p">.</span><span class="nf">swim</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p><a href="https://www.typescriptlang.org/play/?#code/JYOwLgpgTgZghgYwgAgEJwM4QIIa2ZAbwFgAoZC5AdwmAHMALMALmRAFcBbAI2gG4yAXzJkIADwAOAeygFQkWIhSpgUACbJxkEGoxpMOPBAIlylGABsAnqwBi7EAjDApIAWYoYqwTgH5WDmoQMKAQGgD04cgMiADWQiKk4tKyyPLQ8EjItsAYDJpi2rr6WLj4RGSUyCEgGKwcPPyVlF4+dg5OLm4JpKKSMgRgVhIo2CA+cBbIALxoqhoAPtm5DO5kQQgWcFAoFsbIcKxjExZrpMAwyAAUcAB0rZwAlBUeB-fenFfPkcgAKsMQADKCCgwAkBAQMh2TmsaRAMGgejg404kzSSOWeSEQA">See for yourself</a>.</p>

<p>It’s a bit of a hack, and I wouldn’t recommend this for general use, but it can be helpful when used judiciously.</p>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="TypeScript" /><summary type="html"><![CDATA[When using a Union Type such as this:]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/half-bird-half-fish.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/half-bird-half-fish.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Minifying private properties and methods with Terser</title><link href="https://guilhermesimoes.github.io/blog/minifying-private-properties-and-methods-with-terser" rel="alternate" type="text/html" title="Minifying private properties and methods with Terser" /><published>2025-06-23T19:29:12+00:00</published><updated>2025-06-23T19:29:12+00:00</updated><id>https://guilhermesimoes.github.io/blog/minifying-private-properties-and-methods-with-terser</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/minifying-private-properties-and-methods-with-terser"><![CDATA[<p><a href="/blog/service-class-vs-service-module">As we saw last time</a>, minifiers / compressors such as <a href="https://try.terser.org/">Terser</a> do not minify class properties and methods by default. If a class has lots of properties and methods, their names can make quite the difference in the total size of an application. In the following example:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">export</span> <span class="kd">class</span> <span class="nc">Chirpy</span> <span class="p">{</span>
  <span class="nf">constructor</span><span class="p">(</span><span class="nx">options</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">_options</span> <span class="o">=</span> <span class="nx">options</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="nf">chirp</span><span class="p">(</span><span class="nx">message</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">_options</span><span class="p">.</span><span class="nx">endpoint</span><span class="p">}</span><span class="s2">/chirp`</span><span class="p">,</span> <span class="p">{</span>
      <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
      <span class="na">body</span><span class="p">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nf">stringify</span><span class="p">(</span><span class="nx">message</span><span class="p">),</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nf">then</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">_parseJson</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="nf">_parseJson</span><span class="p">(</span><span class="nx">response</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">response</span><span class="p">.</span><span class="nf">json</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Neither <code class="language-plaintext highlighter-rouge">chirp</code> nor <code class="language-plaintext highlighter-rouge">_parseJson</code> nor <code class="language-plaintext highlighter-rouge">_options</code> are minified. We don’t want to minify <code class="language-plaintext highlighter-rouge">chirp</code> because it’s part of our public API. But we do want to minify the parts that we consider private. <a href="https://www.typescriptlang.org/docs/handbook/2/classes.html#private">Using TypeScript</a> we can mark them as such:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">export</span> <span class="kd">class</span> <span class="nc">Chirpy</span> <span class="p">{</span>
  <span class="k">private</span> <span class="nx">options</span><span class="p">:</span> <span class="nx">ChirpyOptions</span><span class="p">;</span>

  <span class="nf">constructor</span><span class="p">(</span><span class="nx">options</span><span class="p">:</span> <span class="nx">ChirpyOptions</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">options</span> <span class="o">=</span> <span class="nx">options</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="k">public</span> <span class="nf">chirp</span><span class="p">(</span><span class="nx">message</span><span class="p">:</span> <span class="kr">string</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">options</span><span class="p">.</span><span class="nx">endpoint</span><span class="p">}</span><span class="s2">/chirp`</span><span class="p">,</span> <span class="p">{</span>
      <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
      <span class="na">body</span><span class="p">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nf">stringify</span><span class="p">(</span><span class="nx">message</span><span class="p">),</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nf">then</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">parseJson</span><span class="p">);</span>
  <span class="p">}</span>

  <span class="k">private</span> <span class="nf">parseJson</span><span class="p">(</span><span class="nx">response</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">response</span><span class="p">.</span><span class="nf">json</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Then, using a TypeScript transformer like <a href="https://github.com/timocov/ts-transformer-minify-privates">ts-transformer-minify-privates</a>, we can prefix them with <code class="language-plaintext highlighter-rouge">_private_</code>. <code class="language-plaintext highlighter-rouge">options</code> is thus renamed to <code class="language-plaintext highlighter-rouge">_private_options</code> and <code class="language-plaintext highlighter-rouge">parseJson</code> to <code class="language-plaintext highlighter-rouge">_private_parseJson</code>. Next, we can configure Terser to minify all properties (and methods) with that prefix:</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">mangle</span><span class="p">:</span> <span class="p">{</span>
  <span class="nl">properties</span><span class="p">:</span> <span class="p">{</span>
    <span class="na">regex</span><span class="p">:</span> <span class="sr">/^_private_/</span><span class="p">,</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This is the final result (whitespace added in order to improve readibility):</p>

<div class="language-js highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">export</span> <span class="kd">class</span> <span class="nc">Chirpy</span> <span class="p">{</span>
  <span class="nf">constructor</span><span class="p">(</span><span class="nx">r</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">t</span><span class="o">=</span><span class="nx">r</span>
  <span class="p">}</span>

  <span class="nf">chirp</span><span class="p">(</span><span class="nx">r</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nf">fetch</span><span class="p">(</span><span class="s2">`</span><span class="p">${</span><span class="k">this</span><span class="p">.</span><span class="nx">t</span><span class="p">.</span><span class="nx">endpoint</span><span class="p">}</span><span class="s2">/chirp`</span><span class="p">,</span> <span class="p">{</span>
      <span class="na">method</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
      <span class="na">body</span><span class="p">:</span> <span class="nx">JSON</span><span class="p">.</span><span class="nf">stringify</span><span class="p">(</span><span class="nx">r</span><span class="p">)</span>
    <span class="p">})</span>
    <span class="p">.</span><span class="nf">then</span><span class="p">(</span><span class="k">this</span><span class="p">.</span><span class="nx">h</span><span class="p">)</span>
  <span class="p">}</span>

  <span class="nf">h</span><span class="p">(</span><span class="nx">r</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">r</span><span class="p">.</span><span class="nf">json</span><span class="p">()</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Easy!</p>

<hr />

<p>Or is it? Turns out, this kind of minification is dangerous, which is why it is not enabled by default. <a href="https://terser.org/docs/cli-usage/#cli-mangling-property-names---mangle-props">Terser’s documentation</a> even shouts at us:</p>

<blockquote>
  <p>THIS WILL BREAK YOUR CODE. A good rule of thumb is not to use this unless you know exactly what you’re doing. You should:</p>
  <ol>
    <li>Control all the code you’re mangling</li>
    <li>Avoid using a module bundler, as they usually will call Terser on each file individually, making it impossible to pass mangled objects between modules.</li>
    <li>Avoid calling functions like defineProperty or hasOwnProperty, because they refer to object properties using strings and will break your code if you don’t know what you are doing.</li>
  </ol>
</blockquote>

<p>For example, when a class extends another:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">A</span> <span class="p">{</span>
  <span class="k">private</span> <span class="nx">prop1</span><span class="p">:</span> <span class="kr">number</span><span class="p">;</span>

  <span class="nf">constructor</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">prop1</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="kd">class</span> <span class="nc">B</span> <span class="kd">extends</span> <span class="nc">A</span> <span class="p">{</span>
  <span class="k">private</span> <span class="nx">prop2</span><span class="p">:</span> <span class="kr">number</span><span class="p">;</span>

  <span class="nf">constructor</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">super</span><span class="p">();</span>
    <span class="k">this</span><span class="p">.</span><span class="nx">prop2</span> <span class="o">=</span> <span class="mi">2</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Terser could minify both <code class="language-plaintext highlighter-rouge">prop1</code> and <code class="language-plaintext highlighter-rouge">prop2</code> to a single letter property like <code class="language-plaintext highlighter-rouge">a</code>. So at runtime <code class="language-plaintext highlighter-rouge">prop2</code> would override the value of <code class="language-plaintext highlighter-rouge">prop1</code>.</p>

<p>Our class <code class="language-plaintext highlighter-rouge">A</code> could also already have a single letter property like <code class="language-plaintext highlighter-rouge">a</code> and the minification of <code class="language-plaintext highlighter-rouge">prop2</code> to <code class="language-plaintext highlighter-rouge">a</code> would also override it.</p>

<p>So, how can we minify things responsibly? Well, in addition to Terser’s recommendations, I would suggest:</p>

<ol>
  <li>
    <p>Use Terser’s <a href="https://terser.org/docs/api-reference/#minify-options"><code class="language-plaintext highlighter-rouge">nameCache</code></a> to cache mangled variable names and property names across multiple invocations of Terser’s <code class="language-plaintext highlighter-rouge">minify</code>.<sup id="fnref:1"><a href="#fn:1" class="footnote" rel="footnote" role="doc-noteref">1</a></sup><sup id="fnref:2"><a href="#fn:2" class="footnote" rel="footnote" role="doc-noteref">2</a></sup></p>
  </li>
  <li>
    <p>Add a linter rule to prevent your source code from including very small variable names and property names. This way Terser’s minified names won’t clash with the source code’s names.<sup id="fnref:3"><a href="#fn:3" class="footnote" rel="footnote" role="doc-noteref">3</a></sup></p>
  </li>
  <li>
    <p>Avoid minification of classes that are extended or extend other classes.</p>
  </li>
</ol>

<hr />

<p>In the end, we can see that this type of minification has a lot of restrictions and is not easy to do. So while minifying private properties and methods <em>is</em> possible, a lot can definitely go wrong. The best way to avoid all this work is to <a href="/blog/classes-considered-harmful-when-authoring-a-js-lib">avoid using classes</a>!</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1">
      <p>Just setting <code class="language-plaintext highlighter-rouge">nameCache</code> to any empty object in Terser’s config should be enough. Like so: <code class="language-plaintext highlighter-rouge">{ nameCache: {} }</code>. To persist renames across multiple builds use a file. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
    <li id="fn:2">
      <p>Bundlers (like Webpack) and its plugins try to speed things up by running things in parallel. When using <code class="language-plaintext highlighter-rouge">terser-webpack-plugin</code>, for example, <a href="https://github.com/webpack-contrib/terser-webpack-plugin/issues/256#issuecomment-1230282316">parallelisation should be turned off</a> if we want mangling to be as safe as possible since currently threads / workers don’t share Terser’s cache. <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
    <li id="fn:3">
      <p>Here’s a quick custom ESLint rule:</p>
      <div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">meta</span> <span class="o">=</span> <span class="p">{</span>
  <span class="na">docs</span><span class="p">:</span> <span class="p">{</span> <span class="na">description</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Disallow property names that may overlap with mangled names.</span><span class="dl">'</span> <span class="p">},</span>
  <span class="na">messages</span><span class="p">:</span> <span class="p">{</span> <span class="na">smallProp</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Property is too small, it may clash with terser mangler.</span><span class="dl">'</span> <span class="p">},</span>
  <span class="na">schema</span><span class="p">:</span> <span class="p">[],</span>
  <span class="na">type</span><span class="p">:</span> <span class="dl">'</span><span class="s1">problem</span><span class="dl">'</span><span class="p">,</span>
<span class="p">};</span>

<span class="kd">function</span> <span class="nf">create</span><span class="p">(</span><span class="nx">context</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">function</span> <span class="nf">validateName</span><span class="p">(</span><span class="nx">node</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">if </span><span class="p">(</span><span class="nx">node</span><span class="p">.</span><span class="nx">key</span><span class="p">.</span><span class="nx">name</span><span class="p">.</span><span class="nx">length</span> <span class="o">&lt;</span> <span class="mi">3</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">context</span><span class="p">.</span><span class="nf">report</span><span class="p">({</span> <span class="na">messageId</span><span class="p">:</span> <span class="dl">'</span><span class="s1">smallProp</span><span class="dl">'</span><span class="p">,</span> <span class="nx">node</span> <span class="p">});</span>
    <span class="p">}</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="p">{</span>
    <span class="dl">'</span><span class="s1">ClassBody PropertyDefinition</span><span class="dl">'</span><span class="p">:</span> <span class="nx">validateName</span><span class="p">,</span>
    <span class="dl">"</span><span class="s2">MethodDefinition[kind='get']</span><span class="dl">"</span><span class="p">:</span> <span class="nx">validateName</span><span class="p">,</span>
    <span class="dl">"</span><span class="s2">MethodDefinition[kind='set']</span><span class="dl">"</span><span class="p">:</span> <span class="nx">validateName</span><span class="p">,</span>
  <span class="p">};</span>
<span class="p">}</span>

<span class="kr">module</span><span class="p">.</span><span class="nx">exports</span> <span class="o">=</span> <span class="p">{</span> <span class="nx">create</span><span class="p">,</span> <span class="nx">meta</span> <span class="p">};</span>
</code></pre></div>      </div>
      <p><a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Perf" /><category term="TypeScript" /><summary type="html"><![CDATA[As we saw last time, minifiers / compressors such as Terser do not minify class properties and methods by default. If a class has lots of properties and methods, their names can make quite the difference in the total size of an application. In the following example:]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/giraffes.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/giraffes.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Making setTimeout return number instead of NodeJS.Timeout in TypeScript</title><link href="https://guilhermesimoes.github.io/blog/making-settimeout-return-number-in-typescript" rel="alternate" type="text/html" title="Making setTimeout return number instead of NodeJS.Timeout in TypeScript" /><published>2024-10-16T02:30:46+00:00</published><updated>2024-10-16T02:30:46+00:00</updated><id>https://guilhermesimoes.github.io/blog/making-settimeout-return-number-in-typescript</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/making-settimeout-return-number-in-typescript"><![CDATA[<p>For the longest time we had to deal with the fact that NodeJS types were being included in a web project at work. The most visible aspect of this issue was that the return type of <code class="language-plaintext highlighter-rouge">setTimeout</code> was a <code class="language-plaintext highlighter-rouge">NodeJS.Timeout</code> when it should be a <code class="language-plaintext highlighter-rouge">number</code>. In order to fix this we used to place the following at the top of each file that used <code class="language-plaintext highlighter-rouge">setTimeout</code>:<sup id="fnref:1"><a href="#fn:1" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kr">declare</span> <span class="kd">let</span> <span class="nx">setTimeout</span><span class="p">:</span> <span class="nx">WindowOrWorkerGlobalScope</span><span class="p">[</span><span class="dl">'</span><span class="s1">setTimeout</span><span class="dl">'</span><span class="p">];</span>
</code></pre></div></div>

<p>We thought these NodeJS types were part of TypeScript just like the DOM types are part of it so we simply worked around them.</p>

<p>One day, while perusing <a href="https://www.typescriptlang.org/tsconfig">TypeScript’s compiler options</a>,
 we discovered <a href="https://www.typescriptlang.org/tsconfig#explainFiles"><code class="language-plaintext highlighter-rouge">explainFiles</code></a> which explains in detail how each typing gets included in a project. Using it in our project yielded this:</p>

<div class="language-terminal wrap-code highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="gp">$</span><span class="w"> </span>tsc <span class="nt">--explainFiles</span>
<span class="go">node_modules/@types/node/index.d.ts
Type library referenced via 'node' from file 'node_modules/@types/graceful-fs/index.d.ts' with packageId '@types/node/index.d.ts@20.5.7'

node_modules/@types/node/index.d.ts
Type library referenced via 'node' from file 'node_modules/@types/cacheable-request/index.d.ts' with packageId '@types/node/index.d.ts@18.11.17'
</span></code></pre></div></div>

<p>So, there were at least two type dependencies that were causing the dependency <code class="language-plaintext highlighter-rouge">@types/node</code> to be included in the project. But why were the types of <code class="language-plaintext highlighter-rouge">graceful-fs</code> and <code class="language-plaintext highlighter-rouge">cacheable-request</code> being included in the first place?</p>

<p>Diving again into <a href="https://www.typescriptlang.org/tsconfig">TypeScript’s compiler options</a> gave us the answer, in the form of another compiler option – <a href="https://www.typescriptlang.org/tsconfig#types"><code class="language-plaintext highlighter-rouge">types</code></a>:</p>

<blockquote>
  <p>By default all visible <code class="language-plaintext highlighter-rouge">@types</code> packages are included in your compilation. Packages in <code class="language-plaintext highlighter-rouge">node_modules/@types</code> of any enclosing folder are considered visible.</p>

  <p>If <code class="language-plaintext highlighter-rouge">types</code> is specified, only packages listed will be included in the global scope.</p>
</blockquote>

<p>Our project was unnecessarily including the types of dozens of development dependencies! Setting the compiler option <a href="https://www.typescriptlang.org/tsconfig#types"><code class="language-plaintext highlighter-rouge">types</code></a> to an empty array prevented all <code class="language-plaintext highlighter-rouge">node_modules/@types</code> from being automatically included. And just like that, the return type of <code class="language-plaintext highlighter-rouge">setTimeout</code> now finally appeared as <code class="language-plaintext highlighter-rouge">number</code>.</p>

<hr />

<p>We should observe that while using <code class="language-plaintext highlighter-rouge">types</code> is the solution to avoid NodeJS types in a web project, this compiler option can cause the project’s tests to fail if they do depend on NodeJS types. In that case, we need a way to include those test-specific types only when running the tests.</p>

<p>In our project, we had to do the following changes:</p>

<ol>
  <li>Create a <code class="language-plaintext highlighter-rouge">tsconfig.test.json</code> file that extends the main <code class="language-plaintext highlighter-rouge">tsconfig.json</code> file.</li>
  <li><a href="https://kulshekhar.github.io/ts-jest/docs/getting-started/options/tsconfig/#path-to-a-tsconfig-file">Configure <code class="language-plaintext highlighter-rouge">jest</code> to use this new file</a>.</li>
  <li>Add <code class="language-plaintext highlighter-rouge">types: ["jest"]</code> to include the type definitions of <code class="language-plaintext highlighter-rouge">@types/jest</code> (like <code class="language-plaintext highlighter-rouge">describe</code>, <code class="language-plaintext highlighter-rouge">it</code>, <code class="language-plaintext highlighter-rouge">beforeEach</code>, etc).</li>
  <li>Avoid adding <code class="language-plaintext highlighter-rouge">"node"</code> to the <code class="language-plaintext highlighter-rouge">types</code> array. While it would be somewhat accurate to do this, the issue is that by doing that we’d “pollute” the global typing environment during tests. All the <code class="language-plaintext highlighter-rouge">setTimeout</code>s would have a return type of <code class="language-plaintext highlighter-rouge">number</code> during our <code class="language-plaintext highlighter-rouge">build</code> command, but would have a return type of <code class="language-plaintext highlighter-rouge">NodeJS.Timeout</code> during our <code class="language-plaintext highlighter-rouge">test</code> command. So our <code class="language-plaintext highlighter-rouge">build</code> command would work but our <code class="language-plaintext highlighter-rouge">test</code> command would fail.</li>
  <li>Rename <code class="language-plaintext highlighter-rouge">global</code> to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis"><code class="language-plaintext highlighter-rouge">globalThis</code></a> in our tests since <code class="language-plaintext highlighter-rouge">global</code> is a NodeJS concept.</li>
  <li>
    <p>Use <a href="https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html">Triple-Slash Directives</a> in tests where <code class="language-plaintext highlighter-rouge">node</code> types are really necessary (for example, when using <code class="language-plaintext highlighter-rouge">fs</code> or <code class="language-plaintext highlighter-rouge">path</code>):</p>

    <div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">/// &lt;reference types="node" /&gt;</span>
</code></pre></div>    </div>
  </li>
</ol>

<hr />

<p>While our project is a web project, we were still using <em>some</em> NodeJS concepts to build the project, mostly in this form:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if </span><span class="p">(</span><span class="nx">process</span><span class="p">.</span><span class="nx">env</span><span class="p">.</span><span class="nx">NODE_ENV</span> <span class="o">!==</span> <span class="dl">'</span><span class="s1">production</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">console</span><span class="p">.</span><span class="nf">error</span><span class="p">(</span><span class="dl">'</span><span class="s1">Log something only necessary in development</span><span class="dl">'</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This code no longer compiled without the NodeJS <code class="language-plaintext highlighter-rouge">process</code> type. Adding a new <a href="https://www.typescriptlang.org/docs/handbook/2/type-declarations.html">declaration file</a> with our own type solved this:</p>

<div class="language-ts highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// globals.d.ts</span>
<span class="kr">declare</span> <span class="kd">let</span> <span class="nx">process</span><span class="p">:</span> <span class="p">{</span>
  <span class="nl">env</span><span class="p">:</span> <span class="p">{</span>
    <span class="na">NODE_ENV</span><span class="p">:</span> <span class="kr">string</span><span class="p">;</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This actually took a little more work than the simple workarounds we were using before but it was worth it. A notable outcome of these changes was that our <code class="language-plaintext highlighter-rouge">build</code> and <code class="language-plaintext highlighter-rouge">test</code> command times improved by about 1 second. It’s possible that VSCode’s auto-completion and auto-import features also improved. And honestly, we’d rather our project only include the exact types that we want instead of grabbing everything from <code class="language-plaintext highlighter-rouge">node_modules/@types</code>.</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1">
      <p>Another option was to surrender to <code class="language-plaintext highlighter-rouge">NodeJS.Timeout</code> and use <code class="language-plaintext highlighter-rouge">ReturnType&lt;typeof setTimeout&gt;</code> instead of <code class="language-plaintext highlighter-rouge">number</code> everywhere. <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;&#65038;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="TypeScript" /><summary type="html"><![CDATA[For the longest time we had to deal with the fact that NodeJS types were being included in a web project at work. The most visible aspect of this issue was that the return type of setTimeout was a NodeJS.Timeout when it should be a number. In order to fix this we used to place the following at the top of each file that used setTimeout:1 Another option was to surrender to NodeJS.Timeout and use ReturnType&lt;typeof setTimeout&gt; instead of number everywhere. &#8617;&#65038;]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/gemsbok.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/gemsbok.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Animating a pirate treasure map path</title><link href="https://guilhermesimoes.github.io/blog/animating-a-pirate-treasure-map-path" rel="alternate" type="text/html" title="Animating a pirate treasure map path" /><published>2023-09-10T15:36:40+00:00</published><updated>2023-09-10T15:36:40+00:00</updated><id>https://guilhermesimoes.github.io/blog/animating-a-pirate-treasure-map-path</id><content type="html" xml:base="https://guilhermesimoes.github.io/blog/animating-a-pirate-treasure-map-path"><![CDATA[<p>Animating an SVG line is nothing to write home about. It has already been described in great detail <a href="https://jakearchibald.com/2013/animated-line-drawing-svg/">many</a>, <a href="https://css-tricks.com/svg-line-animation-works/">multiple</a>, <a href="https://web.archive.org/web/20140226020330/http://product.voxmedia.com/2013/11/25/5426880/polygon-feature-design-svg-animations-for-fun-and-profit">different</a> <a href="https://tympanus.net/codrops/2013/12/30/svg-drawing-animation/">times</a>. We make the line use dashes, configure it so that there is a single dash that spans the entire line, and then we animate the offset of that dash. Done.</p>

<p>But what if we want to animate a line that itself is dashed? Like a dashed line in a treasure map?</p>

<p>As it turns out, we can animate it in pretty much the same way! But instead of animating the dashed line, we mask that dashed line with an identical line, and then we animate <em>that</em> line. So, step by step:</p>

<ol>
  <li>
    <p>Define the line <code class="language-plaintext highlighter-rouge">path</code> inside a <code class="language-plaintext highlighter-rouge">defs</code> element so that it’s not drawn.</p>
  </li>
  <li>
    <p>Draw the line by defining a <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Element/use"><code class="language-plaintext highlighter-rouge">use</code></a> element whose <code class="language-plaintext highlighter-rouge">xlink:href</code> attribute points to the <code class="language-plaintext highlighter-rouge">path</code> defined in the previous step.</p>
  </li>
  <li>
    <p>Create a mask with an identical line by using another <code class="language-plaintext highlighter-rouge">use</code> element. The mask must be white (<a href="https://lab.iamvdo.me/css-svg-masks/#masking">like in Photoshop</a>) and have the same <code class="language-plaintext highlighter-rouge">stroke</code> properties (<a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-width"><code class="language-plaintext highlighter-rouge">stroke-width</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-linecap"><code class="language-plaintext highlighter-rouge">stroke-linecap</code></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit"><code class="language-plaintext highlighter-rouge">stroke-miterlimit</code></a>, etc) as the drawn line so that it can cover it perfectly.</p>
  </li>
  <li>
    <p>Make the mask line use dashes, make it dashed with a single dash that spans its total length, and then animate the dash offset. The usual stuff.</p>
  </li>
</ol>

<p>Finally, we can change the transition timing function to achieve different results. Using the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/transition-timing-function#values">steps transition function</a> with the same amount of steps as the number of line dashes results in a nice effect.</p>]]></content><author><name>Guilherme Simões</name><email>guilherme.rdems@gmail.com</email><uri>https://guilhermesimoes.github.io</uri></author><category term="Animation" /><category term="SVG" /><category term="Interactive" /><summary type="html"><![CDATA[Animating an SVG line is nothing to write home about. It has already been described in great detail many, multiple, different times. We make the line use dashes, configure it so that there is a single dash that spans the entire line, and then we animate the offset of that dash. Done.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://guilhermesimoes.github.io/assets/images/treasure-map.png" /><media:content medium="image" url="https://guilhermesimoes.github.io/assets/images/treasure-map.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>