Skip to content

defensive fetch response

In 2023, while deep in the trenches of my engineering manager role, I decided to purchase a license to access react.gg, “The interactive way to master modern React”. I followed ui.dev team’s work for the last few years, and they often released material that’s been quite helpful to learn React and modern Javascript. This course is just another perspective for brushing up on what I know and pushing myself to learn more.

In the course, I came across a comment reply made showing a good way to use fetch(). The following was initially asked:

I am flummoxed by the assertion that this code is not wise:

function getGithubProfile(username) {
  return fetch(
    `https://api.github.com/users/${username}`
  ).then((res) => res.json());
}

What is the correct way to obtain data from an external source? In other languages, I’ve been using functions for decades to retrieve data from external sources.

His response included a defensive approach to fetching data:

async function getGithubProfile(username) {
  let response;
  try {
    response = await fetch(`https://api.github.com/users/${username}`);
  } catch (error) {
    throw new Error(`Network error: ${error.message}`);
  }
  
  if (!response.ok) {
    const message = `HTTP error! status: ${response.status}`;
    throw new Error(message);
  }
  
  let data;
  try {
    data = await response.json();
  } catch (error) {
    throw new Error(`API response error: ${error.message}`);
  }
  
  if (!data || typeof data !== 'object') {
    throw new Error('Invalid response format from the API');
  }
  
  return data;
}

While I’ve used and seen plenty of snippets from this function in various places, this was the first time I saw it constructed like this. Using fetch like this is one of a few ways that this function could be written, but it’s also very readable and easy to understand.

Here are the four things this structure is doing:

  1. Using asynchronous code to fetch data and return a Promise using async/await
  2. Using try...catch statement to allow the fetch and catch responses or error
  3. Throw errors for Network issues, response status issues, API issues, or response formatting issues
  4. Safely returns the data fetched from the URL or API

Now, let me attempt to destructure this defensive code block.

try…catch

First, we need to fetch some data, so we’ll access an external URL, this example from Github.

async function getGithubProfile(username) {
  let response;
  try {
    response = await fetch(`https://api.github.com/users/${username}`);
  } catch (error) {
    throw new Error(`Network error: ${error.message}`);
  }

  /* more code below */
}

First, we declare a variable called response that’ll be referenced and reassigned throughout the function. This might seem kind of redundant considering it’s called almost immediately inside of the try block. Interestingly enough, we have to declare response outside of the try block because of block scoping, which applies to using const and let. If we declared var response inside of try {}, because of hoisting, it would actually work in the function. Theo (t3.gg) made a video going more in depth about the constraints of the try block.

The first call of response is in the above referenced try...catch syntax construct containing the code to fetch the data or return a network error. Using both async to convert the function to be asynchronous Promise as well as the await expression to suspend execution until the returned promise is fulfilled or rejected is one of the best modern features of Javascript. If the response does not work properly, an error will display to let the user know there’s an issue.

validate the data

Before we even work continue to work with a response containing data, let’s make sure the fetch request was okay by returning a HTTP status code of 200, representing a successful response.

async function getGithubProfile(username) {
  /* fetch the data */

  if (!response.ok) {
    const message = `HTTP error! status: ${response.status}`;
    throw new Error(message);
  }

  /* more code below */
}

If the response was anything but okay, this conditional will throw an error with the status code.

json the data

Time to convert the response to a readable format for Javascript

async function getGithubProfile(username) {
  /* fetch the data */

  /* response validation */

  let data;
  try {
    data = await response.json();
  } catch (error) {
    throw new Error(`API response error: ${error.message}`);
  }

  /* more code below */
}

After setting a new variable for the data, we resolve the response to a JavaScript object. This object could be anything that can be represented by JSON — an object, an array, a string, a number, etc. Now the fetched data is ready to be used by javascript.

On the other hand, if there’s an error with the returned data for any reason, such as malformed JSON, it’ll once again throw a new error.

