<?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[Arnelle’s Blog - Medium]]></title>
        <description><![CDATA[web developer ❤ javascript and open source - Medium]]></description>
        <link>https://medium.com/arnelle-balane?source=rss----4f05a9847d8a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Arnelle’s Blog - Medium</title>
            <link>https://medium.com/arnelle-balane?source=rss----4f05a9847d8a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 17:48:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/arnelle-balane" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Async Clipboard API: Accessing the clipboard using JavaScript]]></title>
            <link>https://medium.com/arnelle-balane/async-clipboard-api-accessing-the-clipboard-using-javascript-f17902af7890?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/f17902af7890</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webapi]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Sun, 08 Sep 2019 08:32:14 GMT</pubDate>
            <atom:updated>2019-09-08T08:32:13.982Z</atom:updated>
            <content:encoded><![CDATA[<p>Accessing the user’s clipboard has not been the nicest thing to do for a long time. We had to use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand">document.execCommand</a> API to copy and paste text to and from the user&#39;s clipboard, which involves the following steps:</p><pre>// #1. Use an input element<br>const input = document.querySelector(&#39;input&#39;);<br><br>// #2. Set the input&#39;s value to the text we want to copy to clipboard<br>input.value = &#39;hello there!&#39;;<br><br>// #3. Highlight the input&#39;s value<br>input.select();<br><br>// #4. Copy the highlighted text<br>document.execCommand(&#39;copy&#39;);</pre><p>The input element can be dynamically created and removed during the process, or styled to not be visible to the user. During the times that I got to use this approach before, I always thought that it looks ugly and not very elegant. Fortunately, a new Web API is here to make this a lot easier!</p><h3>Async Clipboard API</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API">Async Clipboard API</a> provides Web apps with the ability to programmatically read from and write to the system clipboard easily. A few notes about the API:</p><ul><li>It can be accessed at navigator.clipboard</li><li>The site needs to be served over HTTPS or localhost</li><li>Only works when the page is the active browser tab</li></ul><p>Now let’s see how simple it actually is, compared to the old way of doing it.</p><h3>Writing to the clipboard</h3><pre>async function writeToClipboard(text) {<br>    try {<br>        await navigator.clipboard.writeText(text);<br>    } catch (error) {<br>        console.error(error);<br>    }<br>}</pre><p>This method returns a Promise, which we can wait to resolve by chaining a .then() or using async/ await. With that single, short line of code, we&#39;ve just written our text into the clipboard!</p><blockquote><strong>Note:</strong> In Firefox, the text gets written to the clipboard only when calling writeText() in response to a user gesture, otherwise it throws an exception. Chrome writes the text to the clipboard regardless of the user gesture. Both allows writing to the clipboard without having to request for permission.</blockquote><h3>Reading from the clipboard</h3><pre>async function readFromClipboard() {<br>    try {<br>        const text = await navigator.clipboard.readText();<br>        console.log(text);<br>    } catch (error) {<br>        console.error(error);<br>    }<br>}</pre><p>This method also returns a Promise, and is as straightforward as writing to the clipboard. The first time a site tries to read the contents of the clipboard, the browser prompts the user whether they want to allow the request or not:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*oCO-Y3Jy31SzWjiZ.jpg" /></figure><blockquote><strong>Note:</strong> In Chrome, permission to read the clipboard is automatically denied when the user has dismissed it several times (~3 times from my observation).</blockquote><blockquote><strong>Note:</strong> At the time of writing, Firefox (version 68) doesn’t support the readText() method yet, with the MDN docs stating that it is only supported in browser extensions.</blockquote><h3>Checking clipboard access permissions</h3><p>We can check if we have permission to access the clipboard using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Permissions">Permissions API</a>:</p><pre>await navigator.permissions.query({name: &#39;clipboard-read&#39;});<br>// or &#39;clipboard-write&#39; for permission to write<br><br>// sample result: {state: &#39;granted&#39;}</pre><p>We can use this result for example to display some UI letting the user know whether we have access to the clipboard or not.</p><h3>Clipboard Events</h3><p>Aside from allowing us to easily write to and read from the clipboard, the Async Clipboard API also gives us clipboard events. We can know when the user performs a clipboard-related action such as copy, cut, or paste by listening for the copy, cut, and paste events, respectively.</p><pre>document.addEventListener(&#39;copy&#39;, event =&gt; {});<br>document.addEventListener(&#39;cut&#39;, event =&gt; {});<br>document.addEventListener(&#39;paste&#39;, event =&gt; {});</pre><p>These events don’t fire when accessing the clipboard using the Async Clipboard API (i.e. through writeText() or readText()), but they do when calling their corresponding document.execCommand commands. Calling event.preventDefault() cancels the action and maintains the current state of the clipboard.</p><p>These events only fire when the action was performed on the page, and not when performed in other pages or apps.</p><p>The clipboard event objects have a clipboardData property which is a <a href="https://developer.mozilla.org/en-US/docs/Web/API/DataTransfer">DataTransfer</a> object. This allows us to overwrite the data that will be written to the clipboard, giving us the opportunity to write data in other formats, such as text/html:</p><pre>document.addEventListener(&#39;copy&#39;, event =&gt; {<br>    event.preventDefault();<br>    event.clipboardData.setData(&#39;text/plain&#39;, &#39;COPY ME!!!&#39;);<br>    event.clipboardData.setData(&#39;text/html&#39;, &#39;&lt;p&gt;COPY ME!!!&lt;/p&gt;&#39;);<br>});</pre><p>When doing this, we need to call event.preventDefault() so that our custom data is written to the clipboard instead of the original. For cut and paste events, we need to handle removing/inserting the content in the document ourselves.</p><h3>Image Support</h3><p>So far we’ve only seen the version of the Async Clipboard API which only supports reading/writing text, and it already looks cool! A recent addition to the API is support for images, making it easy to programatically read and write images to the clipboard!</p><blockquote><strong>Note:</strong> For the meantime, only PNG images are supported, but support for other image formats (and maybe files in general) will be added in the future.</blockquote><h3>Write an image to the clipboard</h3><p>Before we can write an image to the clipboard, we first need to get a <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">Blob</a> of the image. There are several ways to obtain an image blob:</p><ul><li>Ask the user to select the image using a file input</li><li>fetch() the image from the network as a blob (with response.blob())</li><li>Draw the image to a canvas and call canvas.toBlob()</li></ul><p>Once we have an image blob (let’s call it imageBlob), we need to create an instance of ClipboardItem containing our image Blob:</p><pre>new ClipboardItem({<br>    &#39;image/png&#39;: imageBlob<br>})</pre><p>The ClipboardItem constructor accepts an object whose keys are the MIME types and the values are the actual blobs themselves. We can provide multiple MIME type and blob pairs, giving different representations of the data using different types.</p><p>Now we can write our image to the clipboard using navigator.clipboard.write():</p><pre>async function writeToClipboard(imageBlob) {<br>    try {<br>        await navigator.clipboard.write([<br>            new ClipboardItem({<br>                &#39;image/png&#39;: imageBlob<br>            })<br>        ]);<br>    } catch (error) {<br>        console.error(error);<br>    }<br>}</pre><p>navigator.clipboard.write() accepts an array of ClipboardItem s, but at the time of writing only supports a single item. This will most likely change in the future.</p><h3>Reading an image from the clipboard</h3><p>Reading items (not just text) from the clipboard can be done using navigator.clipboard.read():</p><pre>async function readFromClipboard() {<br>    try {<br>        const items = await navigator.clipboard.read();<br>    } catch (error) {<br>        console.error(error);<br>    }<br>}</pre><p>It returns an array of ClipboardItem s that mirrors the contents of the system clipboard, although currently in Chrome it only returns the latest item in the clipboard.</p><p>We can loop over this array to get each item. We can get all available MIME types in a ClipboardItem through its items property, and get the actual blob data for a specific type using its asynchronous getType() method:</p><pre>for (let item of items) {<br>    console.log(item.types); // e.g. [&#39;image/png&#39;]<br><br>    for (let type of item.types) {<br>        const blob = await item.getType(type);<br>    }<br>}</pre><p>After we get the blob, we can now do anything we want with it. We can use the <a href="https://developer.mozilla.org/en-US/docs/Web/API/FileReader">FileReader API</a> to convert the blob to appropriate formats that we want:</p><pre>const reader = new FileReader();<br>reader.onload = () =&gt; {<br>    const data = reader.result;<br>    // e.g. &#39;data:image/png;base64,...&#39;<br>};<br><br>reader.readAsDataURL(blob);</pre><p>The Async Clipboard API’s write() and read() methods provide generic ways for accessing the clipboard. In fact, the writeText() and readText() methods discussed earlier are just convenience methods for them, and can otherwise be done using write()/ read() by using blobs with type text/plain.</p><pre>async function writeToClipboard(text) {<br>    try {<br>        await navigator.clipboard.write([<br>            new ClipboardItem({<br>                &#39;text/plain&#39;: new Blob([text], {type: &#39;text/plain&#39;})<br>            })<br>        ]);<br>    } catch (error) {<br>        console.error(error);<br>    }<br>}<br><br>async function readFromClipboard() {<br>    try {<br>        const items = await navigator.clipboard.read();<br>        for (let item of items) {<br>            const data = item.getType(&#39;text/plain&#39;);<br>            // convert `data` to string using FileReader API&#39;s<br>            // `.readAsText(data)` method<br>        }<br>    } catch (error) {<br>        console.error(error);<br>    }<br>}</pre><h3>Browser Support &amp; Feature Detection</h3><p>The Async Clipboard API with text support shipped in <strong>Chrome 66</strong> and <strong>FireFox 63</strong> (with readText() not yet available for Web apps). For PNG image support, only Chrome supports it at the time of writing, shipping it in <strong>Chrome 76</strong>. See this <a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API#Browser_compatibility">browser compatibility table</a> for more info.</p><p>We can take advantage of this API already on browsers that support it through feature detection, by checking if navigator.clipboard is present.</p><pre>if (navigator.clipboard) {<br>    // Safe to use Async Clipboard API!<br>} else {<br>    // Use document.execCommand() instead<br>}</pre><h3>Resources</h3><p>Thanks for reading this article, I hope you enjoyed it and learned something from it. Here are more resources to learn more about the Async Clipboard API:</p><ul><li><a href="https://www.w3.org/TR/clipboard-apis/">Clipboard API and events, W3C Working Draft</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Clipboard_API">Clipboard API on MDN</a></li><li><a href="https://developers.google.com/web/updates/2018/03/clipboardapi">Unblocking Clipboard Access</a></li><li><a href="https://developers.google.com/web/updates/2019/07/image-support-for-async-clipboard">Image Support for the Async Clipboard API</a></li></ul><p><em>Originally published at </em><a href="https://arnellebalane.com/blog/async-clipboard-api/"><em>https://arnellebalane.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f17902af7890" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/async-clipboard-api-accessing-the-clipboard-using-javascript-f17902af7890">Async Clipboard API: Accessing the clipboard using JavaScript</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing the T-Rex Runner game inside a Picture-in-Picture window]]></title>
            <link>https://medium.com/arnelle-balane/playing-the-t-rex-runner-game-inside-a-picture-in-picture-window-488a96854b4a?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/488a96854b4a</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[experiment]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 15:11:00 GMT</pubDate>
            <atom:updated>2023-02-12T05:36:58.028Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="T-Rex Runner game running inside a Picture-in-Picture window" src="https://cdn-images-1.medium.com/max/1000/0*yHV0M9cbLhu5c1we.jpg" /><figcaption>T-Rex Runner game running inside a Picture-in-Picture window.</figcaption></figure><p>The Picture-in-Picture API is a new Web platform API that allows websites to play videos in a little floating window that stays on top of other windows even when the browser is not visible, allowing us to continue watching these videos while we interact with other websites or applications.</p><p>The API is currently limited to video elements only. Fortunately, we can also create video streams from canvas elements. This means that we can draw anything on a canvas and have it appear on a Picture-in-Picture window. Experimenting with this eventually led me into trying to make Chrome’s offline T-Rex runner game playable inside a Picture-in-Picture window (<a href="https://pip-trex.arnelle.me/">click here</a> to play it now).</p><p><a href="https://twitter.com/arnellebalane/status/1134838128127012864">https://twitter.com/arnellebalane/status/1134838128127012864</a></p><h3>Get the game’s source code</h3><p>We can get the game’s source code from the <a href="https://chromium.googlesource.com/chromium/src/+/master/components/neterror/resources/">Chromium repository</a>. We copy the contents in that location, rename some of the files, and clean up the HTML to only contain this necessary markup inside the &lt;body&gt;:</p><pre>&lt;!-- This will contain the canvas element --&gt;<br>&lt;div class=&quot;interstitial-wrapper&quot;&gt;&lt;/div&gt;<br><br>&lt;!-- Game assets: sprits + audio --&gt;<br>&lt;div id=&quot;offline-resources&quot;&gt;<br>  &lt;img id=&quot;offline-resources-1x&quot; src=&quot;images/100-percent/100-offline-sprite.png&quot;&gt;<br>  &lt;img id=&quot;offline-resources-2x&quot; src=&quot;images/200-percent/200-offline-sprite.png&quot;&gt;<br><br>  &lt;div id=&quot;audio-resources&quot;&gt;<br>    &lt;audio id=&quot;offline-sound-press&quot; src=&quot;sounds/button-press.mp3&quot;&gt;&lt;/audio&gt;<br>    &lt;audio id=&quot;offline-sound-hit&quot; src=&quot;sounds/hit.mp3&quot;&gt;&lt;/audio&gt;<br>    &lt;audio id=&quot;offline-sound-reached&quot; src=&quot;sounds/score-reached.mp3&quot;&gt;&lt;/audio&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;<br><br>&lt;!-- The main game script --&gt;<br>&lt;script src=&quot;offline.js&quot;&gt;&lt;/script&gt;<br><br>&lt;!-- Initialize the canvas and the game. --&gt;<br>&lt;!-- Originally performed inside neterror.js --&gt;<br>&lt;script&gt;<br>  const runner = new Runner(&#39;.interstitial-wrapper&#39;);<br>&lt;/script&gt;</pre><p>This gives us an exact replica of the offline T-Rex runner game which we can already play with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/0*fXoiAmmq4tjZU-8i.png" /></figure><h3>Implement programmatic T-Rex jump</h3><p>The T-Rex jumps every time we press on the spacebar. Let’s add a way to programatically make our T-Rex jump without us having to actually press the spacebar.</p><p>Digging through the game’s code, we will find two methods on the runner object that handles the spacebar key:</p><ol><li><a href="https://chromium.googlesource.com/chromium/src/+/master/components/neterror/resources/offline.js#676">onKeyDown</a>, makes the T-Rex jump while the game is running.</li><li><a href="https://chromium.googlesource.com/chromium/src/+/master/components/neterror/resources/offline.js#727">onKeyUp</a>, restarts the game when the T-Rex crashed into an obstacle.</li></ol><p>Let’s write a method that calls either of these based on the state of the game, passing in a <em>dummy</em> keyboard event.</p><pre>function simulateSpacebar() {<br>  const keyboardEventOptions = {<br>    code: &#39;Space&#39;,<br>    keyCode: 32,<br>  };<br><br>  if (runner.crashed) {<br>    const event = new KeyboardEvent(&#39;keyup&#39;, keyboardEventOptions);<br>    runner.onKeyUp(event);<br>  } else {<br>    const event = new KeyboardEvent(&#39;keydown&#39;, keyboardEventOptions);<br>    runner.onKeyDown(event);<br>  }<br>}</pre><h3>Capture video stream of canvas contents</h3><p>Calling new Runner(&#39;...&#39;) creates a canvas element and inserts it into the page. We need to get a reference to that canvas element, and then capture its contents as a video stream:</p><pre>const canvas = document.querySelector(&#39;canvas&#39;);<br>const videoStream = canvas.captureStream();</pre><p>We then create a video element with the video stream as the source:</p><pre>const video = new Video();<br>video.srcObject = videoStream;<br><br>video.muted = true;<br>video.play();</pre><p>Here we’re also muting the video so we can autoplay it (see <a href="https://developers.google.com/web/updates/2017/09/autoplay-policy-changes">Chrome’s autoplay policy</a>).</p><h3>Show the Picture-in-Picture window</h3><p>When using new Web APIs like Picture-in-Picture, always feature-detect if they are available before trying to use them. This makes sure that our apps don’t break when the API is not available, and only progressively enhance the experience when it is available. For Picture-in-Picture, it can be done by checking the document.pictureInPictureEnabled property:</p><pre>const button = document.querySelector(&#39;button&#39;);<br><br>if (document.pictureInPictureEnabled) {<br><br>  // Picture-in-Picture is available!<br>  // Subsequent code snippets will be place inside this block.<br><br>} else {<br>  // Picture-in-Picture is not available. User can still play the game normally in the page.<br><br>  button.textContent = &#39;Picture-in-Picture is not available&#39;;<br>  button.disabled = true;<br>}</pre><p>We also add a &lt;button&gt; element to the page, which the user can click to<br> enter Picture-in-Picture. We want to give this control to our users, usually through a Picture-in-Picture icon in the UI, so that they can decide when they want to view our content in the Picture-in-Picture window.</p><p>Now to the fun part, let’s show our video stream in the Picture-in-Picture window when the button is clicked!</p><pre>button.addEventListener(&#39;click&#39;, async () =&gt; {<br>  simulateSpacebar();<br>  await video.requestPictureInPicture();<br>});</pre><p>The result looks like this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJxmrlG_ROAY%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJxmrlG_ROAY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJxmrlG_ROAY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c2a2056a22e51d189f3cf3b70fc48a5/href">https://medium.com/media/0c2a2056a22e51d189f3cf3b70fc48a5/href</a></iframe><h3>Implement game controls</h3><p>The Picture-in-Picture window can stay on top of other application windows, and in that case we won’t be able to press the spacebar key on the page to make the T-Rex jump, so we need another way to make it do that.</p><p><strong>Media Session API to the rescue!</strong></p><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/API/Media_Session_API">Media Session API</a> allows websites to customize media notifications, as well as define event handlers for playback controls (e.g. play, pause, etc.). We can make our T-Rex jump whenever we press the play/pause buttons on our keyboards (or other devices that can control media playback) by defining play and pause event handlers.</p><pre>navigator.mediaSession.setActionHandler(&#39;play&#39;, simulateSpacebar);<br>navigator.mediaSession.setActionHandler(&#39;pause&#39;, simulateSpacebar);</pre><p>The Picture-in-Picture API integrates well with the Media Session API. When we define the playback event handlers, the Picture-in-Picture window will also display their corresponding action buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/0*lj6SvElxSpziPglq.png" /></figure><h3>Let’s play!</h3><p>With all of those changes in place, we’ve now made the T-Rex Runner game<br> playable inside a Picture-in-Picture window, using our play/pause media buttons to make the T-Rex jump!</p><p>You can find the live demo of this project, as well as the complete source code, in the following links:</p><ul><li><a href="https://pip-trex.arnelle.dev/">https://pip-trex.arnelle.dev/</a></li><li><a href="https://github.com/arnellebalane/pip-trex">https://github.com/arnellebalane/pip-trex</a></li></ul><h3>Conclusion</h3><p>In this article we were able to use the Picture-in-Picture API and Media<br> Session API to build something silly. There are more serious and useful uses for these APIs- Youtube has <a href="https://twitter.com/arnellebalane/status/1118537633548759041">a hidden Picture-in-Picture button</a> in their player controls, and before I worked on this experiment, I also built a demo on <a href="https://twitter.com/arnellebalane/status/1134768178318303232">displaying audio visualization inside a Picture-in-Picture window</a> using the same techniques in this article.</p><p>If you’ve built / are currently working on something that uses these APIs, or see some really amazing uses of them in the wild, please share them with us in the comments, I’d love to hear about them!</p><h3>Resources</h3><ul><li><a href="https://blog.arnellebalane.com/the-picture-in-picture-api-30415372009f">The Picture-in-Picture API</a></li><li><a href="https://developers.google.com/web/updates/2018/10/watch-video-using-picture-in-picture">Watch video using Picture-in-Picture</a> by François Beaufort</li><li><a href="https://developers.google.com/web/updates/2017/02/media-session">Customize Media Notifications and Handle Playlists</a> (Media Session API) by François Beaufort</li></ul><p><em>Originally published at </em><a href="https://dev.to/arnellebalane/playing-the-t-rex-runner-game-inside-a-picture-in-picture-window-kpc"><em>https://dev.to</em></a><em> on July 22, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=488a96854b4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/playing-the-t-rex-runner-game-inside-a-picture-in-picture-window-488a96854b4a">Playing the T-Rex Runner game inside a Picture-in-Picture window</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a site navigation menu using React Hooks]]></title>
            <link>https://medium.com/arnelle-balane/building-a-site-navigation-menu-using-react-hooks-efc13d658353?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/efc13d658353</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Sun, 20 Jan 2019 13:23:22 GMT</pubDate>
            <atom:updated>2019-04-23T02:00:37.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7MqLqrumhawyGi8HPWX8Yg.jpeg" /></figure><p>I’m currently learning React, and since I learn better by building stuff, I decided to rebuild my personal website with it. It’s still a work in progress but there is one component which I found interesting to build: the site’s navigation menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*4AHKB02_rrQsvPFNsubevA.gif" /></figure><p>It’s just a simple menu, and I only have two requirements for it:</p><ol><li>The user needs to be able to toggle its state to open or close</li><li>It should close when the user navigates to a different page</li></ol><h3>Initial setup</h3><p>I initially built a static version of the site, composed of the top-level App component, a Header component, and a Menu component. The App component looks like this:</p><pre>// App.jsx</pre><pre>import Header from &#39;./Header.jsx&#39;;</pre><pre>function App(props) {<br>    const isMenuOpen = false;</pre><pre>    return (<br>        &lt;div&gt;<br>            &lt;Header isMenuOpen={isMenuOpen} /&gt;</pre><pre>            {/* Other stuff */}<br>        &lt;/div&gt;<br>    );<br>}</pre><p>As shown in the code snippet, the App component has an isMenuOpen variable which it passes to Header as the isMenuOpen prop. The Header in turn passes the same isMenuOpen prop to Menu. The value of this variable controls whether Menu should be shown or hidden.</p><h3>isMenuOpen component state</h3><p>Initially, isMenuOpen is just a variable whose value I manually change to update the UI. This is okay for the initial static version of the app, but I don’t really want that on the actual app. I want the component to keep track of this variable, modify its value in response to a user action (e.g. a click on the toggle menu button), and re-render the UI based on its new value.</p><p>To achieve that, I need to make isMenuOpen an actual state on the App component. Normally this would be done by converting App from a functional component into a class component. This is because functional components can’t have state while class components can. If I follow this approach, the App component will become:</p><pre>// App.jsx</pre><pre>class App extends React.Components {<br>    constructor(props) {<br>        super(props);<br>        this.state = {<br>            isMenuOpen: false<br>        };<br>        this.handleToggleMenu = this.handleToggleMenu.bind(this);<br>    }</pre><pre>    handleToggleMenu() {<br>        this.setState(state =&gt; ({<br>            isMenuOpen: !state.isMenuOpen<br>        }));<br>    }</pre><pre>    render() {<br>        return (<br>            &lt;div&gt;<br>                &lt;Header <br>                    isMenuOpen={this.state.isMenuOpen} <br>                    onToggleMenu={this.handleToggleMenu}<br>                /&gt;</pre><pre>                {/* Other stuff */}<br>            &lt;/div&gt;<br>        );<br>    }<br>}</pre><p>I would have done it this way, but then it just happened that I just recently read about <a href="https://reactjs.org/docs/hooks-intro.html">React Hooks</a> from the docs.</p><p>React Hooks gives us access to features such as states and lifecycle methods without having to use class components (in fact, they should only be used in functional components). It seemed like I had an opportunity to use React Hooks for my navigation menu so I decided to try it out.</p><h4>Make sure to use the right React version</h4><p>At the time of writing, React Hooks is still on preview, and is only available in <strong>React v16.8.0-alpha.0</strong>. I had to update the corresponding packages to use the right versions:</p><pre>npm install react@16.8.0-alpha.0 react-dom@16.8.0-alpha.0</pre><h4>Using the useState hook</h4><p>With the correct versions of react and react-dom installed, I can now start using React Hooks. Since I want to use states in my functional App component, I used React’s built-in <a href="https://reactjs.org/docs/hooks-state.html">useState</a> hook.</p><pre>import {useState} from react;</pre><p>Then used it to initialize the isMenuOpen state:</p><pre>function App(props) {<br>    const [isMenuOpen, setIsMenuOpen] = useState(false);<br>}</pre><p>The useState hook accepts one argument which is the initial value to set the state to, and returns an array of two things: the current state value and a function used to update the state value.</p><p>And just like that, I now have a reactive isMenuOpen state with just very minimal changes in the code. I was able to use state in my component while keeping it as a functional component. In fact, to me it still kinda looks like I’m just declaring the isMenuOpen variable from the static version of the component. The complete App component now looks like:</p><pre>// App.jsx</pre><pre>function App(props) {<br>    const [isMenuOpen, setIsMenuOpen] = useState(false);</pre><pre>    return (<br>        &lt;div className={style.wrapper}&gt;<br>            &lt;Header<br>                isMenuOpen={isMenuOpen}<br>                onToggleMenu={() =&gt; setIsMenuOpen(!isMenuOpen)}<br>            /&gt;</pre><pre>            {/* Other stuff */}<br>        &lt;/div&gt;<br>    );<br>}</pre><h3>Detecting page navigations</h3><p>At this point the navigation menu already opens and closes when clicking on the menu button inside the Header component. The next thing that I needed to do was to make sure to close it when a menu item gets clicked. Otherwise, the menu will continue covering the page even after navigating to the next page.</p><p>I am using React Router to route URLs to specific page components. To detect page navigations, I first needed access to the history object being used by React Router from the App component. This was achieved by wrapping App inside the withRouter higher-order component, which passed history as one of App’s props.</p><pre>// App.jsx</pre><pre>import {withRouter} from &#39;react-router-dom&#39;;</pre><pre>function App(props) {<br>    const history = props.history;</pre><pre>    // Other stuff<br>}</pre><pre>export default withRouter(App);</pre><p>The history object has a .listen() method which accepts a callback function that it will call every time the current location changes. Subscribing to these changes is usually done in the component’s componentDidMount lifecycle method (and unsubscribing in componentWillUnmount), which requires a class component and will make App look like this:</p><pre>class App extends React.Component {<br>    // constructor(props)<br>    // handleToggleMenu()</pre><pre>    componentDidMount() {<br>        this.unlisten = this.props.history.listen(() =&gt; {<br>            this.setState({<br>                isMenuOpen: false<br>            });<br>        });<br>    }</pre><pre>    componentWillUnmount() {<br>        this.unlisten();<br>    }</pre><pre>    // render()<br>}</pre><p>But again, I didn’t want to convert my App component into a class component. And also I just read that there is a built-in React Hook for doing exactly this pattern, so I decided to use it instead.</p><h4>Using the useEffect hook</h4><p>The pattern of registering something in a component’s componentDidMount and unregistering it in componentWillUnmount is apparently very common that it got abstracted into its own React Hook, the <a href="https://reactjs.org/docs/hooks-effect.html">useEffect</a> hook.</p><pre>import {useEffect} from &#39;react&#39;;</pre><p>The useEffect hook accepts a function containing code that will normally run inside the componentDidMount (and componentDidUpdate) lifecycle method; in my case, that would be code to listen to changes to the current history location and closing the menu when it does.</p><pre>function App(props) {<br>    useEffect(() =&gt; {<br>        props.history.listen(() =&gt; {<br>            setIsMenuOpen(false);<br>        });<br>    });</pre><pre>    // Other stuff<br>}</pre><p>We can also return a function containing code that will normally run inside the componentWillUnmount lifecycle method; in my case, stop listening for changes to the current history location. Calling history.listen() already returns such function so I can just return it right away.</p><pre>function App(props) {<br>    useEffect(() =&gt; {<br>        return props.history.listen(() =&gt; {<br>            setIsMenuOpen(false);<br>        });<br>    });</pre><pre>    // Other stuff<br>}</pre><p>And these are all the changes needed to make the App component close the navigation menu on page navigations. No need to convert it to a class component and setup lifecycle methods. All the related code are located in close proximity to each other instead of being separated in different places in the component code.</p><h3>Final App component</h3><p>After applying all these changes, the App component, complete with the stateful navigation menu which closes on page navigation, now looks like this:</p><pre>import {useState, useEffect} from &#39;react&#39;;<br>import {withRouter} from &#39;react-router-dom&#39;;<br>import Header from &#39;./Header.jsx&#39;;</pre><pre>function App(props) {<br>    const [isMenuOpen, setIsMenuOpen] = useState(false);</pre><pre>    useEffect(() =&gt; props.history.listen(() =&gt; {<br>        setIsMenuOpen(false);<br>    }));</pre><pre>    return (<br>        &lt;div&gt;<br>            &lt;Header<br>                isMenuOpen={isMenuOpen}<br>                onToggleMenu={() =&gt; setIsMenuOpen(!isMenuOpen)}<br>            /&gt;</pre><pre>            {/* Other stuff */}<br>        &lt;/div&gt;<br>    );<br>}</pre><pre>export default withRouter(App);</pre><p>I could have gone even further by making a generic React Hook for such functionality, in case I need to use it again somewhere else. We can use these built-in React Hooks to build more hooks. But I guess I’ll just reserve that for another day when I actually need to.</p><h3>Summary</h3><p>In this article I walked through how I made my site’s navigation menu using React Hooks. We used the built-in useState hook to keep track of the menu’s open/close state, and the built-in useEffect hook to listen to changes in the current location (and cleanup after when the component is going to be removed). After applying the changes, we end up with a functional component that has its own state.</p><p>This is the first time that I’ve used React Hooks on something and so far I totally enjoyed the experience. I think the code is more readable and easier to figure out compared to using class components with lots of lifecycle methods, since I didn’t need to look in multiple separate places to understand a component’s functionality. Instead, all the related functionality are defined in one place. Also, we are able to build custom, more complex hooks out of the built-in ones if we want to, and reuse these functionalities all over our application. I’m really looking forward to using React Hooks more in the future.</p><h3>Resources</h3><ul><li><a href="https://reactjs.org/docs/hooks-intro.html">Introducing Hooks</a></li><li>Toptal’s <a href="https://www.toptal.com/react/react-tutorial-pt2">React Tutorial: Components, Hooks, and Performance</a></li></ul><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. I also write other articles and make demos about cool Web stuff. You can check them out on <a href="http://blog.arnellebalane.com/">my blog</a> and on <a href="https://github.com/arnellebalane/">my GitHub profile</a>. Have a great day! 🦔</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efc13d658353" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/building-a-site-navigation-menu-using-react-hooks-efc13d658353">Building a site navigation menu using React Hooks</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using lazysizes to lazyload images on the Web]]></title>
            <link>https://medium.com/arnelle-balane/using-lazysizes-to-lazyload-images-on-the-web-a0fbcbf58975?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/a0fbcbf58975</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[lazy-loading]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 03:00:10 GMT</pubDate>
            <atom:updated>2019-01-13T03:36:12.608Z</atom:updated>
            <content:encoded><![CDATA[<p>Images constitute a large portion of the page weights of a lot of Web pages. They make our pages more enjoyable to look at, but can also hurt our page load times especially when they have large file sizes or when there are a lot of them on the page, not to mention that they can unnecessarily consume our users’ bandwidths. One way to deal with these concerns is to <strong>lazyload</strong> our images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYfHy9wpdgDdvS2s8egveQ.jpeg" /></figure><p>Lazyloading means that we load our images only when they are going to be visible in the page. For example, an image located somewhere near the end of a long article doesn’t need to be loaded until the user actually scrolls it into view.</p><p>We can implement our own lazyloading functionality with JavaScript using some modern Web APIs (such as the <a href="https://blog.arnellebalane.com/the-intersection-observer-api-d441be0b088d">Intersection Observer API</a>), or use an image lazyloading library like <a href="https://github.com/aFarkas/lazysizes"><strong>lazysizes</strong></a> by <a href="https://github.com/aFarkas">aFarkas</a>. What I like about this library is that it is very easy to start using it, and is performant while being packed with tons of amazing features.</p><h3>Example Web page</h3><p>Let’s create an example Web page with an image which we want to lazyload later on with lazysizes. Our example page is going to have the following markup:</p><pre>&lt;p&gt;Lorem ipsum dolor sit amet...&lt;/p&gt;<br>&lt;!-- 9 more lorem ipsum paragraphs --&gt;</pre><pre>&lt;img src=&quot;image.jpg&quot; alt=&quot;Sample Image&quot;&gt;</pre><pre>&lt;!-- 3 more lorem ipsum paragraphs --&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Wzn_7SBbtudeF_lxyyk5XQ.gif" /><figcaption>Example Web page with an image</figcaption></figure><p>Notice from DevTools’ Network tab that the image has already been loaded since the page has loaded. Let’s try to change that to only load it when it is about to scroll into view using lazysizes.</p><h3>Basic usage</h3><p>To start using lazysizes, the first thing we need to do is load the lazysizes JavaScript file:</p><pre>&lt;script src=&quot;<a href="http://afarkas.github.io/lazysizes/lazysizes.min.js">http://afarkas.github.io/lazysizes/lazysizes.min.js</a>&quot;&gt;&lt;/script&gt;</pre><p>It can also be installed via npm (npm install lazysizes) or bower (bower install lazysizes).</p><p>Second, we modify the img tags that we want to lazyload to:</p><ol><li>Use data-src attribute instead of src, and</li><li>Add lazyload as one of its classes</li></ol><pre>&lt;!-- Before: --&gt;<br>&lt;img src=&quot;image.jpg&quot; alt=&quot;Sample Image&quot;&gt;</pre><pre>&lt;!-- After: --&gt;<br>&lt;img data-src=&quot;image.jpg&quot; class=&quot;lazyload&quot; alt=&quot;Sample Image&quot;&gt;</pre><p>And the result?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9--uGId_DZNPZ5SKTZzGlA.gif" /><figcaption>Basic lazysizes usage result</figcaption></figure><p>Notice from DevTools’ Network tab how the image is only loaded once it’s about to be scrolled into view. Awesome!</p><h3>Lazyload responsive images</h3><p>We can serve responsive images on the Web using the srcset attribute on the img element or using the picture element. This allows us to serve an appropriately-sized image to our users depending on their screen sizes.</p><p>One really cool feature of lazysizes that I really like is its ability to lazyload these responsive images without any additional configuration. All we have to do is to replace the srcset attribute with data-srcset.</p><pre>&lt;!-- Before: --&gt;<br>&lt;img<br>    srcset=&quot;<br>        image-100.jpg 100w,<br>        image-300.jpg 300w&quot;<br>    src=&quot;image.jpg&quot;<br>    alt=&quot;Responsive Image&quot;<br>&gt;</pre><pre>&lt;-- After: --&gt;<br>&lt;img <br>    data-srcset=&quot;<br>        image-100.jpg 100w,<br>        image-300.jpg 300w&quot;<br>    data-src=&quot;image.jpg&quot;<br>    alt=&quot;Responsive Image&quot;<br>&gt;</pre><h3>Use a low-quality image placeholder</h3><p>One potential concern with our lazyloaded images at this point is that when the user’s network connection is slow, it will still take a long time for the images to show up, leaving us with a blank space in our page.</p><p>We can address this by displaying a small-sized, low-quality image as a placeholder until the actual image finishes loading. Because of its very small size, this placeholder image will load very quickly, giving the user an idea of what the actual image is going to look like. To do that, we add the placeholder image as the src attribute of the img tag.</p><pre>&lt;img <br>    data-srcset=&quot;<br>        image-100.jpg 100w,<br>        image-300.jpg 300w&quot;<br>    data-src=&quot;image.jpg&quot;<br>    src=&quot;image-lqip.jpg&quot;  &lt;!-- &lt;= e.g. a 20px-width image --&gt;<br>    width=&quot;300&quot;<br>    height=&quot;200&quot;<br>    alt=&quot;Responsive Image&quot;<br>&gt;</pre><p>Adding the width and height attributes makes the small-sized image take up the space of the actual image. This can also be done via CSS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*qKDZj_TlBQrMI88rkCc3eA.gif" /><figcaption>Lazysizes, using a low-quality image placeholder</figcaption></figure><h3>Summary</h3><p>So far we’ve looked at how to use lazysizes to lazyload images for basic use cases. With the changes we’ve made, users will get to download the images in our page only when necessary. As a result, our page loads faster since it doesn’t need to wait for the large image to finish loading. We also keep the users from unnecessarily consuming their bandwidths on images that they’re not going to see yet.</p><p>However, we’ve only scratched the surface of what lazysizes offers. It offers much more features and different configurations and other patterns of how it can be used for more advanced use cases, so definitely check out the library’s <a href="https://github.com/aFarkas/lazysizes">documentation</a> for those, and let’s all make our Web experiences better together by lazyloading our images.</p><p>Thanks for reading this article! Feel free to leave your comments and let me know what you think. I also write other articles and make demos about cool Web stuff. You can check them out on <a href="http://blog.arnellebalane.com/">my blog</a> and on <a href="https://github.com/arnellebalane/">my GitHub profile</a>. Have a great day! 🦔</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0fbcbf58975" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/using-lazysizes-to-lazyload-images-on-the-web-a0fbcbf58975">Using lazysizes to lazyload images on the Web</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using the Ambient Light Sensor API to add brightness-sensitive dark mode to my website]]></title>
            <link>https://medium.com/arnelle-balane/using-the-ambient-light-sensor-api-to-add-brightness-sensitive-dark-mode-to-my-website-82223e754630?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/82223e754630</guid>
            <category><![CDATA[generic-sensors-api]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ambient-light-sensor]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Sat, 09 Jun 2018 06:54:15 GMT</pubDate>
            <atom:updated>2018-10-09T03:36:00.894Z</atom:updated>
            <content:encoded><![CDATA[<p>I just added a new enhancement to my website: <strong>dark mode</strong>! Because, you know, you might be viewing it at night and I don’t want you to get blinded by the brightness of the screen ;)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gqHYTP4k1ek_HEh2Py2aXw.png" /></figure><p>This article will quickly walk through how I implemented dark mode, and how I made it even cooler by automatically toggling on/off depending on the brightness of the environment.</p><h3>CSS Custom Properties</h3><p>I am using CSS Custom Properties (also referred to as CSS variables) to define the colors that I am using throughout my site. This allows me to place all color definitions in one place, and easily reuse them in other places in my stylesheet.</p><pre>html {<br>  --primary-color: #ffeb3b;<br>  --border-color: var(--primary-color);<br>  --text-color: #333;<br>  --background-color: #fff;<br>}</pre><p>To add dark mode styles, all I have to do is change the values of these custom properties, and the changes will be applied in all the other places that are using them. In my case, I add the dark mode styles when the &lt;html&gt; element has the class dark.</p><pre>html.dark {<br>  --border-color: #ccc;<br>  --text-color: #ccc;<br>  --background-color: #181818;<br>}</pre><p>There are also other minor adjustments needed, like making some links stand out in dark mode by making them use --primary-color instead of the default --text-color .</p><h3>Toggling Dark Mode</h3><p>With the styles in place, I then enable it by adding the dark class to the &lt;html&gt; element. But I want that class to be added dynamically, so I add a button on the page which can be clicked to manually toggle dark mode.</p><pre>&lt;button class=&quot;toggle-theme&quot;&gt;&lt;/button&gt;</pre><pre>// JS<br>const html = document.querySelector(&#39;html&#39;);<br>const button = document.querySelector(&#39;button&#39;);</pre><pre>button.addEventListener(&#39;click&#39;, () =&gt; {<br>  html.classList.toggle(&#39;dark&#39;);<br>});</pre><h3>Using Ambient Light Sensor</h3><p>Now time for the cool part! I then make the dark mode theme automatically enable itself when the surroundings is dark, and then disable when it gets bright. To achieve that, I used the Ambient Light Sensor API.</p><p>A lot of devices already have light sensors built-in on them, and the good news is that readings from these sensors can now be accessed on the Web! To do so, we create an instance of AmbientLightSensor.</p><pre>const sensor = new AmbientLightSensor();<br>sensor.start();</pre><p>Calling the sensor’s start() method tells it to start reporting changes on the brightness reading. We can also call stop() to make it stop.</p><h4>Sensor Events</h4><p>The sensor fires events in order to let us know whether it has been activated, encountered an error, or has new sensor readings. We can listen for these events and respond accordingly.</p><pre>sensor.addEventListener(&#39;activate&#39;, () ={<br>  console.log(&#39;Ready to report readings&#39;);<br>});</pre><pre>sensor.addEventListener(&#39;error&#39;, error =&gt; {<br>  console.error(error);<br>});</pre><p>When there are changes to the sensor reading, the sensor fires the reading event. We can obtain the actual ambient light sensor reading from sensor.illuminance.</p><pre>sensor.addEventListener(&#39;reading&#39;, () =&gt; {<br>  const illuminance = sensor.illuminance;<br>};</pre><h4>Illuminance</h4><p>The illuminance is an integer value representing the current light level in the surrounding environment. <a href="https://en.wikipedia.org/wiki/Lux#Illuminance">This Wikipedia table</a> shows different example illuminance values under different conditions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/1*KrQ_CgeCW7lCXjfd6sC3ug.jpeg" /><figcaption><a href="https://en.wikipedia.org/wiki/Lux#Illuminance">https://en.wikipedia.org/wiki/Lux#Illuminance</a></figcaption></figure><p>Using the table as a guide, we can determine an appropriate illuminance threshold to differentiate light and dark (in my case I picked 25), and use that value to toggle dark mode accordingly. However, we will give this value some allowance, because someone in a room with ~25 illuminance will likely experience constant flickering as the page switches between the light and dark themes. In my case I enable dark mode when illuminance is less then 20, and disable it when illuminance is greater than 30.</p><pre>sensor.addEventListener(&#39;reading&#39;, () =&gt; {<br>  const illuminance = sensor.illuminance;</pre><pre>  if (illuminance &lt; 20) {<br>    html.classList.add(&#39;dark&#39;);<br>  } else if (illluminance &gt; 30) {<br>    html.classList.remove(&#39;dark&#39;);<br>  }<br>});</pre><p>And just like that, dark mode will now automatically enable when the surrounding is dark, and disable when it gets bright!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*cjxgmtRKAnL3kWLFAoGahw.gif" /><figcaption>yeaaaahhhh 🙌</figcaption></figure><h4>Feature Detection</h4><p>This feature is really cool, unfortunately <a href="https://caniuse.com/#feat=ambient-light">browser support</a> is not yet very good. Edge and Firefox supports an outdated version of the API, and it is behind a browser flag in Chrome. You can enable it in Chrome by going to chrome://flags and enabling <strong>Generic Sensor Extra Classes</strong>.</p><p>It is also good to check first if the API is available on the browser before trying to use it. This can be done by checking if the AmbientLightSensor constructor is present on the window object.</p><pre>if (window.AmbientLightSensor) {<br>  // Supported, yay!<br>}</pre><h3>Conclusion</h3><p>That’s how I added dark mode to my website using the Ambient Light Sensor API. This API is just one of the many sensor-related APIs that are available on the Web, and I’m excited to see how other people use these APIs on their applications as well.</p><h3>Resources</h3><ul><li><a href="https://www.w3.org/TR/ambient-light/">Ambient Light Sensor, W3C Candidate Recommendation</a></li></ul><p>Thanks for reading this article! I’m a Web Developer from Cebu, Philippines. I also write articles and make demos about cool Web stuff. You can check them out on <a href="http://blog.arnellebalane.com/">my blog</a> and on <a href="https://github.com/arnellebalane/">my GitHub profile</a>. Have a great day! 🦔</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82223e754630" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/using-the-ambient-light-sensor-api-to-add-brightness-sensitive-dark-mode-to-my-website-82223e754630">Using the Ambient Light Sensor API to add brightness-sensitive dark mode to my website</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Picture-in-Picture API]]></title>
            <link>https://medium.com/arnelle-balane/the-picture-in-picture-api-30415372009f?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/30415372009f</guid>
            <category><![CDATA[picture-in-picture-api]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Thu, 07 Jun 2018 01:28:40 GMT</pubDate>
            <atom:updated>2023-02-12T05:38:20.887Z</atom:updated>
            <content:encoded><![CDATA[<p>The Picture-in-Picture API (PiP) is a new experimental Web Platform API that allows Web pages to play a video in a little window that stays on top of other windows. This feature is valuable for video sites that want their users to continue watching their videos while doing something else, for example watch a coding tutorial video while also coding along in their text editors, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_wBJDuvlpRdvnx1G0cWog.png" /><figcaption>Picture-in-Picture in action</figcaption></figure><p>Picture-in-Picture is currently behind browser flags (like, 3 of them) in Chrome 69, but we should be able to play around with them now by getting the latest Chrome version and enabling these flags.</p><p>This article will walk you through getting started with Picture-in-Picture to make your videos stay on top of other windows too. You can also check out the <a href="https://github.com/arnellebalane/picture-in-picture-video">GitHub repository</a> and <a href="https://picture-in-picture-video.arnelle.dev/">live demo</a> straight away if you want.</p><h3>Enable Picture-in-Picture</h3><p>Before we get into the code, let’s first make sure that we can view our results on the browser properly by enabling the required Chrome browser flags. Go to chrome://flags on your Chrome browser and enable the following:</p><ul><li>Experimental Web Platform features</li><li>Enable Picture-in-Picture</li><li>Enable the use of SurfaceLayer objects for videos</li></ul><h3>Starting Point</h3><p>For this article we will be using the following HTML markup as our starting point:</p><pre>&lt;video <br>  src=&quot;<a href="https://cdn.arnellebalane.com/videos/original-video.mp4">https://cdn.arnellebalane.com/videos/original-video.mp4</a>&quot;<br>  controls<br>&gt;&lt;/video&gt;</pre><pre>&lt;button&gt;Enter Picture-in-Picture&lt;/button&gt;</pre><p>On the page, this will display a video element playing the Big Buck Bunny trailer and a button to toggle Picture-in-Picture; and with some styling, will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cKuAisMbI8rhAgmMOm_WTA.jpeg" /></figure><p>In our JavaScript code, we’re also going to define variables to reference both the video and button elements.</p><pre>const video = document.querySelector(&#39;video&#39;);<br>const button = document.querySelector(&#39;button&#39;);</pre><h3>Check support for Picture-in-Picture</h3><p>Not all users who visit your page will be using a browser that supports Picture-in-Picture, so we only enable it if it is supported by the browser. This is called <strong>progressive enhancement</strong>, and it is important to do this so that users won’t have a broken experience if their browsers don’t support Picture-in-Picture.</p><p>Checking for Picture-in-Picture support can be done by checking for the pictureInPictureEnabled property on the document object:</p><pre>if (!<strong>document.pictureInPictureEnabled</strong>) {<br>  // Let the user know that PiP is not enabled/supported.</pre><pre>  button.textContent = &#39;PiP is not supported in your browser.&#39;;<br>  button.disabled = true;<br>}</pre><p>The specification says that document.pictureInPictureEnabled <em>“is </em><em>true if there is no previously-established user preference, restrictions, or platform limitation, and </em><em>false otherwise.”</em> I don’t know what all of these preferences, restrictions, and limitations are, but it is false when any of the required browser flags are not enabled. For older browsers, this properly will just be undefined which is a false-y value.</p><h3>Requesting Picture-in-Picture</h3><p>Once we’ve determined that the browser supports Picture-in-Picture, we can now safely use the API. In our example, we will make the video go into Picture-in-Picture mode when the “Enter Picture-in-Picture” button is clicked.</p><p>We can make a video go into Picture-in-Picture mode by calling the requestPictureInPicture() method on it, which returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises">Promise</a> object which can be used to determine if the request succeeded or not.</p><pre>button.addEventListener(&#39;click&#39;, () =&gt; {<br>  <strong>video.requestPictureInPicture()</strong><br>    .then(() =&gt; { /**/ })<br>    .catch(() =&gt; { /**. });<br>});</pre><p>When the Promise resolves, the video will go into Picture-in-Picture mode and the document.pictureInPictureElement property will be set to the element that is currently in Picture-in-Picture mode, i.e. our video element.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3WfNuwCVtc1nnt8xVqIRzg.png" /></figure><h3>Leaving Picture-in-Picture</h3><p>Users can get out of Picture-in-Picture mode by clicking on the “x” icon on the Picture-in-Picture window.</p><p>However, we can also add a way in our page for the user to exit from Picture-in-Picture. In our example, clicking on the “Enter Picture-in-Picture” button while there is a Picture-in-Picture window should close it.</p><p>We modify our button’s click event handler to check if there is already a video element displayed in Picture-in-Picture mode. If there is, we close it by calling the document.exitPictureInPicture() method.</p><pre>button.addEventListener(&#39;click&#39;, () =&gt; {<br>  if (<strong>document.pictureInPictureElement</strong>) {<br>    <strong>document.exitPictureInPicture()</strong><br>      .then(() =&gt; { /**/ })<br>      .catch(() =&gt; { /**/ });<br>  } else {<br>    // Request Picture-in-Picture<br>  }<br>});</pre><p>Leaving Picture-in-Picture sets the document.pictureInPictureElement property back to null .</p><h3>Picture-in-Picture Events</h3><p>As elements enter and exit from Picture-in-Picture, they fire events to report these changes. Picture-in-Picture defines two new events on video elements: enterpictureinpicture and leavepictureinpicture , which get fired when the element enters and leaves Picture-in-Picture respectively.</p><p>Let’s use these events in our example to update our button’s label depending on whether the video is in Picture-in-Picture or not.</p><pre>video.addEventListener(&#39;enterpictureinpicture&#39;, () =&gt; {<br>    button.textContent = &#39;Exit Picture-in-Picture&#39;;<br>});</pre><pre>video.addEventListener(&#39;leavepictureinpicture&#39;, () =&gt; {<br>    button.textContent = &#39;Enter Picture-in-Picture&#39;;<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/653/1*KEj2S7T7zuu03pgPJ67FLQ.gif" /></figure><h3>Conclusion</h3><p>And that’s it about the Picture-in-Picture API! Here are some final notes and thoughts about it:</p><ol><li>It currently only works on video elements at the moment, but is meant to be extensible. This means that we could potentially have the ability to place any other elements in the Picture-in-Picture window in the future.</li><li>The number of allowed Picture-in-Picture windows is left to the browser’s implementation and the platform.</li><li>The Picture-in-Picture window stays on the bottom-right corner of the screen. It would be nice to have the ability to drag it around and resize it.</li></ol><h3>Resources</h3><ol><li><a href="https://wicg.github.io/picture-in-picture/">Picture-in-Picture Editor’s Draft</a></li><li><a href="https://developers.google.com/web/updates/2017/09/picture-in-picture">Picture-in-Picture (PiP) post</a> by <a href="https://medium.com/u/4df471ef485d">François Beaufort</a></li></ol><p>Thanks for reading this article! I’m a Web Developer from Cebu, Philippines. I also write articles and make demos about cool Web stuff. You can check them out on <a href="http://blog.arnellebalane.com/">my blog</a> and on <a href="https://github.com/arnellebalane/">my GitHub profile</a>. Have a great day! 🦔</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30415372009f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/the-picture-in-picture-api-30415372009f">The Picture-in-Picture API</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Intersection Observer API]]></title>
            <link>https://medium.com/arnelle-balane/the-intersection-observer-api-d441be0b088d?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/d441be0b088d</guid>
            <category><![CDATA[intersection-observer]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Sun, 25 Feb 2018 08:12:27 GMT</pubDate>
            <atom:updated>2023-02-12T05:39:34.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OtuFV6zUN-a41D9Jfw5YmA.png" /><figcaption><a href="https://arnellebalane.com/intersection-observer-api/">https://arnellebalane.com/intersection-observer-api/</a></figcaption></figure><p>The Intersection Observer API is a Web platform API that allows for observing changes to how much of a target element’s area intersects with that of an ancestor element or the viewport. The need for such information has a lot of use cases, such as implementing lazy-loading and infinite scrolling, just to name a few.</p><p>It’s been historically difficult to obtain such information, and common solutions oftentimes hurt the page’s performance, but the Intersection Observer API changes all of that. This article aims to give an introduction on how the API works as well as how to use it.</p><h3>Why “Intersection”?</h3><p>I’ve wondered for a while why the API is called <em>Intersection</em> Observer, when what it does is basically report changes on how much of an element’s area is visible inside an ancestor element or the viewport. Eventually I came to realize what it actually means and this is how I like to visualize it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*A8FO5ZwmebF9MDIlmOZOjQ.png" /></figure><p>Think of the browser’s viewport and the target element as their own boxes. The target element box is still somewhere at the lower part of the page and therefore not yet visible. As you scroll down, the target element box moves up, until eventually it overlaps (“intersects”!) with the the viewport box. Only then does the target element become visible on the page. The amount of this overlap or <strong>intersection</strong> is what the Intersection Observer API observes changes on.</p><h3>Terminologies</h3><p>Before we begin, here are definitions of some terminologies that are used a lot in the rest of the article:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*f9wc4By18W1Z54A69nhzUg.png" /></figure><ol><li><strong>Target Element</strong>. This is the element whose intersection with an ancestor element (or the viewport) we want to observe.</li><li><strong>Intersection Root</strong>. The ancestor element or the viewport in which we will be measuring the target element’s intersection against.</li><li><strong>Intersection Ratio</strong>. How much of the target element intersects with the intersection root. It is expressed as a value between 0 and 1, inclusive, where 0 means the two don’t intersect at all and 1 means the target element completely intersects with the intersection root.</li></ol><h3>Creating an Intersection Observer</h3><p>An Intersection Observer is created through the <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver/IntersectionObserver">IntersectionObserver</a> constructor. It accepts a callback function which it executes when it has intersection changes that it wants to report. Then we call its .observe() method to start observing a target element.</p><pre>const observer = new IntersectionObserver(function(changes) {<br>    // do something with the changes<br>});<br>observer.observe(targetElement);</pre><p>By default, the Intersection Observer API uses the viewport as the intersection root, and only executes the callback when the target element enters and exits the viewport.</p><h4>Specifying an intersection root</h4><p>If we want to use an ancestor element as the intersection root instead of the viewport, we can do so by passing an options object as the second argument to the IntersectionObserver constructor, and specifying the root property.</p><pre>const intersectionRoot = document.querySelector(&#39;#ancestor&#39;);</pre><pre>const observer = new IntersectionObserver(function(changes) {<br>    // do something with the changes<br>}, {<br>    <strong>root: intersectionRoot</strong><br>});</pre><h3>Thresholds</h3><p>A threshold is a value in which the Intersection Observer will execute the callback function <strong>whenever the intersection ratio reaches that value</strong> (either as it increases or decreases), and is also expressed as a value between 0 and 1, inclusive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*UC1tep1Ql_FuYqwZbUVIJw.png" /></figure><p>The Intersection Observer uses a default threshold value of 0, which is why it only executes the callback function when the target element enters (i.e. crosses the intersection ratio of 0 as it starts to become visible) or exits (i.e. crosses the intersection ratio of 0 as it finally fully disappears) the intersection root.</p><h4>Specifying thresholds</h4><p>We can let our Intersection Observer use a different threshold value by passing a threshold property in the options object.</p><pre>const observer = new IntersectionObserver(function(changes) {<br>    // do something with the changes<br>}, {<br>    <strong>threshold: 0.5</strong><br>});</pre><p>The example above executes the callback function every time the target element’s intersection ratio crosses 0.5. It is also possible to set multiple threshold values by passing an array of threshold values.</p><pre>const observer = new IntersectionObserver(function(changes) {<br>    // do something with the changes<br>}, {<br>    <strong>threshold: [0, 0.25, 0.5, 0.75, 1]</strong><br>});</pre><p>The example above executes the callback function when the target element enters/exits the intersection root (i.e. intersection ratio of 0), then again when its intersection ratio crosses 0.25, then 0.5, etc.</p><h3>The Callback Function</h3><p>The callback function, when executed, is passed an array of entries, each an instance of <a href="https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry">IntersectionObserverEntry</a>. This is an array because the Intersection Observer object can be used to observe multiple target elements, so it just reports intersection changes for these multiple elements together.</p><p>Each IntersectionObserverEntry object has the following helpful properties:</p><ul><li>boundingClientRect and rootBounds, the positions and dimensions of the target element and the intersection root respectively.</li><li>intersectionRect, the position and dimension of the rectangle representing the portion where the target and intersection root intersect.</li><li>intersectionRatio, the intersection ratio value at that point.</li><li>isIntersecting, whether the target element currently intersects with the intersection root or not.</li></ul><h3>Root Margin</h3><p>The rectangles that are used to compute the intersection ratio are based on the bounding boxes of both the intersection root and the target element. However, it is possible to adjust the intersection root’s rectangle by setting <strong>root margins</strong>.</p><p>We can expand the rectangle’s dimensions by setting a positive root margin, and shrink it by setting a negative root margin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*iWRg3m0chUx8w2MzuKQDWQ.png" /></figure><p>Root margins can be specified using a syntax that is similar to setting CSS margins, e.g. 10px 10px 10px 10px or 10px, which allows us to customize the bounding box dimensions on all sides, or just on some specific sides.</p><h4>Specifying a root margin</h4><p>By default, the root margin is set to 0px 0px 0px 0px. If we want to specify a different root margin, we can do so by passing a rootMargin property in the options object.</p><pre>const observer = new IntersectionObserver(function(changes) {<br>    // do something with the changes<br>}, {<br>    <strong>rootMargin: &#39;10px&#39;</strong><br>});</pre><h3>Conclusion</h3><p>So that’s about it for the Intersection Observer API. I made <a href="https://intersection-observer-api.arnelle.dev/">a little demo</a> where you can check out the API in action by interacting with a few elements on the page.</p><p>In terms of browser support, it is supported on the latest versions of Edge, Firefox, Chrome, and Opera, as well as on several mobile browsers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MLagxrzEGeknJLIm7xdKiA.png" /><figcaption><a href="https://caniuse.com/#feat=intersectionobserver">https://caniuse.com/#feat=intersectionobserver</a>, Feb 25 2018</figcaption></figure><p>The Intersection Observer API provides a really simple, performant, and easy-to-use solution to a common need in modern Web applications, and I’m glad that this has been added to the Web platform.</p><p>Thanks for reading! If you find this article helpful, it would be nice if you can share it so that other people will know about how awesome the Intersection Observer API is! :)</p><p>PS: Thanks to <a href="https://medium.com/u/731abe4b584e">Julia Camille</a> for reviewing and giving feedback on this article!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d441be0b088d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/the-intersection-observer-api-d441be0b088d">The Intersection Observer API</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sending data across different browser tabs]]></title>
            <link>https://medium.com/arnelle-balane/sending-data-across-different-browser-tabs-6225daac93ec?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/6225daac93ec</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Fri, 01 Dec 2017 03:40:07 GMT</pubDate>
            <atom:updated>2017-12-01T03:40:06.558Z</atom:updated>
            <content:encoded><![CDATA[<p>Some time ago I explored different ways of sending data across different browser tabs or windows. My challenge is for it to be a purely client-side solution, so WebSockets cannot be used. This was inspired by the need for such a solution in a project that we’re working on, as well as the release of the new BroadcastChannel API which made me wonder how it could be done before it became available.</p><h4>BroadcastChannel API</h4><p>As mentioned, there is a new Web API called the <a href="https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel"><strong>BroadcastChannel API</strong></a> which has been available since Chrome 54 and <a href="http://caniuse.com/#feat=broadcastchannel">recent versions of several other browsers</a>. Its purpose is to allow simple communication between different browsing contexts (i.e. windows, tabs, workers, etc.) from the same origin. Here is an example of how to use it:</p><pre>const channel = new BroadcastChannel(&#39;channel-name&#39;);</pre><p>We create a new channel using the BroadcastChannel constructor which accepts a name for the channel as an argument. The channel name is important because channels that are listening on the same channel name will be able to broadcast messages to each other. Channels can be instantiated from different tabs, workers, and other browsing contexts, but as long as they are listening on the same channel name, they will be able to communicate with each other.</p><p>To make a channel broadcast a message, we would call the channel&#39;s postMessage() method which accepts any kind of object:</p><pre>channel.postMessage(&#39;some message&#39;);<br>channel.postMessage({ key: &#39;value&#39; });</pre><p>This will fire a message event to all the other channels that are listening on the same channel name. Channels can then add an event handler for this event in order to obtain the broadcasted message:</p><pre>channel.onmessage = function(e) {<br>    const message = e.data;<br>};</pre><p>We can also make a channel stop receiving messages by closing it:</p><pre>channel.close();</pre><p>Ideally, the BroadcastChannel API is the way to go when talking about communication across multiple tabs as it was designed to solve that specific problem. It not only broadcasts data across tabs but other browsing contexts as well, including workers, iframes, etc. However, this API is relatively new and at the time of writing is only supported by the latest versions of major browsers. So what are the alternatives?</p><h4>SharedWorker API</h4><p>A Web Worker is a Javascript file that is run by the browser in the background, separate from our applications’ main thread. A <a href="https://developer.mozilla.org/en/docs/Web/API/SharedWorker"><strong>Shared Worker</strong></a><strong> </strong>behaves in a similar way as regular Web Workers except that different browsing contexts from the same origin will have shared access to the worker. In other words, if you have five tabs running the same Shared Worker script, the browser will only run one instance of that script in the background, and the five tabs will have shared access to the context and state of that single running Shared Worker.</p><p>We can make use of Shared Workers and their behavior to create a messaging channel for all connected tabs. First thing we need to do is create the Shared Worker script. Let’s name it shared-worker.js and leave it empty for now.</p><p>Let’s say we have two browser tabs, and each of these tabs want to use the the Shared Worker script to perform some operations, each of them would run some JavaScript code containing this:</p><pre>const worker = new SharedWorker(&#39;shared-worker.js&#39;);</pre><p>This creates a new SharedWorker object, executing the script located at the path passed in to the constructor. Each tab can communicate with the SharedWorker object via a MessagePort which can be accessed from worker.port. The Shared Worker script also has access to their ports, because every time a tab connects to the Shared Worker a connect event is fired within the Shared Worker script.</p><pre>// shared-worker.js<br>const connections = [];</pre><pre>onconnect = function(e) {<br>    const port = e.ports[0];<br>    connections.push(port);<br>};</pre><p>MessagePort objects here only allow communication between the tab and the Shared Worker script, so if we want the tab to broadcast data to other tabs, we’d make the Shared Worker remember the MessagePorts to other tabs.</p><p>To send data from a tab to the Shared Worker, we would call the MessagePort’s postMessage method:</p><pre>worker.port.postMessage(&#39;some message&#39;);</pre><p>This will fire a message event in the port in the Shared Worker, which we can attach an event handler for and forward the data to the other tabs by still using the postMessage method:</p><pre>// shared-worker.js<br>const port = e.ports[0];</pre><pre>port.onmessage = function(e) {<br>    connections.forEach(function(connection) {<br>        if (connection !== port) {<br>            connection.postMessage(e.data);<br>        }<br>    });<br>};</pre><p>Finally, tabs can receive data from the Shared Worker script by similarly adding an event handler for the message event on the MessagePort object:</p><pre>worker.port.onmessage = function(e) {<br>    const message = e.data;<br>};</pre><p>And that’s how we use Shared Workers to make a messaging channel across multiple tabs! It does require a separate file for the Shared Worker script, but I guess that’s just a small price to pay to achieve inter-tab communications.</p><h4>Local Storage</h4><p>One last alternative is to use localStorage, part of the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API">Web Storage API</a>. This API provides a mechanism for storing key-value pairs in the browser. One nice thing about this is that every time a stored item changes (e.g. gets added, removed, or modified), an event is fired in other tabs letting them know about that change. We can make use of this behavior to make a messaging channel across multiple tabs as well.</p><p>The localStorage object is directly available from the window object, so we can use it right away from there. Storing key-value pairs into localStorage can be done as:</p><pre>localStorage.setItem(&#39;key&#39;, &#39;value&#39;);</pre><p>Keys and values are always stored as strings, so we have to serialize complex objects before storing them. This will fire a storage event in the other tabs’ window objects, which they can add an event handler for:</p><pre>window.onstorage = function(e) {<br>    const message = e.newValue; // previous value at e.oldValue<br>};</pre><p>There are other complexities involved with using localStorage for this purpose. One is that adding the exact same key-value pair values will not fire the storage event. This can be taken care of by always deleting the stored key-value pair right away. Another is that writing key-value pairs is prone to race conditions. We’d also have to add our own mechanism to handle that properly.</p><p>This approach is definitely not the most elegant, but it gets the job done.</p><p>I made a library called <a href="https://github.com/arnellebalane/hermes"><strong>hermes</strong></a> which aims to provide a consistent API for a client-side messaging channel. Under the hood, it only abstracts the different solutions described in the previous sections of this article.</p><p>After we’ve loaded the library, we can use it to easily send data to other tabs:</p><pre>hermes.send(&#39;key&#39;, &#39;value&#39;);</pre><p>Other tabs can listen for messages using the .on()/.off() methods:</p><pre>hermes.on(&#39;key&#39;, function(data) { ... });</pre><pre>// stop listening for messages<br>hermes.off(&#39;key&#39;);</pre><p>I hope you find this helpful in your projects. You can also submit issues or contributions through the <a href="https://github.com/arnellebalane/hermes">Github repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6225daac93ec" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/sending-data-across-different-browser-tabs-6225daac93ec">Sending data across different browser tabs</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Updating my website to use JavaScript Modules]]></title>
            <link>https://medium.com/arnelle-balane/updating-my-website-to-use-javascript-modules-78e9b9c71071?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/78e9b9c71071</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Wed, 20 Sep 2017 19:06:17 GMT</pubDate>
            <atom:updated>2017-09-20T19:12:07.134Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DiOqBLQYH9ZLESyXlMPHHA.png" /></figure><p>JavaScript Modules has <a href="https://www.chromestatus.com/feature/5365692190687232">landed in Chrome 61</a>! Excited to try out the Web platform’s native way of defining and loading modules, I started updating my website to use this new feature. This post is going to be about the things that I did as well as the things that I still need to figure out.</p><blockquote>JavaScript modules allow a program to be divided into multiple sequences of statements and declarations. Each module explicitly identifies declarations it uses that need to be provided by other modules and which of its declarations are available for use by other modules.</blockquote><h3>#1. Loading JavaScript modules</h3><p>JavaScript modules are loaded with a &lt;script type=”module”&gt; element. Note the type=”module&quot; attribute, which is required in order for the script to be treated as a module by browsers that support it. Those that don’t will just ignore it.</p><p>Browsers that support JavaScript modules also ignore script tags that have the nomodule attribute. This behavior is useful in specifying fallbacks to browsers that don’t support JavaScript modules yet, while the ones that do can get the modules version.</p><p>With that , this is now what my code for loading my JavaScript files look like:</p><pre>&lt;script type=&quot;module&quot; src=&quot;modules/main.js&quot;&gt;&lt;/script&gt;<br>&lt;script nomodule src=&quot;regular/lib/idb-fetch-mirror.js&quot;&gt;&lt;/script&gt;<br>&lt;script nomodule src=&quot;regular/lib/utils.js&quot;&gt;&lt;/script&gt;<br>&lt;script nomodule src=&quot;regular/main.js&quot;&gt;&lt;/script&gt;</pre><h3>#2. The module scope</h3><p>With JavaScript modules, any top-level declarations are scoped within that module only. This means that these declarations can be used from anywhere in the module, but not by other modules. This is different from the regular behavior where declarations gets into the global scope and is accessible by all other scripts.</p><p>One of my JavaScript files, idb-fetch-mirror.js, uses the Revealing Module Pattern in order to contain its functionality without polluting the global scope and just returning the things that it wants other scripts to use:</p><pre>const ifm = (() =&gt; {<br>    function get(key) { ... }<br>    function put(key, value) { ... }<br>    function mirror(request) { ... }<br>    <br>    return mirror; <br>})();</pre><p>With the module scope of JavaScript modules, I don’t have to do this anymore, and my declarations can be placed directly at the top-level of the module’s body:</p><pre>function get(key) { ... }<br>function put(key, value) { ... }<br>function mirror(request) { ... }</pre><h3>#3. Exporting functionality</h3><p>The module scope makes sure that declarations in the module are scoped within that module. If a module wants to expose some of its declarations for other modules to use, it can do so by exporting them. Exporting is done by prefixing the declaration with the export keyword.</p><p>I have a utils.js file which contains a bunch of utility functions. When loaded as a module, those functions gets scoped within the module. Since I want those functions to be usable by other modules, I make the utils.js module export them:</p><pre>export function $(selector) { ... }<br>export function template(tmpl, context} { ... }<br>export function element(tmpl) { ... }</pre><h4>Default exports</h4><p>Modules can also declare default exports. This is usually done when the module only wants to export a single value. To use default exports, the declaration to be exported is prefixed with the export default keywords.</p><p>My idb-fetch-mirror.js module only exports a single function, mirror(), so I exported it as a default export:</p><pre>function get(key) { ... }<br>function put(key, value) { ... }<br>export default function mirror(request) { ... }</pre><h3>#4. Importing dependencies</h3><p>When loading my modules I am only loading modules/main.js, compared to the fallbacks where each dependency is also loaded. This is because JavaScript modules can explicitly identify from within their code the declarations in other modules that it depends on. It does this by importing those declarations.</p><p>My main.js module depends on the utility functions inside utils.js, so it imports them. The cool thing about this is that it can import only the things that it needs.</p><pre>import { $, template, element } from &#39;./lib/utils.js&#39;;</pre><p>main.js also uses the idb-fetch-mirror.js module, so it also needs to import that. Since idb-fetch-mirror.js uses a default export to export its functionality, importing it is more straightforward:</p><pre>import ifm from &#39;./idb-fetch-mirror.js&#39;;</pre><p>There are many ways of importing a module depending on what you need. You can check out this <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">MDN reference for </a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import">import</a>.</p><h3>Things I still have to fix and figure out</h3><p>Despite the changes being minimal in converting my codebase to use JavaScript modules, I’ve also encountered several difficulties. These are definitely not issues with JavaScript modules but more with how I built my website. Any tips on how to address these are appreciated.</p><h4>#1. Duplicate code</h4><p>In order to support both browsers that do and don’t support JavaScript modules, I had to make two versions of my code. Now my codebase is currently tiny, but as more modules are added, maintaining two versions might not be desirable.</p><p>One thing I tried (you know, just in case it works haha) is to do something like the UMD pattern but for modules. The problem is that I don’t know how to detect if a browser supports modules. Browsers that don’t support modules also throw a SyntaxError, which we can’t try…catch for feature detection. So I guess for now I’m stuck with my duplicate code.</p><h4>#2. Preloading: which ones to preload?</h4><p>My website also preloads the resources that it needs, including the JavaScript files. This is so that these resources are fetched as early as possible and are already available when the page needs them. This is currently done by sending the Link header together with the response:</p><pre>Link: &lt;regular/main.js&gt;; rel=preload; as=script,<br>      &lt;regular/lib/idb-fetch-mirror.js&gt;; rel=preload; as=script,<br>      &lt;regular/lib/utils.js&gt;; rel=preload; as=script</pre><p>But now that I have two versions of my code, preloading both versions wouldn’t make sense. It would actually make things worse because the client would have to download both versions of the code and then end up using just one of the versions, thus wasting the user’s precious bandwidth. Chrome even warns us when preloaded resources are not used, saying to <em>“Please make sure it wasn’t preloaded for nothing.”</em></p><p>Ideally I would want to preload just the version of the code that the browser supports, but I currently do not know how to determine that or if that’s even possible, so for now I just didn’t preload any of JavaScripts yet. Might as well wait a little longer for them to be available than waste bandwidth preloading resources that are not going to be used anyway.</p><h4>#3. Service worker caching: which ones to cache?</h4><p>My website works offline by caching the resources that it needs and intercepting network requests with a service worker. Since it needs the JavaScript files to work offline, I can’t just leave them out like what I did with preloading. So I just ended up caching both versions of the code. They’re only going to be downloaded once, during the service worker’s install step. I guess that’s a small price to pay to get it to work offline. It could be better though.</p><p><em>While writing this section I might have thought of a better way to do this. I could perform the caching of the JavaScript files from within the JavaScript files instead (instead of in the service worker) since they also have access to the Cache API. The modules version of my JavaScript can add only the URLs to the JavaScript modules into the cache, while the regular version can also only add the URLs to themselves. I’ll update this once I’ve tested it out.</em></p><h4>#4. Build system problems</h4><p>I am using Gulp to build my website’s assets and get them ready for production. For building JavaScript specifically, I pipe them through Babel (gulp-babel) to transpile ES6 code to ES5, then pipe the results to UglifyJS (gulp-uglify) for minification.</p><p>My problem is that Babel treats the import calls as NodeJS module imports, and thus transpiles them into require() calls. This doesn’t work for the Web and will result to errors. Babel has an option called sourceType which can be used to indicate how the code should be parsed (I suppose setting it to ‘script’ will parse it as for the browser environment), but it doesn’t recognize the import and export keywords yet, saying that they are only available with the sourceType: ‘module’. So for now I currently do not transpile the module versions of my code.</p><h3>Conclusion</h3><p>I still have a lot to learn about other people’s patterns regarding how they use JavaScript modules so that I could address my issues which I just mentioned. Nonetheless, it’s really exciting to have a native way of defining and loading modules on the Web, and it has finally arrived! Also, I guess it won’t take long already for modules to be natively supported and enabled by default in NodeJS!</p><h3>Additional Resources</h3><ul><li><a href="https://jakearchibald.com/2017/es-modules-in-browsers/">ECMAScript modules in browsers</a> by Jake Archibald, talks about browser-specific behavior of JavaScript modules.</li><li><a href="https://ponyfoo.com/articles/es6-modules-in-depth">ES6 Modules in Depth</a> by Nicolás Bevacqua</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78e9b9c71071" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/updating-my-website-to-use-javascript-modules-78e9b9c71071">Updating my website to use JavaScript Modules</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Credential Management API]]></title>
            <link>https://medium.com/arnelle-balane/the-credential-management-api-7eb5650d23ca?source=rss----4f05a9847d8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/7eb5650d23ca</guid>
            <category><![CDATA[credential-management-api]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Arnelle Balane]]></dc:creator>
            <pubDate>Sun, 27 Aug 2017 15:53:54 GMT</pubDate>
            <atom:updated>2023-02-12T05:40:44.166Z</atom:updated>
            <content:encoded><![CDATA[<p>The Credential Management API is a browser API which provides programmatic access to the browser’s credential manager and helps users sign in to our apps more easily and seamlessly. It allows web apps to store and retrieve user credentials, and offers a lot of benefits:</p><ol><li><strong>Reduces sign in flow friction</strong><br>Users can be automatically signed in back into the site when their session expires, or when they’ve already signed in and saved their credentials on another device.</li><li><strong>Allows one tap sign in with account chooser</strong><br>Users can see a list of accounts that they’ve used for the app via a native account chooser widget, and with a single tap, sign in using a specific account. This capability allows users to sign in without typing passwords.</li><li><strong>Stores and syncs credentials</strong><br>Our apps can store user credentials, be it a username/password combination or federated (i.e. using third-party providers) account details. These credentials are synced across devices by the browser.</li></ol><p>I created <a href="https://credential-management-api.arnelle.dev/">a demo application</a> showcasing the Credential Management API in action, and here’s a video of how it works:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FKuX2lqAeT5M%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DKuX2lqAeT5M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FKuX2lqAeT5M%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e7a2b0c28a29c3af2d8a23e8c7b1a42/href">https://medium.com/media/7e7a2b0c28a29c3af2d8a23e8c7b1a42/href</a></iframe><p>If you are viewing the demo application, here’s something cool to try out: sign in to the app using any of the available sign in methods, and choose “Save” when the browser asks you if you want to save your password or account. This saves and syncs (assuming you have sync enabled in your browser) your credentials across your other devices. Now get another device and open the demo app. It should automatically sign you in. Awesome!</p><p>At the time of writing, this API is only supported on Chrome ≥51, Opera ≥45, Android Browser 56, and Chrome for Android ≥59.</p><p>Now let’s take a look at how to use the Credential Management API to create a really cool authentication experience.</p><h3>Feature Detection</h3><p>Before using the API, we need to check first if the browser supports it.</p><pre>if (navigator.credentials <br>&amp;&amp; navigator.credentials.preventSilentAccess) {<br>    // Credential Management API is supported!<br>}</pre><p>There is an extra check for the presence of preventSilentAccess which checks whether the browser supports the new Credential Management API (the old version has requireUserMediation instead of preventSilentAccess).</p><h3>Storing user credentials</h3><p>When the user signs in to our app, we need to store their credentials so that it can be used later for auto-sign in as well as get synced across devices. This is done by storing a Credential object to the browser using navigator.credentials.store().</p><p>There are two types of credentials depending on how the user signed in to our app.</p><h4>Signing in with username/email and password</h4><p>If the user signed in with a username/email and password, we need to store an instance of PasswordCredential.</p><pre>const credentials = new PasswordCredential({<br>    id: &#39;arnellebalane@gmail.com&#39;,<br>    name: &#39;Arnelle Balane&#39;,<br>    password: &#39;myawesomepassword&#39;,<br>    iconURL: &#39;https://arnellebalane.com/avatar.png&#39;<br>});<br>navigator.credentials.store(credentials);</pre><p>Only the id and password options are required. What the value of the id option is is entirely up to us: it could be an email address, username, etc. as long as it identifies the user in our app.</p><h4>Signing in with federated account</h4><p>If the user signed in with a federated account (i.e. sign in with Google, Facebook, Github, etc.), we need to store an instance of FederatedCredential.</p><pre>const credentials = new FederatedCredential({<br>    id: &#39;arnellebalane@gmail.com&#39;,<br>    name: &#39;Arnelle Balane&#39;,<br>    iconURL: &#39;https://arnellebalane.com/avatar.png&#39;,<br>    provider: &#39;https://accounts.google.com&#39;<br>});<br>navigator.credentials.store(credentials);</pre><p>Only the id and provider options are required. The provider needs to be a valid URL identifying the credential provider, and will be shown in the account chooser as a hint for where the credentials were obtained from.</p><p>You can see from my examples that I am hard-coding credential values. You wouldn’t want to do that. The previous code snippets can be run at any point after user has signed in, when we already have access to their profile.</p><p><strong>Note:</strong> The Credential Management API does not replace existing authentication flows and provide an alternative one. It actually supplements existing ones by storing user credentials so they can perform the authentication process a lot faster.</p><p>Upon calling navigator.credentials.store(), the browser will prompt the user if they want to save their password or account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*teeuK-6tOBXBy_e4Uit-6A.png" /><figcaption>Save credentials prompt on desktop Chrome</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_T-8TaPX_d9XSetyq24Cw.png" /><figcaption>Save credentials prompt on Chrome for Android</figcaption></figure><p>Clicking on the “Save” button saves the user’s credentials on the browser. We can verify that the credentials have indeed been saved by going to <a href="/service/chrome://settings/passwords">chrome://settings/passwords</a>, which lists all saved passwords.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzQPQuMNfgup_E5ZLSBUhg.png" /><figcaption>chrome://settings/passwords</figcaption></figure><h3>Signing in users using stored credentials</h3><p>We can sign in a user using a stored credential by first obtaining which credential should be used. This can be done by calling navigator.credentials.get(), which returns a Promise that resolves into a Credential object that will be used to sign in the user or undefined if no stored credentials are found.</p><pre>navigator.credentials.get({<br>    password: true,<br>    federated: {<br>        providers: [<br>            &#39;https://accounts.google.com&#39;,<br>            &#39;https://www.facebook.com&#39;<br>        ]<br>    }<br>});</pre><p>navigator.credentials.get() accepts an options object which tells it what kinds of credentials it should look for. This object can have the following keys:</p><ul><li>password: a Boolean indicating that the returned Credential instances should include user (i.e. not federated) credentials.</li><li>federated: an object containing requirements for returned federated credentials, and can have the following options: providers and protocols, which are arrays of providers/protocols to search for.</li></ul><p>The code snippet above will get all stored user credentials as well as federated credentials from Google and Facebook. The providers strings need to match the provider option specified when we created the FederatedCredential instance. What happens next depends on how many credentials are found.</p><h4>No credentials found</h4><p>In this case,navigator.credentials.get() resolves with undefined. We can silently ignore it and let the user carry on with whatever they’re doing in our app.</p><h4>One credential found</h4><p>In this case, navigator.credentials.get() resolves with that one credential right away if user mediation is not required, allowing us to automatically sign in the user with it. If user mediation is required, it will open the account chooser showing just that one credential, which the user needs to explicitly select in order for our app to obtain the credential.</p><p>What is user mediation? It is when some action requires the user’s explicit consent in order for it to be performed. In the Credential Management API, it is expressed by the account chooser.</p><p>If the user gets automatically signed in, the browser lets them know about it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*MOXWUOkJyeSIZlhPMYkn8w.png" /><figcaption>Auto-sign in on desktop Chrome</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RPG4kAS2JEQhJ4KzivdRGw.png" /><figcaption>Auto-sign in on Chrome for Android</figcaption></figure><h4>More than one credentials found</h4><p>In this case, the account chooser will show with all the found credentials. When the user selects an account that they want to use from the account chooser, navigator.credentials.get() will resolve with the credential corresponding to the selected account.</p><p>This is what the account chooser looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*NxgJ0e4rw9wI1uh7npx2CA.png" /><figcaption>Account chooser on desktop Chrome</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWgcMOh9UzDSnUj5j5HJVw.png" /><figcaption>Account chooser on Chrome for Android</figcaption></figure><p>Either one of the three scenarios above gives as a Credential object (unless it’s undefined). We then use this credential to sign in the user, using sign in methods that we already have.</p><pre>navigator.credentials.get({ ... }).then(function(credential) {<br>    if (credential) {<br>        signIn(credential);<br>    }<br>});</pre><p>Now we only want the user to be auto-signed in or display the account chooser when the user is not currently signed in yet, so we check the user’s authentication status first before trying to get stored credentials.</p><pre>if (!isSignedIn) {<br>    navigator.credentials.get({ ... });<br>}</pre><p>With this, our users now have an easy way of authenticating themselves in our apps, by either being automatically signed in or with just a single tap on the account chooser.</p><h3>Signing the user out</h3><p>When the user signs out of our app, we’d like to make sure that they don’t get automatically signed back in again the next time they visit the app. For this reason, there is a navigator.credentials.preventSilentAccess() method. We need to call it upon signing out the user.</p><pre>function signOut() {<br>    // Do usual sign out stuff.<br>    navigator.credentials.preventSilentAccess();<br>}</pre><p>This will make the API require user mediation the next time navigator.credentials.get() is called, displaying the account chooser popup, and thus preventing the user from being automatically signed in unless they explicitly sign in themselves.</p><p><strong>Note</strong>: At the time of writing, the <a href="https://developer.mozilla.org/en-US/docs/Web/API/Credential_Management_API">MDN docs</a> for the Credential Management API currently lists preventSilentAccess() as requireUserMediation(). The latter is considered deprecated in the <a href="https://www.w3.org/TR/credential-management-1/">API’s W3C Working Draft document</a>, and has been <a href="https://www.chromestatus.com/feature/4781762488041472">renamed in Chrome</a> in the version 60 release.</p><h3>Additional Notes</h3><ol><li><strong>Identifying federated provider URLs</strong><br>While reading about the Credential Management API, I wondered where the values https://accounts.google.com and https://www.facebook.com came from. Turns out that the Working Draft encourages every site to use the same identifier when referring to a specific federated identify provider. For consistency, federations must be identified by the origin that they use for sign in. Reference <a href="https://www.w3.org/TR/credential-management-1/#provider-identification">here</a>.</li><li><strong>Compatibility with the Fetch API</strong><br>The fetch() function from the Fetch API accepts an options object that could have a credentials property. You might be familiar with it if you’ve used fetch() and wanted to include cookies with the request. This property can also be set to a Credential object from the Credential Management API.</li><li><strong>Removing stored credentials</strong><br>Currently (at least in Chrome), the only way to to remove a stored credential is via the settings page, at <a href="/service/chrome://settings/passwords">chrome://settings/passwords</a>. Nothing wrong with that though technically, in fact the Working Draft <a href="https://www.w3.org/TR/credential-management-1/#user-mediated-storage">states that it’s fine</a>.</li><li><strong>HTTPS is required</strong><br>Even insecure localhost does not work, so while developing I had to use <a href="https://ngrok.com/">ngrok</a>. We could use self-signed certificates as well to serve localhost via HTTPS.</li></ol><h3>Resources</h3><p>Here are the resources that have helped me learn about the Credential Management API:</p><ol><li><a href="https://developers.google.com/web/fundamentals/security/credential-management/">The Credential Management API </a>— a Web Fundamentals article from the Google Developers website.</li><li><a href="https://www.w3.org/TR/credential-management-1/">Credential Management Level 1 W3C Working Draft </a>— for all the technical details about the API. I haven’t really read the entire thing, but it’s cool.</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Credential_Management_API">Credential Management API MDN Docs</a> — might be outdated at the time of writing, but still a useful reference.</li></ol><h3>Conclusion</h3><p>I think this API is really awesome! As I noted earlier in this article, this API supplements existing sign in solutions in our applications, giving users a nice seamless experience without having to type in passwords. Browser support might still be currently low, but it is a good enhancement to add to those that support it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7eb5650d23ca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arnelle-balane/the-credential-management-api-7eb5650d23ca">The Credential Management API</a> was originally published in <a href="https://medium.com/arnelle-balane">Arnelle’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>