I could probably list about 100 reasons, since as a founder, user, and (ahem) PRO member of CodePen myself, I’m motivated to do so. But let me just list a few here. Some of these are my favorites, some are what PRO members have told us are their favorite, and some are lesser-known but very awesome.
1) No-hassle Debug View
Debug View is a way to look at your the Pen you’ve built with zero CodePen UI around it and no <iframe> containing it. Raw output! That’s a dangerous thing, in the world of user-generated code. It could be highly abused if we let it go unchecked. The way it works is fairly simple.
You can use Debug View if :
You’re logged in
The Pen is PRO-owned
Logging in isn’t too big of a deal, but sometimes that’s a pain if you just wanna shoot over a Debug View URL to your phone or to CrossBrowserTesting or something. If you’re PRO, you don’t worry about it at all, Debug View is totally unlocked for your Pens.
2) Collab with anybody anytime
Collab Mode on CodePen is the one that’s like Google Docs: people can work together in real time on the same Pen. You type, they see you type, they type, you see what they type.
Here’s what is special about that:
There is nothing to install or set up, just shoot anybody a link.
Only you need to be PRO. Nobody else does. They don’t even have to be logged in.
Basically, you can be coding together with someone (or just one or the other of you watching, if you please) in about 2 seconds. Here’s a short silent video if you wanna see:
People use it for all sorts of things. In classrooms and educational contexts, for hiring interviews, and just for working out problems with people across the globe.
Drag and drop uploading
Need to quickly host an asset (like an image) somewhere? As in, quickly get a URL for it that you can use and count on forever? It’s as easy as can be on CodePen.
If you’re working on a Project, you can drag and drop files right into the sidebar as well:
Save Anything Privately
Privacy is unlimited on CodePen. If you’re PRO, you can make unlimited Private Pens and Private Collections. You’re only limited in Private Projects by the total number of Projects on your plan. This is the number one PRO feature on CodePen for a variety of reasons. People use them to keep client work safe. People use them to experiment without anyone seeing messy tidbits. People use them to keep in-progress ideas.
I didn’t even mention my actual favorite CodePen PRO feature. I’ll have to share that one some other time 😉
It wasn’t long ago when Mikael Ainalem’s Pen demonstrated how you might use SVG outlines in HTML then lazyload the image (later turned into a webpack loader by Emil Tholin). It’s kind of like a skeleton screen, in that it gives the user a hint of what’s coming. Or the blur up technique, which loads a very small image blurrily blown up as the placeholder image.
José M. Pérez documents those, plus some more basic options (nothing, an image placeholder, or a solid color), and best of all, a very clever new idea using Primitive (of which there is a mac app and JavaScript version), which creates overlapping SVG shapes to use as the placeholder image. Probably a bit bigger-in-size than some of the other techniques, but still much smaller than a high res JPG!
From credit card payment devices and gas pump screens to the software that your company creates, user interfaces react to the actions of the user and other sources and change their state accordingly. This concept isn’t just limited to technology, it’s a fundamental part of how everything works:
For every action, there is an equal and opposite reaction.
– Isaac Newton
This is a concept we can apply to developing better user interfaces, but before we go there, I want you to try something. Consider a photo gallery interface with this user interaction flow:
Show a search input and a search button that allows the user to search for photos
When the search button is clicked, fetch photos with the search term from Flickr
Display the search results in a grid of small sized photos
When a photo is clicked/tapped, show the full size photo
When a full-sized photo is clicked/tapped again, go back to the gallery view
Now think about how you would develop it. Maybe even try programming it in React. I’ll wait; I’m just an article. I’m not going anywhere.
Finished? Awesome! That wasn’t too difficult, right? Now think about the following scenarios that you might have forgotten:
What if the user clicks the search button repeatedly?
What if the user wants to cancel the search while it’s in-flight?
Is the search button disabled while searching?
What if the user mischievously enables the disabled button?
Is there any indication that the results are loading?
What happens if there’s an error? Can the user retry the search?
What if the user searches and then clicks a photo? What should happen?
These are just some of the potential problems that can arise during planning, development, or testing. Few things are worse in software development than thinking that you’ve covered every possible use case, and then discovering (or receiving) new edge cases that will further complicate your code once you account for them. It’s especially difficult to jump into a pre-existing project where all of these use cases are undocumented, but instead hidden in spaghetti code and left for you to decipher.
Stating the obvious
What if we could determine all possible UI states that can result from all possible actions performed on each state? And what if we can visualize these states, actions, and transitions between states? Designers intuitively do this, in what are called „user flows” (or „UX Flows”), to depict what the next state of the UI should be depending on the user interaction.
In computer science terms, there is a computational model called finite automata, or „finite state machines” (FSM), that can express the same type of information. That is, they describe which state comes next when an action is performed on the current state. Just like user flows, these finite state machines can be visualized in a clear and unambiguous way. For example, here is the state transition diagram describing the FSM of a traffic light:
What is a finite state machine?
A state machine is a useful way of modeling behavior in an application: for every action, there is a reaction in the form of a state change. There’s 5 parts to a classical finite state machine:
A set of states (e.g., idle, loading, success, error, etc.)
A set of actions (e.g., SEARCH, CANCEL, SELECT_PHOTO, etc.)
An initial state (e.g., idle)
A transition function (e.g., transition('idle', 'SEARCH') == 'loading')
Final states (which don’t apply to this article.)
Deterministic finite state machines (which is what we’ll be dealing with) have some constraints, as well:
There are a finite number of possible states
There are a finite number of possible actions (these are the „finite” parts)
The application can only be in one of these states at a time
Given a currentState and an action, the transition function must always return the same nextState (this is the „deterministic” part)
Representing finite state machines
A finite state machine can be represented as a mapping from a state to its „transitions”, where each transition is an action and the nextState that follows that action. This mapping is just a plain JavaScript object.
Let’s consider an American traffic light example, one of the simplest FSM examples. Assume we start on green, then transition to yellow after some TIMER, and then RED after another TIMER, and then back to green after another TIMER:
Given the current state and an action, what will the next state be?
With our setup, transitioning to the next state based on an action (in this case, TIMER) is just a look-up of the currentState and action in the machine object, since:
machine[currentState] gives us the next action mapping, e.g.: machine['green'] == {TIMER: 'yellow'}
machine[currentState][action] gives us the next state from the action, e.g.: machine['green']['TIMER'] == 'yellow':
Instead of using if/else or switch statements to determine the next state, e.g., if (currentState === 'green') return 'yellow';, we moved all of that logic into a plain JavaScript object that can be serialized into JSON. That’s a strategy that will pay off greatly in terms of testing, visualization, reuse, analysis, flexibility, and configurability.
Taking a look at a more complicated example, let’s see how we can represent our gallery app using a finite state machine. The app can be in one of several states:
start – the initial search page view
loading – search results fetching view
error – search failed view
gallery – successful search results view
photo – detailed single photo view
And several actions can be performed, either by the user or the app itself:
SEARCH – user clicks the „search” button
SEARCH_SUCCESS – search succeeded with the queried photos
SEARCH_FAILURE – search failed due to an error
CANCEL_SEARCH – user clicks the „cancel search” button
SELECT_PHOTO – user clicks a photo in the gallery
EXIT_PHOTO – user clicks to exit the detailed photo view
The best way to visualize how these states and actions come together, at first, is with two very powerful tools: pencil and paper. Draw arrows between the states, and label the arrows with actions that cause transitions between the states:
We can now represent these transitions in an object, just like in the traffic light example:
Now let’s see how we can incorporate this finite state machine configuration and the transition function into our gallery app. In the App’s component state, there will be a single property that will indicate the current finite state, gallery:
This looks similar to the previously described transition(currentState, action) function, with a few differences:
The action is an object with a type property that specifies the string action type, e.g., type: 'SEARCH'
Only the action is passed in since we can retrieve the current finite state from this.state.gallery
The entire app state will be updated with the next finite state, i.e., nextGalleryState, as well as any extended state (nextState) that results from executing a command based on the next state and action payload (see the „Executing commands” section)
Executing commands
When a state change occurs, „side effects” (or „commands” as we’ll refer to them) might be executed. For example, when a user clicks the „Search” button and a 'SEARCH' action is emitted, the state will transition to 'loading', and an async Flickr search should be executed (otherwise, 'loading' would be a lie, and developers should never lie).
We can handle these side effects in a command(nextState, action) method that determines what to execute given the next finite state and action payload, as well as what the extended state should be:
// ...
command(nextState, action) {
switch (nextState) {
case 'loading':
// execute the search command
this.search(action.query);
break;
case 'gallery':
if (action.items) {
// update the state with the found items
return { items: action.items };
}
break;
case 'photo':
if (action.item) {
// update the state with the selected photo item
return { photo: action.item };
}
break;
default:
break;
}
}
// ...
Actions can have payloads other than the action’s type, which the app state might need to be updated with. For example, when a 'SEARCH' action succeeds, a 'SEARCH_SUCCESS' action can be emitted with the items from the search result:
The command() method above will immediately return any extended state (i.e., state other than the finite state) that this.state should be updated with in this.setState(...), along with the finite state change.
The final machine-controlled app
Since we’ve declaratively configured the finite state machine for the app, we can render the proper UI in a cleaner way by conditionally rendering based on the current finite state:
You might have noticed data-state={galleryState} in the code above. By setting that data-attribute, we can conditionally style any part of our app using an attribute selector:
This is preferable to using className because you can enforce the constraint that only a single value at a time can be set for data-state, and the specificity is the same as using a class. Attribute selectors are also supported in most popular CSS-in-JS solutions.
Advantages and resources
Using finite state machines for describing the behavior of complex applications is nothing new. Traditionally, this was done with switch and goto statements, but by describing finite state machines as a declarative mapping between states, actions, and next states, you can use that data to visualize the state transitions:
Furthermore, using declarative finite state machines allows you to:
Store, share, and configure application logic anywhere – similar components, other apps, in databases, in other languages, etc.
Make collaboration easier with designers and project managers
Statically analyze and optimize state transitions, including states that are impossible to reach
Easily change application logic without fear
Automate integration tests
Conclusion and takeaways
Finite state machines are an abstraction for modeling the parts of your app that can be represented as finite states, and almost all apps have those parts. The FSM coding patterns presented in this article:
Can be used with any existing state management setup; e.g., Redux or MobX
Can be adapted to any framework (not just React), or no framework at all
Are not written in stone; the developer can adapt the patterns to their coding style
Are not applicable to every single situation or use-case
From now on, when you encounter „boolean flag” variables such as isLoaded or isSuccess, I encourage you to stop and think about how your app state can be modeled as a finite state machine instead. That way, you can refactor your app to represent state as state === 'loaded' or state === 'success', using enumerated states in place of boolean flags.
Resources
I gave a talk at React Rally 2017 about using finite automata and statecharts to create better user interfaces, if you want to learn more about the motivation and principles:
When you use a bit of inline <svg> and you don’t set height and width, but you do set a viewBox, that’s a fitwigoo. I love the name.
The problem with fatwigoo’s is that the <svg> will size itself like a block-level element, rendering enormously until the CSS comes in and (likely) has sizing rules to size it into place.
It’s one of those things where if you develop with pretty fast internet, you might not ever see it. But if you’re somewhere where the internet is slow or has high latency (or if you’re Karl Dubost and literally block CSS), you’ll probably see it all the time.
I was an offender before I learned how obnoxious this is. At first, it felt weird to size things in HTML rather than CSS. My solution now is generally to leave sensible defaults on inline SVG (probably icons) like height="20" width="20" and still do my actual sizing in CSS.
If we put four grid items in there, here’s what it looks like when inspecting it in Firefox DevTools:
Now let’s target one of those grid items and give it a background-color:
The grid area and the element are the same size!
There is a very specific reason for that though. It’s because the default value for justify-items and align-items is stretch. The value of stretch literally stretches the item to fill the grid area.
But there are several reasons why the element might not fill a grid area:
On the grid parent, justify-items or align-items is some non-stretch value.
On the grid element, align-self or justify-self is some non-stretch value.
On the grid element, if height or width is constrained.
Check it:
Who cares?
I dunno it just feels useful to know that when placing an element in a grid area, that’s just the starting point for layout. It’ll fill the area by default, but it doesn’t have to. It could be smaller or bigger. It could be aligned into any of the corners or centered.
Perhaps the most interesting limitation is that you can’t target the grid area itself. If you want to take advantage of alignment, for example, you’re giving up the promise of filling the entire grid area. So you can’t apply a background and know it will cover that whole grid area anymore. If you need to take advantage of alignment and apply a covering background, you’ll need to leave it to stretch, make the new element display: grid; also, and use that for alignment.
I recently learned about a browser feature where, if you provide a special HTTP header, it will automatically post to a URL with a report of any non-HTTPS content. This would be a great thing to do when transitioning a site to HTTPS, for example, to root out any mixed content warnings. In this article, we’ll implement this feature via a small WordPress plugin.
What is mixed content?
„Mixed content” means you’re loading a page over HTTPS page, but some of the assets on that page (images, videos, CSS, scripts, scripts called by scripts, etc) are loaded via plain HTTP.
A browser warning about mixed content.
I’m going to assume that we’re all too familiar with this warning and refer the reader to this excellent primer for more background on mixed content.
What is Content Security Policy?
A Content Security Policy (CSP) is a browser feature that gives us a way to instruct the browser on how to handle mixed content errors. By including special HTTP headers in our pages, we can tell the browser to block, upgrade, or report on mixed content. This article focuses on reporting because it gives us a simple and useful entry point into CSP’s in general.
CSP is an oddly opaque name. Don’t let it spook you, as it’s very simple to work with. It seems to have terrific support per caniuse. Here’s how the outgoing report is shaped in Chrome:
The outgoing report in the network panel of Chrome’s inspector.
What do I do with this?
What you’re going to have to do, is tell the browser what URL to send that report to, and then have some logic on your server to listen for it. From there, you can have it write to a log file, a database table, an email, whatever. Just be aware that you will likely generate an overwhelming amount of reports. Be very much on guard against self-DOSing!
Can I just see an example?
You may! I made a small WordPress plugin to show you. The plugin has no UI, just activate it and go. You could peel most of this out and use it in a non-WordPress environment rather directly, and this article does not assume any particular WordPress knowledge beyond activating a plugin and navigating the file system a bit. We’ll spend the rest of this article digging into said plugin.
Sending the headers
Our first step will be to include our content security policy as an HTTP header. Check out this file from the plugin. It’s quite short, and I think you’ll be delighted to see how simple it is.
There a lot of args we can play around with there.
With the Content-Security-Policy-Report-Only arg, we’re saying that we want a report of the assets that violate our policy, but we don’t want to actually block or otherwise affect them.
With the default-src arg, we’re saying that we’re on the lookout for all types of assets, as opposed to just images or fonts or scripts, say.
With the https arg, we’re saying that our policy is to only approve of assets that get loaded via https.
With the unsafe-inline and unsafe-eval args, we’re saying we care about both inline resources like a normal image tag, and various methods for concocting code from strings, like JavaScripts eval() function.
Finally, most interestingly, with the report-uri $rest_url arg, we’re giving the browser a URL to which it should send the report.
If you want more details about the args, there is an excellent doc on Mozilla.org. It’s also worth noting that we could instead send our CSP as a meta tag although I find the syntax awkward and Google notes that it is not their preferred method.
This article will only utilize the HTTP header technique, and you’ll notice that in my header, I’m doing some work to build the report URL. It happens to be a WP API URL. We’ll dig into that next.
Registering an endpoint
You are likely familiar with the WP API. In the old days before we had the WP API, when I needed some arbitrary URL to listen for a form submission, I would often make a page, or a post of a custom post type. This was annoying and fragile because it was too easy to delete the page in wp-admin without realizing what it was for. With the WP API, we have a much more stable way to register a listener, and I do so in this class. There are three points of interest in this class.
In the first function, after checking to make sure my log is not getting too big, I make a call to register_rest_route(), which is a WordPress core function for registering a listener:
In that function, I massage the report in it’s raw format, into a PHP array that my logging class will handle.
Creating a log file
In this class, I create a directory in the wp-content folder where my log file will live. I’m not a big fan of checking for stuff like this on every single page load, so notice that this function first checks to see if this is the first page load since a plugin update, before bothering to make the directory.
That update logic is in a different class and is wildly useful for lots of things, but not of special interest for this article.
Logging mixed content
Now that we have CSP reports getting posted, and we have a directory to log them to, let’s look at how to actually convert a report into a log entry,
In this class I have a function for adding new records to our log file. It’s interesting that much of the heavy lifting is simply a matter of providing the a arg to the fopen() function:
function add_row( $array ) {
// Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
$mode = 'a';
// Open the file.
$path = $this -> meta -> get_log_file_path();
$handle = fopen( $path, $mode );
// Add the row to the spreadsheet.
fputcsv( $handle, $array );
// Close the file.
fclose( $handle );
return TRUE;
}
Nothing particular to WordPress here, just a dude adding a row to a csv in a normal-ish PHP manner. Again, if you don’t care for the idea of having a log file, you could have it send an email or write to the database, or whatever seems best.
Caveats
At this point we’ve covered all of the interesting highlights from my plugin, and I’d advice on offer a couple of pitfalls to watch out for.
First, be aware that CSP reports, like any browser feature, are subject to cross-browser differences. Look at this shockingly, painstakingly detailed report on such differences.
Second, be aware that if you have a server configuration that prevents mixed content from being requested, then the browser will never get a chance to report on it. In such a scenario, CSP reports are more useful as a way to prepare for a migration to https, rather than a way to monitor https compliance. An example of this configuration is Cloudflare’s „Always Use HTTPS„.
Finally, the self-DOS issue bears repeating. It’s completely reasonable to assume that a popular site will rack up millions of reports per month. Therefore, rather than track the reports on your own server or database, consider outsourcing this to a service such as httpschecker.net.
Next steps
Some next steps specific to WordPress would be to add a UI for downloading the report file. You could also store the reports in the database instead of in a file. This would make it economical to, say, determine if a new record already exists before adding it as a duplicate.
More generally, I would encourage the curious reader to experiment with the many possible args for the CSP header. It’s impressive that so much power is packed into such a terse syntax. It’s possible to handle requests by asset type, domain, protocol — really almost any combination imaginable.