A great overview of the benefits and drawbacks of TypeScript-style static type systems.
When I talk to other developers about Observables, it’s often hard to explain their benefits because on the surface, they just look like glorified event emitters, but it’s how they compose that make handling dependencies between async events such a breeze. While working on the code snippet editor in WP-Gistpen, I came across an example that shows how easily Observables handle async behavior.
So here’s the setup: building a snippet editor on top of PrismJS and borrowing some code from Dabblet, both from Lea Verou, and using Redux as an Observable of states, we need to rerender the editor as the text changes, keeping the syntax highlighting up to date. We keep the position of the cursor and the value of the editor in the Store, allowing the reducer to be responsible for the complex logic that handling special text editor keystrokes, like enter, tab, etc.
The issue is rendering the editor requires us to track & reset the cursor, as we have to reset the text with the latest from the store and rehighlight it. If we do that while the user is typing, we have the potential to interrupt her, so we need to delay the render until the user is no longer typing. The render itself is scheduled in a
requestAnimationFrame, so if the user types before the next frame, we need to cancel the render request and wait until the user stops typing again. Otherwise, when the frame renders, the cursor will jump back to the position it was at when the render was scheduled.
So this is the problem we’re trying to solve.
brookjs, a component is just a function that takes a DOM element & a stream of
props$ and returns a stream of (usually Flux Standard) Actions from the element. Since we’re given an Observable of state, we’re able to get pretty fine control over exactly when the editor renders.
I’m using Kefir, but the same concepts apply any other Observable implementation. Here’s how I solved this:
This problem is obviously solvable in a stateful way, with the view being responsible for holding onto a reference to the render loop, scheduling it in one event callback if a render isn’t scheduled and cancelling the render on the other if it is. We’re not talking about a huge component here, so there’s no reason to think managing this state would be difficult.
But as this component grows in complexity (and it will), colocating the temporal dependencies makes it very easy to reason about how the component changes over time. In the above example, how keyup and keydown events interact with the render cycle is explicit, rather than bouncing between callbacks or methods to see how animations are scheduled and cancelled. There’s zero chance of accidental cancellations or double renders.
Side effects, like updating the DOM, are wrapped in a stream, so they can be handled asynchonrously and cancelled, if needed. Because an Observable comes with its own cleanup code (the function returned at the end of
stream‘s callback), when the active Observable is switched, the animation frame request for the previous Observable is cancelled, ensuring the user isn’t interrupted as she types. The
props$ stream has control over when the render happens, and
flatMapLatest ensures only the newest Observable is being observed at a time, so as the
props$ emits new state, previous renders are also cancelled.
brookjs provides some structure around this paradigm, but underneath, this is all that’s happening, and it provides some elegant solutions to thorny async problems. The canonical example is the autocomplete box, sending an AJAX request as a user types and cancelling the previous request. This is explained by Jafar Husain in this great talk.
Even after writing this article, the editor rendering continued to get more complicated, and handling it with Observables allowed me to focus on how particular events interacted with the render cycle, without worrying about how to manage what was actually happening at a given time. Let me know if you think the current implementation is easy to understand.
This post is part of the thread: Project: WP-Gistpen - an ongoing story on this site. View the thread timeline for more context on this post.
ah yes, the revolution we’ve all been waiting for. humans on the internet talking to brands so they dont have to talk to each other.
This is your regular reminder that you’re just a renter on Google’s land.
This post is part of the thread: The Case for Our (Digital) Space - an ongoing story on this site. View the thread timeline for more context on this post.
Not sure this is best, but using Kefir’s `withHandler`, this debounce’s the values from the stream to only emit the latest value on `requestAnimationFrame`.
This is a surprisingly helpful (and cute!) tool for learning Flexbox.
I had been working on oEmbed into WP-Gistpen, so I wrote this tutorial on customizing oEmbed content from WordPress yourself. How have you been using the new oEmbed feature in WordPress?
This post is part of the thread: Personal Milestone - an ongoing story on this site. View the thread timeline for more context on this post.
In our introduction to the series, we got a simple static page rendered with
handlebars. Now that we’ve got everything going, we’re going to leverage React’s server-side rendering to move from just sending some static HTML to sending a rendered component’s HTML. On the client side, we’ll bootstrap React into the rendered HTML using the same state that produced the HTML on the server, and the application can just pick up where it left off.
es2015 preset as well.
I got that working in the introduction to the series, even though it didn’t happen in that order in real life, so if you need a refresher, check that out. Now before we build our first React component, make sure you install
npm; these are the two main React tools we’re going to use in this project.
Just to get started with React, we’ll replicate the current
Hello World! setup with a simple
App component that takes a required
headline as its props.
If this is your first introduction to React, you’ll notice the XML-like JSX syntax in the
render function. This is transpiled by
class is a reserved word, you see above one of the many differences with plain HTML; we have to use
className to give the DOM node a
class. If we were to render it with
headline as "Hello World!", the resulting HTML would look like this:
As for the other two props on the object: both them (
propTypes) are primarily useful for development. One of React’s greatest strengths is the ecosystem of development tools that have cropped up around it; this feature comes built-in! You get
console messages when the component receives props of the wrong type.
Ensuring that you’re validating your props’ values and types during development helps ensure nothing unexpected happens during production, so definitely get in the habit of defining your components’
propTypes along with its
render method as part of a standard component. The React docs on "reusable components" has the full list of types and constraints you can put in your
displayName is used in these log methods to indicate which component has the error, making it easier to debug where the problem is coming from.
This is a really simple component, but now we need to pass it props and render it. The process for doing that on the server side mirrors the client side, so let’s get it running on the server first.
In our main
server.js file, we have to change the root (
/) route to render this component instead of the static string we provided earlier. Here’s the new
react-dom is React’s DOM rendering tools. These used to be bundled with React but they were split off in v0.14. They were split off from the main React package because React has ambitions beyond just the DOM, like
react-native and others, so separating the packages makes sense for the project. These tools allow us to render the React components on the server as well as to the DOM; in this case, we’re using it to render the React component to a string, so the
express server can send it to the client.
The first thing we do is set up the initial page
state variable. As we build out the full application, this would be the point where we fetch the information from the database that’s required to render the page state. In our case, we’re just going to set our
From there, we just call
ReactDOMServer.renderToString on the
App component, passing in the
state variable using JSX’s spread attributes to pass the object’s properties as the component’s props. This JSX syntax is modeled after ES6’s spread operator, allowing you to pass in the entire state object rather than just the props the component needs, which can be a bit more cumbersome for larger components.
Lastly, we stringify the state object so we can pass it into the view, where it’ll get received by the client code to boostrap the same React component.
On the client-side, we just need to bootstrap off the DOM node and state object we originally rendered with:
On the client side, we call the
render method with the component as well as the DOM element to render onto. React will automatically pick up the fact that this is React-sourced HTML and instead of rerendering the whole page, will just attach the event listeners to the DOM, using the rendered
From there, you can bootstrap your application however you’d like, depending upon how you choose to structure your application. In the next article, we’re going to start wiring up the RxJS streams, building a stream that will model our state as a series of messages as well functioning as a clearinghouse for all of the messages running through the client application. In this way, we’ll be able to direct those messages to and from the server and throughout the server application, with the UI just responding to state refreshes from this main stream.
This post is part of the thread: RxJS & React w/ Chatr - an ongoing story on this site. View the thread timeline for more context on this post.
I ran into a problem today. I had two elements next to each other on a row. I needed the first element to just be contained to the width of its child elements, while the second element needed to take up the rest of the space.
Here’s some dummy markup to get the idea:
The problem is, when I was using
float left and right, I was setting the width of the second element manually using media queries, which worked at first but turned into a real bit of trouble when I attempted to make the containing element (a
column wrapping the
row) more responsive.
I couldn’t keep adding breakpoints and reset the size. Or I could, but it would be really brittle and would need to be updated every time the breakpoints of the containing element changed. I floundered around a bit, trying to find a solution, until I settled on this one, which relies on the oft-maligned
<table> per se, but
display: table. I have not used this feature much, since my CSS knowledge is generally pretty minimal, but there are a lot of places, like this one, where it’s going to be a lot more functional than the standard "float the div" method we’re all used to for building responsive layouts. Here’s how it works:
First, I needed to add an extra wrapper, so our HTML now looks like this:
And our CSS looks like this:
The nifty thing to notice is the
.contained CSS. We set the width to be impossibly small, but tell the cell not wrap its contents. This has the effect of forcing the cell to expand to be the width of its contents, while allowing the
.expanded div to take over the remaining space, achieving the effect I was looking for.
Do you know of any other uses for
display: table that can’t be solved with the standard "float the div" method? Let me know in the comments.
I’ve played around with RxJS & React[^1] a little bit, but I’m not entirely sure what a full-stack architecture might look like (yet). I want to explore the possibilities by building a real-time chat application (with the uninspiring name Chatr) on Node.js with RxJS, React, & Ramda, applying functional programming to a system that can easily be modeled as a stream of messages/events.
With RxJS, I should be able pipe messages around the application, including into React to update the UI on the client side, as well as to and from a data store like Redis or a messaging queue like RabbbitMQ on the server side, with the data streaming between the server & client over a Socket.io stream. This architecture could also be inspired by Flux, ensuring all data flows into a central "store stream," which then pipes out the messages to wherever it needs to go. This primary data store stream probably could be reused on both the client & server side, which allows us to introduce some isomorphism in both our data handling & UI.
My plan is to build this in public and write about it, and see what some of the advantages and drawbacks of this approach for building web applications. You can follow along with the repo on GitHub, or keep up with the thread on this website.
Before we can get started doing anything interesting, we’ve got to get some boilerplate going. Since we want to try out some isomorphic techniques, we’re going to need to, at a minimum, get the JSX compiled on the server side.
babel is the default standard for compiling JSX, and they have a very clear example for getting it running on the server. Since we’re already using it, we’re also going to bring in ES6 compilation and use that for both the server- and client-side code.
Following along with the example, we’re going to add
babel-cli, and the two babel presets we’re going to use,
babel-preset-react. Since we’re going to be sharing the
babel configuration between the server and client, we need a
.babelrc file, which
babel uses to register presets and plugins:
nodemon server.js --exec babel-node to the
package.json‘s scripts key as
"start", so we can run
npm start to run the server.
babel-node is shipped with the
babel-cli package we installed, and it ensures our server-side code is compiled on-the-fly by
babel and then run in
nodemon recompiling and restarting the server whenever our code changes.
We’re going to use express.js to handle routing and serve our static assets. Let’s create the
server.js file and get some simple routes going:
Pretty basic express server; run
npm start in your terminal and then go to localhost:3000. You should see a big "Hello World!". Got it? Good! Let’s get some script and style compilation going.
We’ll start with the scripts.
browserify are both solid options for compiling scripts using
babel. I’ve used
browserify a lot more than I’ve used
webpack, so I’m going to use
webpack for this project. Fortunately, the configuration isn’t that complicated for a simple setup like this:
We’re not going to worry about getting any of the really complicated features setup, like hot reloading or dev servers or anything like that. Instead, we’re going start with to create a simple script that uses some ES6 to ensure that we’re compiling our scripts correctly.
webpack, you can just run
webpack in your terminal and it should spit out a
main.min.js file in your
public folder. Pull that up in your browser and you should see the compiled file.
On the style side, we can compile our
styles.scss file with
node-sass. I’m going to be including Bourbon, Neat, and Bitters for this project, as I like their mixin-only approach for its flexibility and control. Here’s the very basic
I’d love to get this setup with Eyeglass as well, but we’ll start with this. Install
node-sass and run
node-sass styles.scss public/styles.css. We should see the CSS file rendered, compressed and compiled correctly, with a long sourcemap appended at the end.
which we’re going to use to render a very simple template:
This is set up this way in preparation for implementing is server-side rendering! The
app variable in the template context will become the rendered HTML string from React, and the
state variable will be the state object that produced the given HTML. Then on the client side, we’ll pull in current state, render the React components on the current state on the page, and bootstrap the application. This is how the Redux docs suggest doing it, and since they know what they’re doing, we’re going to follow their lead.
But we’re going to wire that up in the next tutorial. For now, you should have a simple page page, rendering "Hello World!", with a CSS file and a script that outputs
3 to the console. Next, we’re going to write our first React component, render it on the server, and bootstrap our application.
[^1]: In the next version of WP-Gistpen, the settings page is built with React & RxJS.
This post is part of the thread: RxJS & React w/ Chatr - an ongoing story on this site. View the thread timeline for more context on this post.