Note: It’s also here that you might need a different resolve type. For example, there are cases where you’re working with a string response that isn’t or doesn’t need to be JSON formatted data. In that case, your response could be returned using await response.text() to return a string. There are several other method types that can be applied here as well.

type validation

What happens if we get through everything but the data itself doesn’t actually resolve to a valid object or the data is just plain corrupt? This is an often forgotten step in fetching data where we should do one last check to make sure we’re actually returning a valid data type, object in our case, or just making sure the data is still available. If not, throw an API error.

async function getGithubProfile(username) {
  /* fetch the data */

  /* response validation */

  /* resolve data type */

  if (!data || typeof data !== 'object') {
    throw new Error('Invalid response format from the API');
  }

  /* more code below */
}

return the data

At this point, the data has survived multiple check stops to make sure the result of the data is exactly what we need. So, all we have to do is return the data.

return data;

Voila! Now we have a fully functioning and very safe function to fetch data for our site or application.

For React, this type of function can either stand alone outside of a component to be invoked in the Component, or it can also exist directly in React.useEffect() to grab the data when the component mounts or updates based on a state change.

fetch promise

By default, fetch() is really a promise, allowing you to cover a lot of these checks that are located inside of the multiple try...catch blocks. Here’s an alternative syntax, often referred to as then/catch for fetching:

fetch('https://api.github.com/users/${username}')
  .then((response) => {
    if (response.ok) {
      return response.json();
    } else {
      throw 'Error getting users list'
    }
  }).then((data) => {
    /* handle data */          
  }).catch((error) => {
    /* handle errors */
  });

Both methods are Promise chains, both handle responses and errors in similar ways. There’s nothing wrong with using the above, it’s perfectly valid! Why use try...catch over then/catch built-in promise syntax?

The primary difference is the addition of the async/await in ES2017. Ultimately, using this syntax offers a cleaner to read, easier to understand method to retrieve the data. There’s no nesting of then/catch methods, which can be common in then/catch blocks.

Here’s a great Smashing Magazine article going over examples between try...catch over then/catch.

Happy fetching!

Updates

  • August 14, 2024 – Added additional context around the try block and a video link to YouTube

all in on popover modals

Let’s talk about the new popover feature added to HTML. I decided to create a few versions of a modal that contains a search form, just to both get experience as well as prove that this is a good new use of a popover. I am biased but I’m completely on board!

Because responsive websites have so many features that need to work from small to large devices, sometimes we have to make decisions that universally provide necessary features but don’t add too much complexity for users. One of those is a search field that can fit on all devices, and it’s this feature that led me in the direction of a modal.

Yeah, I know, modals are overused. They distract from the main content, take focus away from the important parts of site. However, adding a search form to a modal provides a much used feature with minimal impact on mobile layout structure, allowing for more components in a small area.

Screenshot of mobile header for stopthethyroidmadness.com
This is an example of a search component on a mobile sized device with a minimal footprint

To activate the search form, the magnifying glass icon is a button and requires to be pressed or tapped. A search form appears inside of a modal that overlays the screen, blurring the background.

Screenshot of mobile search modal that's open on stopthethyroidmadness.com
The search form appears in a modal on top of the content

Since spring of 2024, we have a new feature of HTML, using an attribute, called popover. This new addition to the language provides some really great superpowers:

  • No javascript required!
  • Automatic overlay, highest z-index
  • Light dismiss (clicking/tapping outside of the popover element)
  • Default focus management
  • Keyboard binding for improved accessibility support
  • Support for ::backfill pseudo element (wanna blur the background without extra code!)

If I was talking to my 2000s web designer self, he would describe this as magic! Because, well, it really is so simple and easy.

Here’s a CodePen of my first version of this:

The best thing about the above component is that you can try it out on all the modern browsers with success… unless you’re using Safari on iOS. With the help of Luke Warlow, he found and reported a Webkit bug that the light dismiss behavior doesn’t work.

Because of the above bug, in order to have universal support, I created another version that includes a button inside of the popover that mostly duplicates the button trigger that opens the popover, but instead this one closes and dismisses the popover.

