<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Jesse Pinho on Medium]]></title>
        <description><![CDATA[Stories by Jesse Pinho on Medium]]></description>
        <link>https://medium.com/@jessepinho?source=rss-786d54738d11------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ocJ2F42h7t42Qgmpf-jvng.jpeg</url>
            <title>Stories by Jesse Pinho on Medium</title>
            <link>https://medium.com/@jessepinho?source=rss-786d54738d11------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 19:39:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jessepinho/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Make it pop! Creating interactive content with React and Contentful]]></title>
            <link>https://medium.com/bleeding-edge/make-it-pop-creating-interactive-content-with-react-and-contentful-9b2ecac06d3?source=rss-786d54738d11------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b2ecac06d3</guid>
            <category><![CDATA[online-publishing]]></category>
            <category><![CDATA[interactive-content]]></category>
            <category><![CDATA[creative-coding]]></category>
            <category><![CDATA[contentful]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jesse Pinho]]></dc:creator>
            <pubDate>Wed, 26 Jun 2019 09:15:47 GMT</pubDate>
            <atom:updated>2019-06-26T11:43:46.266Z</atom:updated>
            <content:encoded><![CDATA[<h4>Coding for the future of online publishing</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HaOXT6eVx5Gv0FsK1Vtr-A@2x.png" /><figcaption>Illustration by <a href="https://www.instagram.com/marta__pucci/?hl=en">Marta Pucci</a></figcaption></figure><p><em>Note: this article was a joint effort between Clue and Contentful. You can find the original version on Contentful’s blog </em><a href="https://www.contentful.com/blog/2019/05/31/interactive-content-react-rich-text-editor/"><em>here</em></a><em>. You can also watch </em><a href="https://jessepinho.com/talks"><em>Jesse’s talk</em></a><em> that inspired this post.</em></p><p>A year ago, we relaunched <a href="https://helloclue.com/">the Clue website</a> as an encyclopedia for women and people with cycles. Clue’s first product is a period tracker app, which is used by over 10 million people to track their symptoms and learn about patterns in their reproductive health. With the website relaunch, we put all of our content together in one organized place where people could more easily get the information they want.</p><p><a href="https://helloclue.com/articles/cycle-a-z/period-blood-color-brown-black-dark-does-it-matter">Here’s</a> an example of some of our encyclopedic content. This is one of our most popular articles, which explains what the significance of period blood color is. (Spoiler alert: it’s not that significant.)</p><p>We have a ton of articles like these. Lately, we’ve been thinking that our readers might be better served by interactive content that does more showing and less telling.</p><p>Another of our top 10 most popular articles is titled, <a href="https://helloclue.com/articles/cycle-a-z/what-is-the-clitoris">“What is the clitoris?”</a>. The article goes into detail about the anatomical structure of the clitoris, but the entire article was just text. We thought we could do better and asked ourselves: what if, as you scroll through and read about the different parts of the clitoris, an illustration would highlight the parts being discussed so you could really <em>get</em> what you’re reading about?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqWs-op4Vwk6NW3xcKJrSA.png" /></figure><p>In our Contentful setup, we have a content type called “Article” with a Markdown body field. This field contains a bunch of text in the clitoris article, but we wanted to figure out how to get a plain text field to also include interactivity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sqFQnBwU9ObXVLzp.png" /></figure><p>Our first attempt at this was to extend Markdown’s syntax using the concept of “shortcodes.” Basically, this means inserting an HTML comment in the middle of the article body, with special syntax inside of it that refers to an interactive piece. Our Markdown renderer would pick up that HTML comment and render a custom React component in its place. That way, writers could insert some custom interactive widget in the middle of an article, and control where it appears based on where they inserted the HTML comment.</p><p>But that didn’t work super well, for several reasons:</p><ol><li>It was brittle. Our writers had to insert an HTML comment in a very specific format that could be easily broken</li><li>The text in the interactive portion was hard-coded. Our writers would have to email me if they wanted to change that text.</li><li>Because the text was hard-coded, any changes to the text required a code deploy.</li></ol><p>We knew we could do better. Specifically, we wanted to achieve the following five goals with our interactive pieces:</p><ol><li>Writers should be able to make changes to text without waiting for a code deploy.</li><li>Content should be translatable using Contentful’s existing localization functionality.</li><li>The setup shouldn’t be brittle:<br>- We wanted to avoid telling writers, “Make sure you include these items in this specific order!” since that means things could break easily.<br>- If a piece has inline HTML to make the interaction work, and a writer accidentally deletes part of an HTML tag while making edits, the whole interactive piece could break.</li><li>Writers shouldn’t have to deal with code. Ideally, the interface should be very intuitive and easy-to-use for non-tech folks.</li><li>Writers should be able to preview their changes and get quick feedback</li></ol><p>To solve this problem, I turned to the New York Times. Their engineering blog contains a <a href="https://open.nytimes.com/building-a-text-editor-for-a-digital-first-newsroom-f1cb8367fc21">fascinating article about their rich text editor</a>, which treats every bit of content in their articles as a series of nodes. Paragraphs, pull quotes, images, captions, headings — everything is just a node in their text editor. And then on the front end they can render different node types however they’d like.</p><p>I connected with an engineer there, and he said that for the interactive pieces, they simply created a new node type: an “interactive” node, which had a field that referenced the interactive code written for that specific article. When authoring an article they would create a new node, just like a paragraph tag or a header, and insert it into the middle of the article. Then, their renderer for the node would render the interactive content designed for it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wJRvI38Tz2PVNhZz.png" /></figure><p>Contentful has a new <a href="https://www.contentful.com/developers/docs/concepts/rich-text/">rich text feature</a> that works very similarly to the way the New York Times text editor works. In the screenshot above from the Contentful web app, you see a WYSIWYG text editor where you can compose rich text with formatting and so forth, without having to deal with the special syntax required by Markdown.</p><p>When you request rich-text content from the Contentful API, it represents your text as a series of blocks in the form of JSON objects that can be nested inside of each other. So a paragraph, a heading, a quotation — each of these are essentially a “node” in this giant JSON structure describing your content.</p><p>This allows for a great degree of flexibility. Instead of just composing text, you can also insert entries from other content types, right in the middle of the text!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I9TLtsq9Ldj7DIGK.png" /></figure><p>You can see here in the screenshot how a content type called “Block: Video”, has been inserted directly into the rich text body.</p><p>I realized I could create custom content types for any kind of interactive or custom content that I would need in an article, and then write React components that would render these content types exactly the way I want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vcok0OUSQPQHxVcU.png" /></figure><p>So, I’ll take you through the model we set up. First, I created a new content type and called it “Custom Block.” It only has three fields: the “Name” field references an actual React component name — that is, the machine name of the React component. Microcopies is a multi-reference field to the “Microcopy” content type, which I’ll get to in a second. And “Asset(s)” is for all the assets the component needs, with the title of each asset set to a machine name that the custom block refers to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LIf5TxDiRsSCsicq.png" /></figure><p>The Microcopy content type is simply a key-value pair. The key is a machine name referring to this piece of copy, and the value is a long text field, which can even include Markdown. <a href="http://bit.ly/contentful-microcopy">This article</a> was my inspiration for microcopy — give it a read!</p><p>So, we have a custom block model, and we can insert it into the middle of an article’s rich text field. Let’s dive into the code and see what it takes to render all of this.</p><p>First, we’ll install the rich-text-to-react NPM module. This module was specifically made for Contentful&#39;s rich text feature. It recursively loops over the JSON object and creates a React component tree for the whole thing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nNKNJ9sYFa3mA8Hk.png" /></figure><p>It also lets you override its default renderers for different node types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fXsOqNJlrtsW84-3.png" /></figure><p>For example, if you want to use <a href="https://www.styled-components.com/">styled-components</a> to make a styled paragraph tag, you can pass that styled component in the config, and it will use that rather than a native paragraph tag.</p><p>As you can see, we have styled versions of many of the node types that you’ll find in our rich text documents. But those first three renderers (lines 26–28) are the more interesting ones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*f_ur67G6cb5P9RgM.png" /></figure><p>Line 26 specifies the renderer for embedded entries. The renderer itself checks the content type of the embedded entry, and then delegates to the React component that knows how to render it — meaning that, if it’s a custom block entry, it will delegate to the CustomBlock React component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_ohEJvzsVbJBbpfV.png" /></figure><p>Here’s my CustomBlock component. It doesn&#39;t do a lot on its own — it just imports a hard-coded registry of all the different custom blocks I&#39;ve created. Then it looks in that registry for a component with the name we specified in the custom block&#39;s &quot;Name&quot; field, and renders it if it exists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JE2h9vWedfFjbh63.png" /></figure><p>Here’s the registry itself.</p><p>This maps machine names of custom blocks to an asynchronously loaded component. We use code splitting here so that the custom blocks aren’t loaded as part of the main JavaScript bundle.</p><p>As I mentioned earlier, we grab a React component from the custom block registry based on its name, and then render it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*systZZN3oFRkZYxk.png" /></figure><p>You’ll notice that we’re also passing the entire custom block entry from Contentful into the component we loaded from the registry. This gives the component access to all of the microcopies and assets that we’ve entered in Contentful. Then, that component uses the machine names of the microcopies to determine which pieces of text should show up where.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fp1eXEphumaSHWXz.png" /></figure><p>I won’t go into too much of our code, but here’s an example from the clitoris article of how the microcopy can be used. You can see how the alt text of several images is set via this microcopies object, which is just an object of key-value pairs generated from the microcopies array in Contentful.</p><p>So, to recap:</p><ol><li>First, the rich-text-to-react module goes through the rich text tree, and converts nodes to their corresponding React components</li><li>For nodes that are embedded custom blocks, the CustomBlock React component is loaded and rendered</li><li>The CustomBlock component takes the name of the custom block entry, and looks it up in its hard-coded registry of custom blocks. If it finds it, it renders the component linked in the registry.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cre6IksN0A4u-gWj.png" /></figure><p>Moving on: let’s actually go through the process of creating an article with this setup. As you remember, here’s the old way of doing it in the screenshot above: a Markdown body field with an HTML shortcode in the middle of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0r30CqZZbeI064GT.png" /></figure><p>But with rich text, we have the WYSIWYG editor. And more importantly…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BldRwbnqMxT37ZAS.png" /></figure><p>…we can embed our custom block entry right in the middle of the text! Much better than the HTML shortcode we used to be using!</p><p>Let’s click the edit button and see what the custom block record looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kwn2fGOapOImbAZe.png" /></figure><p>Now we see all the microcopies associated with this article. Let’s go one level deeper and click the edit button on one of those.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*71dyXAVSpyDIcS6m.png" /></figure><p>Here you can see the alt text for a single image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/391/1*Efm4twYVizS0oivy2eVfSQ.gif" /></figure><p>Once we’ve set up all the microcopies in the custom block, the article is ready to go. We now have a custom block in the middle of the article. The parts of the text it’s scrolling past are actually microcopies that, as they go past, trigger the animation at the top to switch.</p><p>If you want to see a couple more examples of custom blocks in the middle of rich text fields, visit our <a href="https://helloclue.com/jobs">jobs page</a> (we’re hiring, by the way) and our <a href="https://helloclue.com/period-tracker-app">app download page</a>, which both include more interactivity and animations.</p><p>Earlier I mentioned the five goals that I had when implementing interactivity in rich text. Now is probably a good time to revisit them and see how we did:</p><ol><li><em>Writers can make changes to text without waiting for a code deploy. <br></em>✅ Check! They can make changes via the microcopies</li><li><em>Content can be translated using Contentful’s existing localization functionality.</em><br>✅ Also check! Microcopies can be localized</li><li><em>The setup isn’t brittle.<br></em>👌 Mostly good, although there’s still a risk that writers could accidentally change one of the keys of the microcopies. Ideally, they shouldn’t be able to edit the keys at all — just the values. But we’re still in better shape than before, when I was using HTML tags and comments.</li><li><em>Writers don’t have to deal with code.<br></em>👌 Again, mostly good. I do think of machine names as being a bit code-ish, but other than that, they can just insert custom blocks into text using the native Contentful interface, and don’t have to worry about using shortcode syntax.</li><li><em>Writers are able to preview their changes and get quick feedback.<br></em>✅ Check! Writers can edit the microcopies and then use Contentful’s content preview to see how their changes look in staging.</li></ol><p>Overall, I’d say we did pretty well.</p><p>That said, I do see some clear areas for improvement.</p><p>First, it’d be great to have a clearer UI for editing microcopy. Contentful does have a feature for bulk editing referenced entries, but even that isn’t exactly what I want, since writers can still edit the Key field, which is a bit risky. So I might want to develop a UI extension for editing microcopies.</p><p>Second, while the microcopies are indeed translatable, sending individual microcopies to translators and then copy-pasting them back in is obviously pretty tedious. So I’d like to set up some tooling that can, for example, auto-generate a JSON file that our writers can use to upload to our translation provider.</p><p>Lastly, I’d love to hear from readers on this solution and what could be better. Feel free to add comments below or reach out to me on Twitter: <a href="https://twitter.com/jessepinho?lang=en">@jessepinho</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b2ecac06d3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleeding-edge/make-it-pop-creating-interactive-content-with-react-and-contentful-9b2ecac06d3">Make it pop! Creating interactive content with React and Contentful</a> was originally published in <a href="https://medium.com/bleeding-edge">Bleeding Edge</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keep it contained!]]></title>
            <link>https://medium.com/bleeding-edge/enforcing-an-aspect-ratio-on-an-html-element-in-react-and-css-27a13241c3d4?source=rss-786d54738d11------2</link>
            <guid isPermaLink="false">https://medium.com/p/27a13241c3d4</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jesse Pinho]]></dc:creator>
            <pubDate>Thu, 09 Aug 2018 00:34:12 GMT</pubDate>
            <atom:updated>2018-11-15T16:15:39.811Z</atom:updated>
            <content:encoded><![CDATA[<h4>Enforcing an aspect ratio on an HTML element in React and CSS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nid7QzbP-rV6aD4xq9_KQQ@2x.png" /><figcaption>Illustration by Marta Pucci</figcaption></figure><p>Frequently, it’s necessary to set an aspect ratio on an element (like a &lt;div&gt; element), so that it will maintain its shape while scaling to any size. For example, you may be displaying a YouTube video in an iframe, and you want to make sure it shows up in 16:9.</p><p>This is relatively simple to accomplish due to a CSS quirk. Per <a href="https://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#padding-properties">w3.org</a>, when you set the CSS padding for a box:</p><blockquote>The percentage is calculated with respect to the <em>width</em> of the generated box’s <a href="https://www.w3.org/TR/2011/REC-CSS2-20110607/visuren.html#containing-block">containing block</a>, even for <a href="https://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#propdef-padding-top">‘padding-top’</a> and <a href="https://www.w3.org/TR/2011/REC-CSS2-20110607/box.html#propdef-padding-bottom">‘padding-bottom’</a>.</blockquote><p>That is, if you have a 200 pixel-wide element and you set its padding-bottom to 50%, the bottom padding will be 100 pixels—regardless of the element’s height!¹</p><p>We can take advantage of this fact to set an aspect ratio for an element, even as the window scales to any size. All we have to do is divide the height of our aspect ratio by its width, and then use that as the percentage for padding-bottom. For example, to enforce a 16:9 aspect ratio for an element, divide 9 by 16, which is 0.5625. Then, set the padding-bottom to 56.25%. Note that you also have to set the height to 0 to ensure that the padding constitutes the entirety of the element. Here’s a full CSS class for a 16:9 container:</p><pre>.aspect-ratio--16x9 {<br>  width: 100%;<br>  height: 0;<br>  padding-bottom: 56.25%;<br>}</pre><h4>Working out the quirks</h4><p>One issue you might face here is that, while the 16:9 container takes up the right amount of space on the page, its height is set to 0. While this will work fine for displaying a background image cropped to a specific aspect ratio, it doesn’t handle actual content well. Take the YouTube iframe from earlier: if you put an iframe into this container, it won’t actually fit into the aspect ratio you’ve specified. By default, YouTube’s embed code includes width and height attributes on the video player iframe, so it will stick out of your container element if it’s too big.</p><p>Meanwhile, if you style it with CSS to have a width and height of 100%, it will disappear! This is because, when you set its height to 100%, it will match the height of its container, which is 0. So, how do you get the iframe to match the aspect ratio of the container element?</p><p>The solution is to add an inner wrapper to the container element, which stretches to fill it. We can do that by absolute-positioning it:</p><pre>.aspect-ratio__inner-wrapper {<br>  position: absolute;<br>  top: 0;<br>  right: 0;<br>  bottom: 0;<br>  left: 0;<br>}</pre><p>We then have to add position: relative to the container, so that it positions its inner wrapper correctly:</p><pre>.aspect-ratio--16x9 {<br>  width: 100%;<br>  height: 0;<br>  padding-bottom: 56.25%;<br>  <strong>position: relative;<br></strong>}</pre><p>Then, we can safely give the iframe a width and height of 100%, and it will maintain its aspect ratio at all screen sizes! Here’s the complete code example:</p><pre>/* styles.css */</pre><pre>.aspect-ratio--16x9 {<br>  width: 100%;<br>  height: 0;<br>  padding-bottom: 56.25%;<br>  position: relative;<br>}</pre><pre>.aspect-ratio__inner-wrapper {<br>  position: absolute;<br>  top: 0;<br>  right: 0;<br>  bottom: 0;<br>  left: 0;<br>}</pre><pre>.youtube-video {<br>  width: 100%;<br>  height: 100%;<br>}</pre><pre>&lt;!-- page.html --&gt;</pre><pre>&lt;div class=&quot;aspect-ratio--16x9&quot;&gt;<br>  &lt;div class=&quot;aspect-ratio__inner-wrapper&quot;&gt;<br>    &lt;iframe class=&quot;youtube-video&quot; src=&quot;https://youtube.com/...&quot;&gt;&lt;/iframe&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><h4>Doing it the React way</h4><p>Since I need to solve this problem frequently on <a href="https://helloclue.com/">Clue’s website</a>, I didn’t want to have to create two &lt;div&gt;s and assign their classes manually each time I needed to enforce an aspect ratio on an element. Since we use <a href="https://www.styled-components.com/">styled-components</a> as our CSS-in-JS solution, I was able to easily create dynamic CSS classes containing the desired aspect ratio. So I decided to create an &lt;AspectRatio /&gt; component to solve this for me:</p><pre>// AspectRatio.tsx</pre><pre>import * as React from &quot;react&quot;<br>import * as Styles from &quot;./AspectRatio.styles&quot;</pre><pre>interface Props {<br>  children?: any</pre><pre>  /**<br>   * The width divided by the height. This ratio can be passed in<br>   * using JavaScript division syntax. So, to get a 16:9 ratio, <br>   * simply pass `ratio={16/9}`.<br>   */<br>  ratio: number<br>}</pre><pre>const AspectRatio = ({ children, ratio }: Props) =&gt; (<br>  &lt;Styles.OuterWrapper ratio={ratio}&gt;<br>    &lt;Styles.InnerWrapper&gt;<br>      {children}<br>    &lt;/Styles.InnerWrapper&gt;<br>  &lt;/Styles.OuterWrapper&gt;<br>)</pre><pre>export default AspectRatio<br></pre><pre>// AspectRatio.styles.ts</pre><pre>import styled, { StyledFunction } from &quot;styled-components&quot;</pre><pre>const outerWrapper: StyledFunction&lt;{ ratio: number}&gt; = styled.div<br>export const OuterWrapper = outerWrapper`<br>  position: relative;<br>  width: 100%;<br>  height: 0;</pre><pre>  /**<br>   * For human readability, the ratio is expressed as<br>   * width / height, so we need to invert it.<br>   */<br>  padding-bottom: ${props =&gt; (1 / props.ratio) * 100}%;<br>`</pre><pre>export const InnerWrapper = styled.div`<br>  position: absolute;<br>  top: 0;<br>  right: 0;<br>  bottom: 0;<br>  left: 0;<br>`</pre><p>This component abstracts away all the complexity of the CSS classes we discussed earlier. It also exposes a nice-to-use prop, ratio, which can be passed in as a simple JavaScript division expression—e.g., &lt;AspectRatio ratio={16 / 9} /&gt;.</p><p>Let’s demonstrate with an example. Going back to the YouTube example, let’s create a &lt;YouTube /&gt; component that renders videos with a 16:9 aspect ratio:</p><pre>// YouTube.tsx</pre><pre>import * as React from &quot;react&quot;<br>import styled from &quot;styled-components&quot;<br>import AspectRatio from &quot;./AspectRatio&quot;</pre><pre>const ResponsiveIframe = styled.iframe`<br>  width: 100%;<br>  height: 100%;<br>`</pre><pre>interface Props {<br>  id: string<br>}</pre><pre>const YouTube = ({ id }: Props) =&gt; (<br>  &lt;AspectRatio ratio={16 / 9}&gt;<br>    &lt;ResponsiveIframe src={`<a href="https://www.youtube.com/embed/W7l1lKmCk4w">https://www.youtube.com/embed/</a>${id}`} /&gt;<br>  &lt;/AspectRatio&gt;<br>)</pre><pre>export default YouTube</pre><p>There you have it! A YouTube video that will scale to any size while maintaining a 16:9 aspect ratio.</p><p>¹ Thanks to <a href="https://stackoverflow.com/a/10441480/974981">this StackOverflow post</a> for finding the W3 spec on using percentages in padding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27a13241c3d4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleeding-edge/enforcing-an-aspect-ratio-on-an-html-element-in-react-and-css-27a13241c3d4">Keep it contained!</a> was originally published in <a href="https://medium.com/bleeding-edge">Bleeding Edge</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Screenshot testing with React and Storybook]]></title>
            <link>https://medium.com/bleeding-edge/screenshot-testing-with-react-and-storybook-19ab7e49ec92?source=rss-786d54738d11------2</link>
            <guid isPermaLink="false">https://medium.com/p/19ab7e49ec92</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[visual-regression-testing]]></category>
            <category><![CDATA[screenshot-testing]]></category>
            <category><![CDATA[storybook]]></category>
            <dc:creator><![CDATA[Jesse Pinho]]></dc:creator>
            <pubDate>Mon, 19 Mar 2018 05:45:20 GMT</pubDate>
            <atom:updated>2018-11-15T16:49:56.308Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Visual regression testing for fun, profit, and peace of mind</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TdvypkumWOFXNmtDs0WPMw@2x.png" /><figcaption>Illustration by Marta Pucci</figcaption></figure><p>A friend of mine recently related a scary story about the lack of automated visual regression testing where he works—a huge international tech firm that you’ve heard of and probably use. He’d added a CSS class to an element to hide it from the user. Unbeknownst to him, and despite using <a href="http://getbem.com/naming/">BEM-style naming</a> for CSS classes, this class name was already being used for an important checkbox in the user settings screen of his company’s web app. The result? Users could no longer change the setting represented by the checkbox, because it was invisible!</p><p>I asked him why that hadn’t been caught by automated tests. He explained that, although they did have end-to-end tests in place that went through the UI and tested its functionality, the tests didn’t catch the bug. Selenium was still able to check the original checkbox via its selector, so its visibility had no effect on the outcome of the test. The only way this could have been caught is via visual regression testing — or, as it is sometimes called, screenshot testing.</p><h4>💅 Switching to styled-components</h4><p>I recalled this story recently while working on a sizable project at Clue: converting all of our “native” CSS to use <a href="https://www.styled-components.com/">styled-components</a>. The new <a href="http://helloclue.com/">helloclue.com</a> website consists of dozens of components. An article page, for example, contains at least ten different React components, all of which have accompanying CSS files. Converting all of this CSS to styled-components means there’s an enormous risk of bugs exactly like the one my friend experienced. So before the project began, I investigated setting up screenshot testing for the site.</p><h4>📕 Enter Storybook</h4><p>(Note: if you’re already familiar with Storybook and <a href="https://www.npmjs.com/package/@storybook/react">@storybook/react</a>, feel free to skip to the next section.)</p><p>We use <a href="https://storybook.js.org/">Storybook</a> when developing simple <a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">presentational components</a>. This way, we can test them in every possible state, without having to reproduce all the logic and so forth required to get them to that state.</p><p>For example, on <a href="https://helloclue.com/authors/ida-tin">our author pages</a> (the AuthorPage component), there are four possible states:</p><ul><li>Both the author and the author’s articles are loading.</li><li>The author is loaded, but the articles are still loading.</li><li>The articles are loaded, but the author is still loading.</li><li>Both the author and the articles are loaded.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ghjNhbb9qx2rbftAuxaDUQ.png" /><figcaption>Loading-state placeholder elements on the author page in Storybook</figcaption></figure><p>The loading states are reflected in the UI via placeholder elements. The problem is, how do I make sure these elements look right? Using our office’s speedy internet connection, I only get a split second to check the loading state of the author page before the placeholders are replaced with real content.</p><p>That’s where Storybook comes in. With Storybook, you can render a component in the specific state you want to test it in, and keep it in that state for as long as you need<a href="#e671">¹</a>:</p><pre>// stories/AuthorPage.tsx<br>// Note that the code samples in this article are written in TypeScript.</pre><pre>import { storiesOf } from &quot;<a href="http://twitter.com/storybook/react">@storybook/react</a>&quot;<br>import AuthorPage from &quot;../components/AuthorPage/AuthorPage&quot;</pre><pre>storiesOf(&quot;AuthorPage&quot;, module)<br>  .add(&quot;loading&quot;, () =&gt; (<br>    &lt;AuthorPage<br>      isLoadingArticles={true}<br>      isLoadingAuthor={true}<br>    /&gt;<br>  ))</pre><p>In the example above, I’ve created a “story” for the author page in which both the articles and the authors are still loading. I can then run yarn run storybook (or npm run storybook), and it starts a Storybook server where I can view the AuthorPage component in its loading state. (Of course, I created additional stories for each of the other states, as well.)</p><p>While viewing the component, I can use Chrome Dev Tools to inspect the elements on the page, debug UI issues, and generally have a stable environment in which to develop the loading state of the component.</p><h4>📸 But what about screenshots?</h4><p>Since each component can be isolated and locked into a specific state in Storybook, and I wanted to screenshot every possible state of many of the site’s components, our Storybook setup seemed like a great place to do screenshot testing.</p><p>A bit of searching turned up an excellent library called <a href="https://github.com/tsuyoshiwada/storybook-chrome-screenshot">storybook-chrome-screenshot</a>, a Storybook <a href="https://storybook.js.org/addons/introduction/">addon</a>. Using Storybook Chrome Screenshot, I can add a <a href="https://storybook.js.org/addons/introduction/#1-decorators">decorator</a> to my Storybook stories:</p><pre>// stories/AuthorPage.tsx</pre><pre><strong>import { initScreenshot, withScreenshot } from &quot;storybook-chrome-screenshot/lib&quot;<br></strong>import { <strong>addDecorator,</strong> storiesOf } from &quot;<a href="http://twitter.com/storybook/react">@storybook/react</a>&quot;</pre><pre>import AuthorPage from &quot;../components/AuthorPage/AuthorPage&quot;</pre><pre><strong>addDecorator(initScreenshot())</strong></pre><pre>storiesOf(&quot;AuthorPage&quot;, module)<br>  .add(&quot;loading&quot;, <strong>withScreenshot()(</strong>() =&gt; (<br>    &lt;AuthorPage<br>      isLoadingArticles={true}<br>      isLoadingAuthor={true}<br>    /&gt;<br>  )<strong>)</strong>)</pre><p>When I run storybook-chrome-screenshot -p 9001 -c .storybook, a Storybook server is once again spun up. But this time, the Storybook Chrome Screenshot addon goes through each story that I’ve added the withScreenshot decorator to and takes a screenshot of it. (The decorator can also be added to the entire Storybook setup to automatically screenshot every story.<a href="#3a50">²</a>)</p><p>I can then add the storybook-chrome-screenshot command to the scripts key in my package.json, and automatically run it as a part of my CI process.</p><h4>🔬 Comparing screenshots: before and after</h4><p>OK, so I have screenshots of every component in the site in every possible state. But the whole point of taking screenshots is to compare them against master, to make sure nothing unintentionally changed.</p><p>That’s where <a href="https://reg-viz.github.io/reg-suit/">reg-suit</a> comes in. It’s an NPM package that does the actual work of pixel-by-pixel visual regression testing, and then generates an HTML report of the results.</p><p>First, I created regconfig.json in our app’s root directory (with a few non-JSON compliant comments added for your benefit):</p><pre>{<br>  &quot;core&quot;: {<br>    // The directory where storybook-chrome-screenshot dumps its screenshots, which reg-suit will use to compare against screenshots from master.<br>    &quot;actualDir&quot;: &quot;__screenshots__&quot;,<br>    // The directory where reg-suit will dump its HTML report, as well as images showing the visual differences if there are any.<br>    &quot;workingDir&quot;: &quot;__screenshots_tmp__&quot;,<br>    // This determines how forgiving reg-suit should be of differences between screenshots.<br>    &quot;threshold&quot;: 0,<br>    &quot;addIgnore&quot;: true,<br>    &quot;thresholdRate&quot;: 0,<br>    &quot;ximgdiff&quot;: {<br>      &quot;invocationType&quot;: &quot;client&quot;<br>    }<br>  },<br>  &quot;plugins&quot;: {<br>    // Use CI environment variables to determine which commits to compare screenshots from (in this case, master vs. HEAD).<br>    &quot;reg-simple-keygen-plugin&quot;: {<br>      &quot;expectedKey&quot;: &quot;${TARGET_GIT_COMMIT}&quot;,<br>      &quot;actualKey&quot;: &quot;${GIT_COMMIT}&quot;<br>    },<br>    // Notify GitHub of the results of the visual regression test.<br>    &quot;reg-notify-github-plugin&quot;: true,<br>    // Publish screenshots and test results to S3. Note that your CI will need to have AWS credentials configured for this to work.<br>    &quot;reg-publish-s3-plugin&quot;: {<br>      &quot;bucketName&quot;: &quot;&lt;BUCKET_NAME&gt;&quot;<br>    }<br>  }<br>}</pre><p>Given the above config, reg-suit stores the screenshots for each commit in an S3 bucket, under a directory named for the Git SHA of that commit. It also stores master screenshots in the same bucket under its own Git SHA directory. It then uses the reg-simple-keygen-plugin to identify those directories and run comparisons between the screenshots in each.</p><h4>🍱 Putting it all together</h4><p>I mentioned earlier that the impetus for screenshot testing of helloclue.com was the conversion of CSS files to styled-components. Once we got the setup described above working on helloclue.com, I started the conversion process.</p><p>What was so cool about having automated screenshot tests during this process was that I could make tons of changes to the styling of components without worrying too much about making mistakes, since I knew they’d be caught.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6_-junTHXgiTj91KrEcElw.png" /><figcaption>At right, how the loading author page <em>should</em> look on mobile. In the middle, how it actually looked in my PR. On the left, red highlights where changes were detected.</figcaption></figure><p>And of course, I did make mistakes! While converting the author page to styled-components, for example, I mistakenly left out the styling that made the placeholder for the author’s title appear as a gray bar. Since our visual regression tests are integrated with GitHub, reg-suit commented on my PR to inform me that some visual comparisons had failed<a href="#7f42">³</a>: they didn’t match what was on master. My visual regression testing was actually working!</p><h4>🎁 Fin</h4><p>There are two things that I hope are clear from this article. First, visual regression testing is important! It can help you catch major UI bugs that your end-to-end tests missed. And second, there are tools available to make this easy in React. It’s just a matter of putting them together to make them work for you!</p><p>I’d love to hear from you in the comments:</p><ol><li>Was there anything that could be made clearer about the setup steps in this article? I’m happy to explain in the comments, or even to edit this article to make it easier to understand.</li><li>What other tools, if any, are you using right now to do visual regression testing—particularly for React?</li><li>Any other thoughts or feedback?</li></ol><p>¹ Note that this works best with presentational components. Our presentational components simply take properties (such as isLoading) and output DOM. API calls, timeouts, etc. are all handled in container components. If you’d like to read more about separating business logic from presentation logic in React, I highly recommend <a href="https://medium.com/@dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0">Dan Abramov’s excellent article on the topic</a>.</p><p>² Our actual screenshot configuration (with comments added for your benefit) looks like this:</p><pre>// stories/index.tsx</pre><pre>import { addDecorator } from &quot;<a href="http://twitter.com/storybook/react">@storybook/react</a>&quot;<br>import { initScreenshot, withScreenshot } from &quot;storybook-chrome-screenshot/lib&quot;</pre><pre>addDecorator(initScreenshot())</pre><pre>// Rather than wrapping an individual story in `withScreenshot()(...)`, we&#39;ll add a decorator to the entire Storybook instance. This way, it&#39;ll take screenshots of every single story.<br>addDecorator(withScreenshot({<br>  // A one-second delay ensures that fonts load before screenshots are taken.<br>  delay: 1000,</pre><pre>  // We take screenshots at multiple viewport sizes, to ensure that various media queries are covered.<br>  viewport: [<br>    {<br>      width: 320,<br>      height: 568,<br>      isMobile: true,<br>      hasTouch: true,<br>    },<br>    {<br>      width: 768,<br>      height: 1024,<br>      isMobile: true,<br>      hasTouch: true,<br>    },<br>    {<br>      width: 1024,<br>      height: 768,<br>      isMobile: true,<br>      hasTouch: true,<br>    },<br>    {<br>      width: 1280,<br>      height: 800,<br>    },<br>    {<br>      width: 1440,<br>      height: 900,<br>    },<br>  ],<br>}))</pre><pre>import &quot;./AuthorPage.tsx&quot;<br>// [import all other stories...]</pre><p>³ It’s worth noting that we use a custom GitHub integration which doesn’t actually fail the build when screenshot comparisons “fail.” This is because changes to the UI are often intentional. Instead of failing the build, our GitHub integration simply comments on the PR with a count of how many screenshots changed from master to the PR. If that count is greater than 0, I can manually review the visual regression report and determine whether or not all the changes in the PR were intentional.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19ab7e49ec92" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleeding-edge/screenshot-testing-with-react-and-storybook-19ab7e49ec92">Screenshot testing with React and Storybook</a> was originally published in <a href="https://medium.com/bleeding-edge">Bleeding Edge</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Backstage: deploy individual branches with ease!]]></title>
            <link>https://medium.com/bleeding-edge/introducing-backstage-deploy-individual-branches-with-ease-efa301e5a533?source=rss-786d54738d11------2</link>
            <guid isPermaLink="false">https://medium.com/p/efa301e5a533</guid>
            <category><![CDATA[qa]]></category>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Jesse Pinho]]></dc:creator>
            <pubDate>Tue, 06 Mar 2018 14:33:40 GMT</pubDate>
            <atom:updated>2018-11-15T16:50:59.612Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eAoItwGdza24JWFpWyNPDQ@2x.png" /><figcaption>Illustration by Marta Pucci</figcaption></figure><p>You know what I miss from my PHP days? (…said no one, ever.)</p><p>No, but really: I used to host my Drupal projects on <a href="https://pantheon.io/">Pantheon</a>¹, and they had a feature with which you could easily spin up a Drupal instance for a single Git branch.</p><h4>Who needs that?!</h4><p>It occurred to me recently how useful that setup would be here at Clue. I’m working on a team of two developers that’s responsible for the all-new <a href="https://reactjs.org/">React</a>-based, <a href="https://www.contentful.com/">Contentful</a>-powered <a href="https://helloclue.com/">helloclue.com</a>. Not long ago, I was working on the “welcome mat” at the top of each page that introduces first-time visitors to the site, while my teammate Omosola was working on a feature that enhances the excerpts of articles that you see on the home page.</p><p>We both needed our QA team to review the changes we’d made, but we only have one staging server, and it’s reserved for auto-deployments from the master branch. So to make our work available for testing, we both had to merge our changes to master and then send the staging link to our QA team for review.</p><p>But what if the welcome mat had a bug, or needed its text tweaked before it could be deployed to production? <strong>We’d have to delay deploying both features to production, since </strong><strong>master would be in a bad state.</strong></p><p>One way around this is to have a dedicated qa branch. We could both merge our work into qa, then deploy it to a dedicated QA server. But this entails a bit of overhead as well: the qa branch will often have fragments of old work that were merged in, which can cause merge conflicts. In order to avoid such conflicts, I’d need to reset the branch to what was on master. Before I could do that, though, I’d first need to check with Omosola to see whether she had unmerged features in qa that shouldn’t be removed.</p><p>These workflow problems can become endlessly frustrating, especially as a project and team grow in size. So I was prompted to reflect back on my PHP days, and the workflow I used at Pantheon.</p><h4>One solution: per-branch servers</h4><p>Using Pantheon, I was able to deploy a single branch, and it would create a server instance whose lifetime was limited to that of the branch. My QA team could then use that instance to test the changes I’d made, after which I’d merge my branch into master and remove the server instance. master would then be deployed to the app-wide “dev” instance, from where it could eventually be pushed to staging, and then production.</p><p>Having a separate server instance for each feature branch solved all of the aforementioned workflow complications: there were never merge conflicts, and I never stepped on teammates’ toes by accidentally blowing away their deployed feature on a shared server.</p><p>Since moving on to other software frameworks, though, I haven’t found a service with features comparable to Pantheon’s. Of course, deploying a new instance to Heroku is relatively easy, but there’s more overhead involved than simply git pushing my current branch to Heroku, since I need to set up an entirely new “dyno” to serve my new branch. Plus, free tier dynos go to sleep after thirty minutes; so if I send a link to someone on my QA team to view, and they only get to it a few hours later, chances are they’ll get pretty frustrated that they have to wait for slow load times to QA my code.</p><p>The closest solution I’ve found for front-end apps is <a href="https://zeit.co/now">Now</a> by ZEIT. But while Now does allow for easy one-off deploys, the URL changes each time, so I couldn’t provide my QA team with a dedicated URL for a branch. Furthermore, URLs are publicly accessible, and I have little control over the server until I start paying monthly fees.</p><p>In short, what I want doesn’t seem to exist yet: an open-source server that I can configure to my liking, which serves per-branch deploys of my front-end app via an easy-to-use command-line tool.</p><h4>Enter Backstage</h4><p>This seemed like an easy enough problem to solve with code, and I know how to code! 🤓 So I started working on a simple solution, inspired by tooling that <a href="https://twitter.com/deanmarano">Dean Marano</a> created for Groupon back when we were colleagues there. The goal was to have two complementary tools:</p><ol><li>A CLI program for deploying individual branches of my front-end app to a server.</li><li>A server that receives these deployments, and then serves them on request.</li></ol><p>To these ends, I created <a href="https://backstage.js.org/">Backstage</a>. The backstage-server library is dead simple: it returns an Express server instance with three routes:</p><ul><li>POST /__backstage/deploy for uploading a .tar.gz package of the app</li><li>GET /__backstage/go/:appName/:branchName for setting necessary cookies and then redirecting to the deployed package</li><li>GET /* for serving all deployed assets</li></ul><p>To use backstage-server, you simply import it into your main app file, configure it with a storage backend, and call .listen(&lt;port&gt;) on it:</p><pre>// your-app.js<br>const path = require(&#39;path&#39;)<br>const { backstage } = require(&#39;backstage-server&#39;)<br>const { fileSystem } = require(&#39;backstage-server/dist/storage-backends/file-system&#39;)</pre><pre>const fileDir = path.join(__dirname, &#39;../files&#39;)<br>const storageBackend = fileSystem(fileDir)</pre><pre>backstage({ storageBackend }).listen(3000)</pre><p>(Note: you can clone <a href="https://github.com/BackstageJS/backstage-example">backstage-example</a> for a fully functional example Backstage instance.)</p><p>I won’t bore you with all the details of how I implemented these features (if you’re interested, you can read the source code for both the <a href="https://github.com/BackstageJS/backstage-server">server</a> and the <a href="https://github.com/BackstageJS/backstage-cli">client</a>!). But the end result is that our workflow for testing new branches at Clue is much easier now!</p><pre>clue-website$ git checkout welcome-mat<br>clue-website$ backstage deploy<br>Your deploy can now be viewed at https://clue-backstage-instance/__backstage/go/clue-website/welcome-mat</pre><p>I can then paste that link into Slack for my colleagues to review before I merge my branch into master.</p><p>If Omosola is working on a separate branch that also needs QAing, she can do the same thing:</p><pre>clue-website$ git checkout article-excerpts<br>clue-website$ backstage deploy<br>Your deploy can now be viewed at https://clue-backstage-instance/__backstage/go/clue-website/article-excerpts</pre><p>Our feature branches can now be tested separately and merged independently of each other, thereby ensuring that our master branch can always be deployed.</p><h4>Coming up: MOAR FEATURES 🔨🗜🔧</h4><p>At the moment, Backstage is in alpha. It stores deployed packages locally on the machine running the server instance, and uses cookies to remember which app and branch to serve you.</p><p>There’s a lot more I’d like to do with it. For starters, I’d like to have the option of using subdomains rather than cookies to determine which app/branch to serve. For example, for a new-feature branch of the clue-website app, I’d like to be able to preview the branch at https://new-feature.clue-website.clue-backstage-instance/. This way, QA folks can have one tab open for each branch they want to test, which isn’t possible when cookies are used to determine which branch to serve.</p><p>Another feature I’ll be working on soon is basic HTTP authentication. At the moment, we just restrict access to our Clue Backstage instance via a whitelist of IP addresses. I’d like to be able to give our QA team a username and password they can use to access the server, so they can easily access it from any location, such as when they’re working from home.</p><p>These and other features and ideas are tracked via GitHub issues in the respective repos. If you have additional suggestions, bug reports, or just general feedback, open up a GitHub issue or shoot me a tweet at <a href="https://twitter.com/jessepinho">@jessepinho</a>!</p><p>¹ No affiliation, but 5/5 would recommend.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efa301e5a533" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bleeding-edge/introducing-backstage-deploy-individual-branches-with-ease-efa301e5a533">Introducing Backstage: deploy individual branches with ease!</a> was originally published in <a href="https://medium.com/bleeding-edge">Bleeding Edge</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>