Just to fun, I took one more try at making a version that uses the dialog element, which has been available since 2022. The main reason I did not go this route was to attempt a new, accessible element with no javascript. Buttons that open dialogs have at least one inline onclick="dialog.showModal()" attribute that’s required for the dialog to appear. Adding light dismiss also requires a little script, as you can see in the CodePen example. Additionally, the dialogs don’t need any additional code for focus to just work right, which is very nice.

You have your choice in these examples so feel free to borrow or steal whatever you want!

come on, safari

I’m nearing the end of the first phase of a website redesign, teaching myself new CSS, and sprinkling in some JS. Of the things I’m learning, I’m also rediscovering some old Safari linear-gradient issues and seeing some new Safari positioning bugs.

You can follow along if you view the CodePen titled “color-scheme, light-dark, Safari bug”.

The original point of the above pen is to verify linear gradient issues with Safari.

Webkit-based linear-gradient issues are well documented, they behave differently because of the transparent color values. You can see this by switching the theme mode from light to dark, or dark to light. I keep running into linear gradient issues in Safari because I infrequently use them with transparent values and forget they’re still an issue.

CodePen screenshot after switching pen from light mode to dark mode, showing linear gradients that are not ideal
CodePen screenshot after switching the theme mode from light to dark, showing linear gradients that are not ideal. It also shows that the aspect ratio isn’t a square as it should be.

Try the above pen in Firefox or any Chromium browser and the linear gradients are consistently working when switching between dark and light mode.

I found 3 more issues having created this:

  1. In .square, Webkit doesn’t seem to center things consistently using just place-items: center. I am forced to add place-content: center to make the content “this is a square” center consistently with the other modern browsers
  2. aspect-radio: 1 / 1 doesn’t actually work right for the content area of .square. It’s elongated into a rectangle.
  3. Adding position: fixed to .square, which is already centered using the place-* rules breaks the positioning only on Webkit. I am forced to use older positioning methods, i.e. left, top, and transform.

sad twentytwentyfive

Quoted GitHub – WordPress/twentytwentyfive by WordPress (GitHub)

Twenty Twenty-Five is built as a block theme. The theme aims to ship with as little CSS as possible: our goal is for all theme styles to be configured through theme.json and editable through Global Styles.

This makes me sad.

In a different system, a configuration file like theme.json would be considered a design token where a design system will automatically generate a JSON file full of tokens to be used in a component library or website. The potential for design tokens are quite high, but sadly they’re less practical without tools that are configured to both generate the design token file or system and give easy access for developers to use them. Right now, it’s still piecemeal and there’s not a great workflow in many systems.

Modern WordPress development is abstracting a subset of CSS to a JSON file, for the ease of builders and publishers. The developers who build Block Themes are kind of being forced against the grain of the web in the development phase. Developers consumed by a Javascript-centric system, this might make a lot more sense. But, for those of us who want to build using the technology that browsers provide, this is very unappealing and backwards.

This is just another reason I can’t see how much longer WordPress will be serious going forward. Maybe the update to React 19 in Gutenberg will change things, considering that it makes Web Components a first class integration, also considering the possibility of using React Server Components. But, I haven’t seen anything that gives me an indication either of these are being really thought out.

This quote was from the TwentyTwentyFive Github Repo.

svg background images to inherit light-dark value

With the spirit of using new widely supported, Baseline CSS rules, I’m implementing light-dark() as a simplified method to allow light and dark mode on a website. This function is a game changer, very simple to apply color modes for websites, so I’m a big fan already. That said, using SVG images as background images exposes an edge case that took me down a rabbit hole leading me to CSS masks.

Let’s apply light-dark using color-scheme for the site.

:root {
  /* NOTE: Use @supports for <= Safari 17.4 (2024-05) */
  @supports (color: light-dark(black, white)) {
    color-scheme: light dark;
	  --surface-color: light-dark( #ccc, #333 );
	  --text-color: light-dark( #333, #ccc );
  }
}

I’m applying carets to navigation menu item links, which look like this:

navigation item link named "Resources" with down-pointing caret on the right of the link

So that chevron or caret on the right side of Resources, which is pointing down, is applied to the anchor element as a background image.

a {
  background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='currentColor' [...]");
}

Why am I adding an SVG as a background image here? Wouldn’t it be easier to add SVG to the source code? Well, yes, but this is WordPress, and since I’m pulling in the navigation menu from an API, the markup is auto-generated and formatted so it’s not easy to add in additional markup into the API results. I’m sure we’ve all faced similar limitations on generated code from an API, so I was determined to attack this problem and find a solution.

Additionally, I’m not referencing an additional file as a way to save an HTTP request, one of the many micro-optimizations for better performance. This also gives us the ability to easily cache the image, or if I decide to use an SVG sprite in the future, this saves multiple requests.

Back to the code above, see that fill='currentColor' rule? It doesn’t work as you would expect because, regardless of the SVG being added a background image, the SVG is being treated as an external resource. Considering this, we can’t apply the currentColor value to inherit the anchor’s color.

In the Stackoverflow I just linked to above, there’s a reference to Coloring SVGs in CSS Background Images, which provided me a big clue to solve this, which is using CSS masks. It worked… kinda!

I converted everything from background to be mask, because the syntax is mostly identical, and added a background color for the mask to work correctly. Well, that actually hid the text of the anchor element, so while I was now able to see the background caret with the correct color mode text color, the actual text was hidden. To this point, I’ve purposely been trying to not use ::after pseudo-elements out of principle, just to make things a little simpler. Time to break through the ego and add back that pseudo-element!

The final code that works for me:

a::after {
  background-color: var(--text-color);
  content: "";
  height: 100%;
  mask-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='currentColor' aria-hidden='true' viewBox='0 0 20 20'><path fill-rule='evenodd' d='M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z' clip-rule='evenodd'/></svg>");
  mask-position: left 17%;
  mask-repeat: no-repeat;
  mask-size: 0.9rem;
  position: absolute;
  width: 100%;
}

Problem solved!

search form + popover api

Wresting with whether or not I should move forward using the Popover API for a search form, almost solely to delete the javascript code for the same type of interaction.

I’m hung up on default focus *not* going to the search field. I discovered that it’s only a tap of the tab key away, which is very helpful, but that default focus would be the clincher for me.

This probably won’t improve accessibility either.

This is so tempting!

The following Codepen link is a demo of what I’m considering. It’s really, really cool to see this work so easily with two new attributes! Mindblowing.

codepen.io/asuh/pen/jOojyJB

updated the site again

Reached a stopping point to update asuh.com using the new Forage theme I put together.

github.com/asuh/forage/

It’s nice to remove so much from my previous iteration and simply things with some modern CSS.

Forage is such a great tool for classic theme developers and I should continue improving it where I can.

Next, I’m going to probably update another site with Forage that uses Gutenberg and see how that goes. I believe it’ll be a hybrid block theme this way.

laravel blade > php?

Filed an Issue

This is mostly reproduced from a Github issue I created for the new Forage WordPress theme I created. I’m thinking out loud whether or not to support a new branch with plain ‘ole PHP instead of the Blade syntax.


Laravel Blade has some notable features that help PHP developers move faster. Here are a few reasons to keep using it:

(quickly generated by ChatGPT, with edits and additions by me)

  • Layout Components: Blade offers the @component directive for defining reusable components, such as navigation menus, alerts, or forms. This promotes encapsulation and reusability for components containing HTML, CSS, and JS.
  • Escaping by Default: Blade automatically escapes output by default, helping to prevent XSS (Cross-Site Scripting) attacks. This enhances the security of your application by reducing the risk of injecting malicious code into your HTML. While PHP provides functions for escaping output, Blade handles this automatically, reducing the likelihood of accidental omissions.
  • Template Inheritance: allows you to define a base layout with placeholders that child views can fill in with their own content. This enables a more structured and modular approach to building views, reducing duplication and promoting code reusability.In other words, PHP would require explicit includes everywhere for PHP files to work with each other. Blade uses hooks like @yield as placeholders to work with various functions like @section.@yield('content") in the base file would render @section('content") in the child view file, such as page.blade.php`.
  • Control Directives: Blade provides convenient directives for common control structures, making it easier to express conditional logic and iterate over data.Example@if () as plain PHP would need PHP tags, looking like <?php if () ?>. Essentially, it’s more verbose to use plain PHP.
  • Concise Syntax: Blade offers a concise and readable syntax for common tasks such as echoing variables ({{ $variable }}), control structures (@if, @else, @endif, etc.), loops (@foreach, @for, @while), and more. This makes Blade templates easier to write, understand, and maintain compared to raw PHP embedded within HTML.
  • Template Comments: using {{-- This is a Blade comment --}}, which is not rendered in the final output.
  • Include Statements: In addition to @include, which mostly mirrors plain PHP, Blade also provides the @includeWhen and @includeFirst directives for conditional inclusion of templates.

I attempted to order the above in the order of importance, with the top few being quite more efficient than plain PHP.

My overall observation is that Blade should truly be considered if you can think of good use cases for adding components rendered by PHP. At some point, it might be less useful as Web Components find their way into the WordPress ecosystem.

Additionally, the auto-escape and inheritance for Blade is pretty great for efficiency. The benefits of these features are quite convenient.

The rest are just nice little sprinkles to clean up PHP. Nice, but not necessary.

If I review everything I’ve used with Blade, I really don’t think I have any real needs yet for PHP driven components. All the rest of the bullet points could easily have been regular PHP in my own personal work flow, but I’m really only using themes on smaller sites that don’t have a lot of complexity.

If Blade is removed from any project, you likely have the option to completely remove a dependency on Composer as well as some application methods to render the Blade syntax into PHP. I can also see this argument for those who prefer to stay as close to the original languages as possible.

At some point in the near future, decisions to support Laravel Blade might come down to whether or not you want a build step to compile a language. There’s a potential future approaching where the browser contains so much power that build steps can once again become optional. That’s a very interesting future!

forage, my last wordpress theme

forage

Introducing Forage, my new hybrid starter theme joining Roots Sage and FootMATE. This is a project of love, giving me an opportunity to learn new technologies and simplify the WordPress theme I was using. While this might not technically be the last theme I apply to my personal site, WordPress is moving into a new direction of lots of Javascript to drive a WordPress block theme.

Why Forage?

I think the mushroom kingdom that we live among is quite interesting, and the act of foraging mushrooms feels like what I do when I’m writing code: I’m always looking for something to consume and use.

Features

Forage is a starter theme. This means that when you install it, no styling or interactive behavior is added to the front-end. This gives you complete flexibility to create the theme you want with minimal opinionated code.

  • Laravel Blade as a templating engine
  • Vite for compiling assets, concatenating, and minifying files
  • Biome for linting and formatting both CSS and JS
  • Modern CSS & JavaScript – No preprocessors, libraries, or frameworks
  • DocHooks provide new functionality of class method DocBlock as hooks into WordPress API
  • IndieWeb out of the box

Laravel Blade

Sage was my real introduction to Laravel, back in the days when PHP just landed in the version 7 era, so I was mostly used to older PHP 5.2-5.4. While I tend toward wanting pure forms of HTML, CSS, and JS, I found Laravel Blade to be an interesting abstraction of PHP. In the last few years, PHP has come of age in so many great ways. PHP 7 and PHP 8, and all point releases, added superpowers for functional programming and types, among many other features. Modern PHP and TypeScript, less so even modern Javascript, have a lot in common today. In many ways, it’s impressive where PHP is today.

Laravel Blade is a modern approach to templating PHP. In a similar way that TypeScript is also Javascript, all blade files are PHP files as well which makes it convenient to get started. The main benefits of using a blade file is the cleaner looking syntax and custom components. Not  Here’s a great overview of all the strengths of Blade.

Vite

I first used Vite via Astro, and as a build tool, it felt so easy and simple. I’ve used many other build tools over the years, from grunt and gulp to webpack. I tried others here and there, but nothing stuck. Vite, however, makes a lot of sense for WordPress classic theme development.

The instance of Vite used for this theme is so lightly integrated that you wonder how it’s really doing all that magic so easily. The biggest difference? I don’t need to have two environments to see live reloads anymore. If I’m using https://example.local/ to work on WordPress locally on my computer, Vite will use the same environment for live reloading. No need to switch to a different URL like https://localhost:3000! Truly, I’ve been annoyed by this for more than a decade about Webpack! No more!

Biome

This project feels like a game changer for linting. We’ve seen several come and go, with the most popular ones being ESLint, Prettify, and Stylelint in 2024. However, Biome is positioning itself to be one tool to lint it all.

The background is interesting and having won a contest set up by the Prettier folks, Biome has a strong position going forward. I expect some breaking features as it continues to mature, but it’s also stable enough for a large majority of linting rules that I already don’t miss ESLint. As of June 2024, the CSS linting is in its first public beta release, so it’ll be some time before that’s mature enough to replace Stylelint, but I fully intend to migrate over when it’s stable.

Vite and Biome Node Packages

The most exciting thing about both Vite and Biome is reduced complexity. Just by replacing Webpack and ESLint with Vite and Biome, respectively, /node_modules/ was reduced by more than 50%. In fact, I think even more packages were removed from the project overall. This is a big win.

Once CSS linting is stable, this is what devDependencies looks like in package.json:

  "devDependencies": {
    "@biomejs/biome": "^1.8.0",
    "glob": "^10.4.1",
    "vite": "^5.2.12"
  }

That’s refreshing!

Modern CSS & JavaScript

I have purposely included no libraries, frameworks, or packages to abstract CSS or Javascript. This might be considered silly or naive, but if you review both CSS and JS in 2024, the languages are powerful enough that the need for additional state management or other helpers and shortcuts is far less than before. I expect sometime in 2025 that so much will be supported across all browsers that we’re going to see some significant paradigm shifts in the need to use large frameworks or libraries.

In fact, for my own site, I’ve removed Sass completely. Because nesting is widely supported in modern browsers, all I did was convert Sass variables to native CSS Custom Properties and everything just worked. Having reviewed the site in non-supporting browsers that don’t have modern CSS syntax features, progressive enhancement is the winner because all content and functionality is still available even if it doesn’t look as pretty.

Regardless, it’s quite easy to just yarn add svelte or any other library if you need it.

DocHooks

From the FootMATE creator, DocHooks are an interesting syntactic sugar for functions and methods to the WordPress APIs using DocBlocks.

    /**
     * Loads default theme supports
     * @action after_setup_theme
     */
    public function addThemeSupport()
    {
        /* add logic here */
    }

The part that says @action after_setup_theme is the same as writing add_action( 'after_setup_theme', 'addThemeSupport, 10, 3 );. It’s a big cleaner and easier to parse the functions this way.

Currently, DocHooks only support adding to the API. If you need to remove, you still have to write remove_action('after_setup_theme', 'addThemeSupport');

IndieWeb

I’ve added as much Microformats2 syntax to the markup as I could so that you add a few plugins and it’ll be indieweb compatible almost immediately after setting up the pieces. We should own as much of our own content as we can.

Background

The Roots Sage project provided an excellent philosophy and approaches for a progressively developed WordPress theme, but after version 9, Sage had too many interconnected pieces, new dependencies, and legacy to keep up with. Additionally, having focused on so many other  returning to an old version of Sage left much to be desired, as well as plenty of broken services or packages.

I found FootMATE in spring of 2024 looking for an alternative. Strangely, it follows enough of a paradigm similar to Sage that it feels like a younger cousin. Also, the author decided to integrate Vite instead of Webpack, and that’s a huge win for productivity and DX.

The combination of the two themes satisfies my desire for good file architecture and modern tooling without much bloat or dependencies. It just works.

WordPress’ direction towards full-site editing and Gutenberg leaves much to be desired for developers working on WordPress. This theme, while starting from a basis of the classic theme structure, has a lot of flexibility between the two worlds of classic and modern WordPress theme development.

The Future

I’m going to continue development on this theme indefinitely, as both FootMATE and Sage deliver new updates that make sense for this theme. Additionally, I already have a number of Github issues that I hope to resolve or bring into the theme.

Ultimately, I’ll probably slow down on development for this theme soon and maintain things as time goes on. Who knows, I might support this for several years to come. I don’t have all the experience or expertise for some of the integrations I am questioning or interested in, so community help will be desired where possible. That said, I’ll keep an open mind about how to continue on with this starter theme.

I’m eager to hear any feedback or comments on the direction this theme is going and how to make it better. It solves my personal needs here on asuh.com but it’ll be interesting to see what appeal it has outside of what I needed.

Thanks for your support and eyeballs on this post!

it just works

If you visit this website, it’s likely it won’t look or act any differently right now. Maybe you’ll see a new dark mode! I spent the last two weeks moving to a new WordPress theme, one which I’d call a younger cousin to the previous theme I used. It has less under the hood, uses slightly different syntax, but the ideals behind some of the tech are similar.

Here are some small updates I made in the transition:

  • I added a new CSS function called light-dark(), pretty much the result of Dave Rupert’s experiment. You know what this unlocked for me? I was able to remove almost all declarations of color and background-color from the code, outside of a few instances. I couldn’t believe how it simplifies light and dark mode code.
  • I was using CSS mixins to drive fluid sizing, borrowed from this Codepen. This was a Scss based mixin that gave the site fluid responsive superpowers, added around 2017. Since that time, utopia.fyi is now a much easier, more efficient way to provide fluidity. And, I don’t even have to use Scss for this.
  • All variables are now CSS custom properties, aka CSS variables. I love removing abstractions!
  • I have a new plugin called Lite Video Embed, which now won’t require YouTube to load everything until the visitor interacts with the video. Performance win!
  • I’m now using another new CSS function called color-mix(), and it’s pretty badass how it just works. This is another Scss abstraction I didn’t need to use.
  • Switching themes means I transitioned from using Webpack to using Vite. It’s such a refreshing difference!
    • One major difference that I noticed immediately is the ability to run the vite server environment, and allow it to hijack the development environment for reloading.
    • In other words, I don’t need to have two environments to see live reloads anymore. If I’m using https://example.local/ to see WordPress work locally, Vite will use the same environment for live reloading. No need to switch to a different URL like https://localhost:3000! Truly, I’ve been annoyed by this for more than a decade about Webpack! No more!
  • With all of this, I changed every CSS partial from .scss to .css. Since CSS now supports nesting natively, Sass and Scss aren’t necessary for my personal work.
    • Now, that said, this theme does include PostCSS and Vite is still doing some kind of transpiling. I need to figure out how to turn off transpiling and allow Vite to just concatenate all CSS partials into the global CSS file, as well as generate a critical CSS file that I can insert into the <head> for even better performance. UPDATE: fixed transpiling from happening!

The fact that this new theme has likely half the dependencies that it used to is a big win for me. If I walk away from the theme files and come back in some time, it seems more likely that I won’t encounter legacy issues like I did with Webpack. In fact, here’s what the dependencies look like right now:

asuh.com development package dependences in May 2024 from package.json

I think I might clone the original theme at some point and update it to either remove whatever possible above as well as add back in some of the changes I made for this theme. So my Github might have one more repository before too long!

The takeaway from this work, at least for right now, is that I really enjoy working with Vite. It’s such a cool builder and feels so much easier than anything else I’ve used. I needed this kind of enjoyment with tech since my career has been such a rollercoaster of stress!

Oh, and I hope this automatically syndicates to Mastodon and Bluesky. So that’s another test of posting this.