<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Alex Borton on Medium]]></title>
        <description><![CDATA[Stories by Alex Borton on Medium]]></description>
        <link>https://medium.com/@alexborton?source=rss-54452b006873------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kh9F0-4hfDKrw3HRcDJRVw.png</url>
            <title>Stories by Alex Borton on Medium</title>
            <link>https://medium.com/@alexborton?source=rss-54452b006873------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:37:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alexborton/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Authenticated API Calls]]></title>
            <link>https://medium.com/creating-totallymoney/authenticated-api-calls-1b431889a903?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b431889a903</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[mutex]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[rtk-query]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Tue, 29 Oct 2024 10:00:12 GMT</pubDate>
            <atom:updated>2024-10-29T10:00:12.192Z</atom:updated>
            <content:encoded><![CDATA[<h4>How we changed our authentication approach for the TotallyMoney Native App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YTNsbRvZ47_h0EJomyCz0w.jpeg" /></figure><h3>TL;DR</h3><p>Using pre-defined constants allowed us to intercept authenticated API calls, make sure the user is authenticated <em>or </em>can re-authenticate, and finally continue with the original request. Spoiler; I used <a href="https://www.npmjs.com/package/async-mutex">Mutex</a> to pause subsequent requests that might overlap the process.</p><h3>Background</h3><p>We have two types of “session” in our application;</p><ul><li>The Local session is effectively a <em>continued use</em> timer. If the user doesn’t use the application for a fixed period of time, we can soft log them out. This timer is reset with each app interaction, allowing continued use to occur. If the user is soft logged out, they have to re-authenticate. This acts as a security layer.</li><li>The Authentication session is more traditionally aligned with oAuth practices; a refresh token (that lasts a long time) and an Access token that expires quickly. <strong>This is the area we wanted to explore and improve.</strong></li></ul><p>It’s not all that common that our users local session overlaps with their auth session, but it does happen. And when it does, it’s likely they are trying to complete a task they are invested in, so it’s even more important that we get it right.</p><h3>The old solution</h3><p>Previously, we had the authentication session running on a timeout, where by we could query the time elapsed and refresh their token when the timer was running low (or expired). We would also automatically attempt to refresh their auth session when they returned from the background and other intervals that we guessed would be appropriate.</p><p>This did work, however, it started to introduce some issues when users were going from flow-to-flow often including external app activities. The likelihood of a race condition or tokens becoming out of sync became much, much higher. Not least because Android (and sometimes iOS) are happy to pause your javascript thread without you knowing, thus making the timer you set before redundant 🤦‍♂</p><p><strong>This got us thinking about how we might request new tokens when they <em>are required</em>, rather than as a preemptive step when we think <em>they might be required</em>.</strong></p><h3>The new solution</h3><p>Let’s start with what we know<em> </em>about the users session;</p><ul><li><strong>We know when their token will expire</strong>. Unlike local sessions, this is only reset when the token is actually refreshed. It’s stored in Redux for easy access.</li><li><strong>We know when the user is making authenticated API calls</strong>. We have Redux integrated into our application in the shape of RTK Query, RTK slices and some “classic” redux actions and thunks.</li></ul><p>It’s quite simple then — make each authenticated API request a Redux action, giving it access to our state at the point of the request, allowing us to intercept the request <strong>if the access token has expired</strong> and attempt to refresh <strong>before completing the original request</strong> with the new tokens, throwing the user out if they cannot refresh, or it fails 🔒.</p><p>One problem still remains — <strong>what if we have multiple authenticated requests coming in from different parts of the application at the same time, or overlapping</strong>? This could feasibly happen in lots of places within our app and the danger if they overlap is the same problem as before whereby the tokens could become out of sync.</p><h3>Mutex to the rescue!</h3><p>I had not heard of Mutex as a concept, less the library <a href="https://www.npmjs.com/package/async-mutex">async-mutex</a> but this solves our problem with effective “thread-locking”. Our TotallyMoney app is written in TypeScript (React Native, specifically) and thread-locking doesn’t exist. But that’s basically what Mutex gives you under the hood — the ability to pause incoming requests, locking a thread before opening it back up when we choose.</p><blockquote><a href="https://www.npmjs.com/package/async-mutex">This package</a> implements primitives for synchronizing asynchronous operations in Javascript.</blockquote><p>Going back to the new solution. When we have an expired authentication token we want to refresh, we can use Mutex to “pause” all incoming requests <em>until the original refresh request resolves. </em>Then we will know whether the user has re-authenticated successfully, or they need to return to a full authenticated flow. Using this approach, we can use up to date Redux state with the latest tokens and refresh timestamps to decide how to proceed. Better still, we can even share the same Mutex instance with multiple authenticated api helper calls, to covers RTK Slices, RTK Queries and the classic Redux implementation.</p><p>We will start with a Thunk called authenticatedApiCall. This can be used in the classic Redux setup, as well as in our RTK Slices.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f303d4be6c22ada9ae858e58ac5e91e7/href">https://medium.com/media/f303d4be6c22ada9ae858e58ac5e91e7/href</a></iframe><p>We start with the unhappiest of paths. The <strong>token is expired</strong>. Next we check to see if the thread is <strong>already locked. </strong>If this is the case, we know there is another authenticated request resolving, so we must first wait for it to resolve. It doesn’t entirely matter the outcome of that request, just that we use the most up to date authentication headers when it resolves.</p><p>If the <strong>token is expired</strong>, but the thread <strong>is not locked</strong>, we first need to lock it to pause subsequent requests. At this point, we can safely carry out our auth token refresh actions as we normally would, and assuming everything progresses correctly, release the locked thread.</p><p>The last case is the <strong>token is valid</strong> and all we need to do is execute the original request with the most up to date auth headers.</p><p>The usage of the thunk is just like any other api call.</p><p>I mentioned before that we are also using RTK Query and this means that we sadly can’t use the same thunk. Instead, we have to create a separate function, but we can follow all the same process and crucially, share the same instance of Mutex. This means that the thread locking will work across both Redux and RTK query 🎉</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e06a19b0dd095f55b972d57b97fc6e6/href">https://medium.com/media/6e06a19b0dd095f55b972d57b97fc6e6/href</a></iframe><p>Adding this as a baseQuery for our RTK Query setup means we can pop this in and leave it to do it’s thing — easy peasy.</p><pre>export const baseApi = createApi({<br>  reducerPath: &#39;api&#39;,<br>  baseQuery: appBaseQueryWithAuth,<br>  // ...<br>})</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b431889a903" width="1" height="1" alt=""><hr><p><a href="https://medium.com/creating-totallymoney/authenticated-api-calls-1b431889a903">Authenticated API Calls</a> was originally published in <a href="https://medium.com/creating-totallymoney">Creating TotallyMoney</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I write apps in my spare time, and you should too.]]></title>
            <link>https://medium.com/creating-totallymoney/i-write-apps-in-my-spare-time-and-you-should-too-ad226471029c?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad226471029c</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[product-design]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Thu, 12 Sep 2024 15:04:25 GMT</pubDate>
            <atom:updated>2024-09-12T15:04:25.593Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L8bWFdjDPJ1NHBUUAqsORA.png" /><figcaption><a href="https://qwhiz.app.link/">Qwhiz</a> — daily quizzing app</figcaption></figure><p>I am a developer by trade and in my spare time, I enjoy writing apps. It’s something I think a lot of other engineers do too, but a lot of the time they don’t quite get it over the line — which, by the way, doesn’t matter.</p><p>In this article I will talk a little about why I spend a lot of my spare time doing the same things as my full time job, what I get from it and how I think all engineers can benefit. This isn’t a technical dive, more of a reflection on my journey.</p><p>—</p><p>I have been a developer for more than 15 years. I started, like a lot of people, teaching myself. I don’t have a degree, instead, I have learnt on the job (and off it). I spent a lot of those <em>university years</em> trying out lots of other passions; skateboarding, filmmaking, t-shirt printing and product making. I’ve always had a calling towards <em>making things</em>.</p><p>I am now a Senior Engineer at <a href="https://www.totallymoney.com/">TotallyMoney</a>. We have a great Native app, website, and lots of other tech to keep me more than busy. So why do I go from writing code in the day, to writing <em>more </em>code in the evening and at the weekends?</p><p>—</p><p>The first reason is the most important: <strong>I enjoy it</strong>. I’ve always considered myself very lucky to enjoy my work so much. And I imagine that’s a big part of why I continue on into the evenings and weekends.</p><p>What I enjoy the most about my job is building things. Sure, they are digital, but still, you are placing bricks upon bricks, building <em>something </em>up and up, improving it, renovating it, knocking parts down and building it again. And like any good project, it’s never really <em>done</em>. This can transcend into the side projects I start too.</p><p>—</p><p>The second reason I code for so many extra hours is because <strong>I learn so much</strong>. When you’re coding at work, there are guardrails and red tape and protocol and process. My employer, TotallyMoney, is actually incredibly flexible and offers huge amounts of autonomy to its engineers and other employees, but even still, I am fulfilling <em>their </em>vision, targets and objectives.</p><p>By writing your own projects, you have the infinite flexibility to just try <em>something</em>. It doesn’t have to fit into a predefined agenda. That might be a new tech stack, a new technique, a new pattern or process or even a whole new language or discipline. When I am writing my own projects, I’m managing the whole thing, from start to finish. This gives me insight into different areas that I’m not necessarily involved in, in my day to day.</p><p>Needless to say, all that learning can transfer directly into work. It might lead to a technical solution, or part of an idea, or maybe just a better formed opinion on a specific area.</p><p>—</p><p>The third really useful thing I can get from my own projects is <strong>failure</strong>. It’s not a new concept that failing is beneficial — failing fast specifically is the most useful. Those new patterns or ideas you have can be proven quickly in the wild and you can take that information back again into your workplace. Again, TotallyMoney are very good at encouraging and supporting this type of exploration, where failure can be celebrated. But let’s face it, no one really <em>wants</em> to fail at work and whilst you can learn from those failings, it’s not quite the same.</p><p>The difference between your personal projects and those that are done in the workplace is justification. You don’t have to justify any of your decisions to yourself. If you want to try something, just for the sake of trying it, you can. If you’ve absolutely no idea of whether you’re going to succeed, it doesn’t matter at all.</p><p>—</p><p>This is the part where I talk about my latest project; <a href="https://qwhiz.app/">Qwhiz</a>. Qwhiz is a quizzing app. It was born quite organically, with a very small scope and whilst it didn’t quite fail in that scope, I quickly realised a much better path to success (hopefully!).</p><p>To set the scene, my team and I were on a social on winter evening at a local pub, cycling through some q-card-type-quiz sets. I happened to be the one reading the questions to the group (as I am awful at quizzes!) and everyone was shouting answers and listening to the results. It was quick fire, fun, simple and social.</p><p>It wasn’t long before a few more pints had been consumed, and the questions had run out. As an engineer, the first thought that crossed my mind is “there must be a Quiz API I can could tap into…”.</p><p>And that was the start of the project; build an app that users can quickly and easily create their own quiz “rooms”, generating questions for the participants to answer, on their own devices, asynchronously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OcUEtT4CT19vfJXmVbaqig.png" /><figcaption>The initial user journey for Qwhiz private quizzing</figcaption></figure><p>I teamed up with a talented product designer, also from TotallyMoney, and we quickly had the bare bones of the app ready to go. We kept the scope pretty tight — looking to get an MVP out within a couple of months.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OeBoIpwV5Pwn6_HOdAsr3Q.png" /><figcaption>Early wireframes of the Qwhizmaster journey</figcaption></figure><p>By our office Christmas party, I had enough of an app put together to suggest that one of our traditional Christmas Quiz rounds be played on Qwhiz, by the whole office (60 plus people!) in a bold, live testing scenario. After some crowd jeering, we successfully completed a tongue-in-cheek round of multiple choice questions about current employees. There was some cheating, some bugs and lots of laughs. Overall, it was a success.</p><p>After that, I continued to work on the app, building in more fun features (that weren’t used very much!) because I found enjoyment in building the features and seeing them in the wild. It was a good, solid product that I could continue to construct. But it became clear after a few more months that the format was difficult to introduce people to. Unless it was me selling it to my friends and family, it wasn’t really taking off. In other words, it was failing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WvPGtTBBxrBaEJWmp0j_Ew.png" /><figcaption>Visual direction of the application</figcaption></figure><p>But that was just fine by me because I had another idea, what about a Daily Quiz? It could keep the same multiple choice answering mechanism, the same API to generate to questions, but instead of “private rooms” for people to play in, all users can complete against all users, every day, with a quick set of 5 random questions.</p><p>It didn’t take me long to structure this, reusing a whole bunch of code I’d already written and patterns I’d already established successfully within the app. And then before I knew it, I had a couple of dozen users coming back every day to play the quiz – I’d found a hook.</p><p>Naturally, this isn’t really the end of the story and I am continuing to actively develop Qwhiz. The original functionality for private rooms still exists in the app, and I have more plans to expand there. The Daily Qwhiz now has weekly leaderboards and speed bonuses and fastest answers etc. The next steps for me are clear; grow my user base – hence the shameless blogging and promotion!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wN2g4AI0uXsWPJVfMh5wgw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mXRMmJZQ13T9pwdHGtIlDA.png" /></figure><p>Equally as important to me as the success of Qwhiz, is the learnings that I have taken directly into my full time work. Countless shifts in thinking, patterns and small failures (to know to avoid!) has made me a far better engineer, with a more broad understanding of product development and engineering best practices.</p><p>If you want to join the Daily Qwhiz, or setup your own private quiz with your friends, you can do all that right now on the <a href="https://qwhiz.app.link/">Web</a>, <a href="https://apps.apple.com/gb/app/qwhiz/id6467556058?platform=iphone">App Store</a> or <a href="https://play.google.com/store/apps/details?id=com.alexborton.qwhiz&amp;hl=en_GB&amp;pli=1">Play Store</a>.</p><p>I’ll continue to develop Qwhiz (and the next apps…) and I think you should start your own journey, too. You can increase your knowledge, broaden your skill set and have a whole lot of fun at the same time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad226471029c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/creating-totallymoney/i-write-apps-in-my-spare-time-and-you-should-too-ad226471029c">I write apps in my spare time, and you should too.</a> was originally published in <a href="https://medium.com/creating-totallymoney">Creating TotallyMoney</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CodePush in React Native]]></title>
            <link>https://medium.com/creating-totallymoney/codepush-in-react-native-3ad152206688?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad152206688</guid>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[over-the-air-update]]></category>
            <category><![CDATA[code-push]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[react-native-codepush]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Mon, 13 Nov 2023 10:56:14 GMT</pubDate>
            <atom:updated>2023-11-13T10:56:14.646Z</atom:updated>
            <content:encoded><![CDATA[<h4>A look at how you can optimise your configuration and UI for a better UX.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D9824-1FPPunawiHQpcXIg@2x.jpeg" /></figure><p><a href="https://github.com/microsoft/react-native-code-push">CodePush</a> is a really powerful tool that allows us to update our users quickly with iterative changes, without requiring a Store update.</p><p>CodePush has some limitations (which I won’t get into here) but it also comes with <a href="https://github.com/microsoft/react-native-code-push/blob/master/docs/api-js.md">a lot of configurability</a>, which you may not have dived into.</p><p>We recently made a number of changes to allow us to fine-tune our users experience, as well as make sure they are kept up to date with important (and frequent) changes in our app; <a href="https://www.totallymoney.com/">TotallyMoney</a>.</p><h3>CodePush default behaviour</h3><p>If you follow the setup guides that CodePush provide, you’ll end up with the default setup. This means that users effectively <strong>require two cold starts</strong> to first <em>download/install</em>, then <em>apply/run</em> the latest applicable CodePush update.</p><h3>Why is this not suitable for our users?</h3><p>We release changes frequently. Usually, multiple CodePush changes a day, by multiple missions. These range from new features to bug fixes. As much as we would love our users to engage multiple times a day, our app simply doesn’t lend itself to that kind of usage. So, if users aren’t that frequent, it means they will be much slower to adopt our latest changes, especially if the majority of our updates come via CodePush.</p><p>Ultimately, that means<strong> users aren’t getting the most from our latest features</strong> and we aren’t able to promote those features as freely and as quickly as we would like.</p><h3>How have we managed this until now?</h3><p>Generally, we have leaned quite heavily on Store updates (App Store and Play Store). This involves frequent submissions and releases. Each release takes time to build (even with a lot of automation) and even more time for <em>some</em> Stores to accept them (ehem… Apple). Not all users have automatic updates enabled, and even if they do, there are conditions outside our control that mean we can’t really know when that update will land in our users hands.</p><p><strong>All of those things lead to unpredictability and uncertainty.</strong></p><p>On top of that, there is the “back in time” paradigm that means that a user who <em>was</em> on the latest applicable CodePush version could have their app updated by the operating system to the latest Store (or binary) version that was built <em>before </em>the latest CodePush version meaning they now have <em>technically </em>out of date code until the next (or even previous) CodePush is reapplied, with the Cold start rules we talked about earlier. 🤯</p><h3>What is the ultimate objective of our CodePush changes?</h3><p>We want to <strong>make sure our users receive our updates as soon as possible</strong>. This means two things;</p><ul><li>Change the logic surrounding background checks for CodePush versions to be more assertive.</li><li>Intercept <strong>new</strong> downloads/installs/store-updates to apply the latest applicable CodePush.</li></ul><p>In other words, we need to handle both Cold and Warm starts. Let’s start to look at some coded solutions.</p><h3>First, a <em>really </em>quick win</h3><p>We can swap our default installMode: ON_NEXT_RESTART for installMode: ON_NEXT_SUSPEND and add a minimumBackgroundDuration: 600 // 10 minutes .</p><p>Depending on how you have set up your CodePush (using sync or component wrapping), this will sit in the top-level configuration, something like the one below.</p><pre>import codePush from &#39;react-native-code-push&#39;<br><br>...<br><br>const App = codePush({<br>    checkFrequency: codePush.CheckFrequency.ON_APP_RESUME,<br>    installMode: codePush.InstallMode.ON_NEXT_SUSPEND,<br>    mandatoryInstallMode: codePush.InstallMode.IMMEDIATE,<br>    minimumBackgroundDuration: 600,<br>})(MainAppComponent)<br><br>export default App</pre><p>When the app is “resumed” (comes into the foreground), a check will be made for an applicable CodePush version. If one is found, it will be downloaded to the device immediately. Then, when the user next “suspends” the app for a minimum of 10 minutes, the app will automatically be restarted in the background, with the latest version applied.</p><p>As far as users are concerned, nothing has happened here. For us specifically, this ties into a session timeout so our users would expect to be back to authentication level anyway — which is what happens after the background app restart.</p><p>This does a decent amount of heavy lifting for us, but doesn’t help with the second scenario of new app downloads from their respective stores.</p><h3>Manually managing CodePush</h3><p>CodePush gives us <a href="https://github.com/microsoft/react-native-code-push/blob/master/docs/api-js.md#checkfrequency">a few different options</a> for manually managing how and when different CodePush actions are performed. This gives us complete control. And it’s actually not as technical as you might think.</p><p>To help us with this, I wrote a custom hook that allows us to tap into the CodePush lifecycle events using the <a href="https://github.com/microsoft/react-native-code-push/blob/master/docs/api-js.md#codepushsync">CodePush </a><a href="https://github.com/microsoft/react-native-code-push/blob/master/docs/api-js.md#codepushsync">sync method</a>. This has the added benefit of being able to report usage statistics and drop offs too.</p><p>Let’s dive in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d564e8a937c6ac6fc92c57f518b0217/href">https://medium.com/media/4d564e8a937c6ac6fc92c57f518b0217/href</a></iframe><p>Most of the code there is self-documenting, or commented for convenience. Once you have the hook in place, you can use it wherever is convenient, passing in different configurations if required and listening to the various callbacks and status changes.</p><p><strong>Something important to note; </strong>you need to inform your CodePush component wrapper that you are manually checking for updates, otherwise the two can collide, resulting in failed sync attempts;</p><pre>import codePush from &#39;react-native-code-push&#39;<br><br>...<br><br>const App = codePush({<br>    checkFrequency: codePush.CheckFrequency.MANUAL,<br>})(MainAppComponent)<br><br>export default App</pre><p>With this additional level of control, we can enforce the second part of our requirements; Intercept <strong>new</strong> downloads/installs/store-updates to apply the latest applicable CodePush.</p><h3>Intercepting fresh installations</h3><p>Our setup has a great spot for intercepting <em>and </em>informing the user that an update is occurring. We will call this a “forced update” because our UI doesn’t allow them to continue with the app until they have finished installing*</p><p><em>*We will fine tune this later as that might not always be desirable for our users.</em></p><blockquote>An important distinction; CodePush has a “mandatory” update. This is different to our approach, purely because we control the users experience from start to finish</blockquote><p>We will catch users from a <strong>cold start</strong> after the Splash Screen has finished, seamlessly transitioning to our Installing UI. This gives accurate feedback to the user as to what is happening and that progress is being made.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*b_S1iUMVkSU7Lpg8CwRQ5g.gif" /><figcaption>Example of the Cold Start updating flow</figcaption></figure><p>Let’s take a look at some code.</p><pre>  // bootsplash screen/controller<br><br>  // Use some state to decide when CodePush is done<br>  const [isSetupComplete, setIsSetupComplete] = useState(false)<br>  // Similarly, differentiate between Downloading or not<br>  const [isCodePushDownloading, setIsCodePushDownloading] = useState(false)<br>  // retain Download progress for our UI<br>  const [downloadProgress, setDownloadProgress] = useState(null)<br><br>  const handleCodePushSync = useCodePushSync()<br><br>  useEffect(() =&gt; {<br>    const init = async () =&gt; {<br>      await handleCodePushSync({<br>        syncOptions: {<br>          // We tell the custom hook to immediately apply any update.<br>          // this will cause the app to restart when the update is successful.<br>          installMode: codePush.InstallMode.IMMEDIATE,<br>        },<br>        onDownloadStart: () =&gt; setIsCodePushDownloading(true),<br>        onDownloadProgress: (progress) =&gt; {<br>          setDownloadProgress(<br>            Math.round((progress.receivedBytes / progress.totalBytes) * 100)<br>          )<br>        },<br>        onError: () =&gt; setIsCodePushDownloading(false),<br>      })<br><br>      setIsSetupComplete(true)<br>    }<br>    init()<br>  }, [])</pre><p>The above implementation starts with setting up our custom hook useCodePushSync() and tapping into the lifecycle methods to firstly see if there is a CodePush update to download, then when that download starts and what the progress is of said download. Finally, when the whole sync process has finished, so we can advance the user to the app via an app restart (to apply the new JS bundle).</p><p>Setting some local state in this component, we are easily able to change the UI accordingly, passing in the download progress to a loading bar, for example.</p><h3>Summary</h3><p>The combination of the items above means that we have two different update methods;</p><ul><li><strong>Cold starts/</strong>fresh installations will immediately download and apply any available update.</li><li><strong>Warm starts</strong>/app resume will check for and download an update, applying it at the next possible app suspension (or next Cold start).</li></ul><p>This setup is configurable too — you can change most of the options using the custom hook and tweak it further to your requirements.</p><h3>Bonus reading — Manual CodePush Sync</h3><p>Things get a <em>little </em>more complicated here as we want the option to time out of the forced update for various reasons. For example, if the user is on a bad connection, or they have entered the app from a specific source, or if it’s just taking too long.</p><p>In order to achieve that, I had to manually write the sync function, defining our own lifecycle events to make sure the app wouldn’t suddenly restart at a point in time we weren’t anticipating — this didn’t seem possible with the sync method.</p><p>Following a very similar pattern, with a really similar API, I created the following hook.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fd07941a3774737c5ad99dff12a0f75/href">https://medium.com/media/3fd07941a3774737c5ad99dff12a0f75/href</a></iframe><p>Slightly more advanced usage here allows us to manually decide when to restart the app, bail from an update or continue in a different way with the update — in the background — on the next suspend for example.</p><h3>More summary</h3><p>There are many different ways we can configure CodePush and manually call and intercept the lifecycle methods that should give us a level of granularity to suit all our needs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad152206688" width="1" height="1" alt=""><hr><p><a href="https://medium.com/creating-totallymoney/codepush-in-react-native-3ad152206688">CodePush in React Native</a> was originally published in <a href="https://medium.com/creating-totallymoney">Creating TotallyMoney</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Managing Large Pull Requests]]></title>
            <link>https://medium.com/creating-totallymoney/managing-large-pull-requests-e5ca473dca40?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5ca473dca40</guid>
            <category><![CDATA[pull-request]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Mon, 29 Aug 2022 06:02:09 GMT</pubDate>
            <atom:updated>2022-08-29T06:02:09.895Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*Wu8wWDcXs9Ev1wwrt3J_jA@2x.jpeg" /></figure><p><strong>TL:DR</strong>; I have a <em>main feature branch</em> with everything on it. I can create <em>another, sub-feature </em>branch from main;</p><p>git checkout -b feat-smaller-specific-changes</p><p>then checkout the components/code I want to include in said feature branch directly from the <em>feature main branch;</em></p><p>git checkout origin/main-feature-branch app/component/MySmallComponentForBranch</p><p>That will pull the folder (and it’s content) directly into my <em>new</em> feat-smaller-specific-changes branch.</p><p>I can then commit my changes as normal on my teeny more manageable branch. 🎉</p><p>Code reviews are a really important part of dev workflow at TotallyMoney. In fact, every company I’ve ever worked with is hot on this. Its practical implications mean that you can catch bad code and uphold coding standards and best practices. But above all, it’s one of the best learning opportunities for developers. Developers of all levels can see what their peers are doing, learn new techniques and challenge/question methods adopted. It helps with codebase familiarity and not siloing information.</p><p>In short, <strong>everyone needs to be reviewing code</strong>. To make that more digestible, we encourage our devs to submit smaller Pull Requests*.</p><p>So here’s the scenario; you have a big new feature, it touches lots of the app, you don’t know in advance just how you will break this down for your peers to review. Fear not.</p><p>Create your feature branch as normal — this will be your <em>main feature branch</em>. Do your work… all of it. Don’t get hung up on breaking it down at this stage. When you’re done, take a look at the diff and you’ll more than likely start to see parts of the feature naturally break out. Create a new <em>smaller feature branch</em> from main, specifically named to suit the piece of your feature this covers. Now pull directly the code relative to this <em>smaller feature branch</em> <strong>only</strong>, directly from your <em>main feature branch</em>. git will help you here;</p><ol><li>Push all your changes up to your feature branch<br>- git add --all <br>- git commit -m &quot;add all the things&quot; <br>- git push</li><li>Switch to main<br>- git checkout main</li><li>Create your new sub-feature branch — this will be your bitesized branch<br>- git checkout -b feat-smaller-specific-changes</li><li>Now pull the code you want directly from your original feature branch<br>- git checkout origin/main-feature-branch app/component/MySmallComponentForBranch <br>- [origin/...] this is remote main feature branch<br>- [app/...] this is the path to the file/folder you want in this bitesized branch</li><li>Repeat step 4 with all the paths to folders/files you need</li><li>Commit and push your changes with your branch as you normally would</li></ol><p>That’s it. Your code is more manageable, your colleagues are happy. Your feature is on its way. Well done you 👏</p><p><em>*Not all devs agree with the “smaller is better” approach to PRs — sometimes context around the whole feature is more important than your line count… That’s well worth bearing in mind.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5ca473dca40" width="1" height="1" alt=""><hr><p><a href="https://medium.com/creating-totallymoney/managing-large-pull-requests-e5ca473dca40">Managing Large Pull Requests</a> was originally published in <a href="https://medium.com/creating-totallymoney">Creating TotallyMoney</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Native Dark Mode and Theming]]></title>
            <link>https://javascript.plainenglish.io/react-native-dark-mode-and-theming-dc299bec206d?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc299bec206d</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[dark-mode]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Fri, 01 Nov 2019 10:19:20 GMT</pubDate>
            <atom:updated>2019-11-19T11:35:34.370Z</atom:updated>
            <content:encoded><![CDATA[<p>The new Dark mode in iOS got me all excited. I could use all my favourite apps but now they were Dark 😎. Ok, not that exciting but I think for a lot of people, just a change in the presentation is refreshing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*8tUA-mpXYG-iSr7XFtiw7A.jpeg" /></figure><p>I had to immediately make a few amendments to our application at work, and I also got thinking about how I could roll this feature out to my own applications. Naturally, they both follow a similar pattern when it comes to colours (or colors 🙄) and theming.</p><p>I am going to talk through the approach and setup I have come up with to theming and Dark mode and how this could be adapted to make it even more versatile for users to customise their experience in your app.</p><h3>Current setup</h3><p>Currently, we centralise our colours and theme in one place. For the sake of this article, I will only talk about colours, but of course theming could and probably should contain spacing, font, icon… whatever you want to persist across your application with a certain amount of consistency.</p><pre>/src<br>-- /theme/index.js</pre><p>Right at the root, we have our theme . This is where we store our colours (and everything else that you want to use app-wide). Here is an example of what that looks like;</p><pre>// theme/index.js</pre><pre>const palette = {<br>  palette01: &#39;#000000&#39;,<br>  palette02: &#39;rgba(255,255,255,1)&#39;,<br>}</pre><pre>export const colors = {<br>  paragraphText: palette.palette01,<br>  buttonPrimaryBg: palette.palette02,<br>  headingText: palette.palette01,<br>}</pre><p><em>Why split the palette and the colours? </em>Great question. Well, this way we can define the colours on a more granular level by their use case and reuse from our palette. This makes sure that we aren’t coming up with 50 shades of grey 😏. Sure, we will end up repeating the palette usage throughout the colours, but that doesn’t actually matter and it’s kind of the point. It also means that when it comes to theming, we can either change the palette or the colours individually (or both, if we wanted).</p><p>Just a quick example of how they are used for clarity;</p><pre>// ButtonPrimary/index.js</pre><pre>...</pre><pre>import { colors } from &#39;theme&#39;</pre><pre>const ButtonPrimary = ({ onPress, children }) =&gt; (<br>  &lt;TouchableOpacity onPress={onPress} style={styles}&gt;<br>    {children}<br>  &lt;/TouchableOpacity&gt;<br>)</pre><pre>const styles = {<br>  backgroundColor: colors.buttonPrimaryBg,<br>}</pre><pre>export default ButtonPrimary</pre><p>Nothing exciting going on here, but we do have our theme essentially decoupled from our components themselves. Great start.</p><h3>Dark mode</h3><p>Dark mode is the subject of this short article and is exclusive to iOS, but there are also other theme/UI influencing setups out there for Android like Night Mode. I imagine this will become more common in the future and regardless of a <em>device </em>preference, this same idea could be used to change a users internal settings.</p><p>If you are using <a href="https://docs.expo.io/versions/latest/">Expo</a>, like I am (I really love it… but more on that another time) then you can use <a href="https://www.npmjs.com/package/react-native-appearance">react-native-appearance</a> to listen to the users device preferences. This is currently only for iOS and doesn’t take into account Android, but as per the docs here;</p><blockquote>The Appearance API will likely be available in react-native@&gt;=0.61</blockquote><p>So this should set us up for future use. There are also other modules if you are not using Expo, like <a href="https://www.npmjs.com/package/react-native-dark-mode">react-native-dark-mode</a> that take a similar approach.</p><p>react-native-appearance gives us a couple of ways to work with the users preferences, but the most straight forward and practical to me seems to be the <a href="https://www.npmjs.com/package/react-native-appearance#usage">hooks</a>.</p><p><em>I am not going to get into how to use hooks, but I recommend you </em><a href="https://reactjs.org/docs/hooks-intro.html"><em>take some time to read about them</em></a><em>. They are awesome.</em></p><p>Here is the react-native-appearance hook in use, straight out the docs;</p><pre>...</pre><pre>import { useColorScheme } from &#39;react-native-appearance&#39;</pre><pre>function MyComponent() {</pre><pre>  let colorScheme <strong>=</strong> useColorScheme()</pre><pre><strong>  if</strong> (colorScheme <strong>===</strong> &#39;dark&#39;) {</pre><pre><em>   // render some dark thing</em></pre><pre>  } <strong>else</strong> {</pre><pre><em>  // render some light thing</em></pre><pre>  }</pre><pre>}</pre><p>So if we take our earlier example of a ButtonPrimary , we <em>could </em>do something like this;</p><pre>// ButtonPrimary/index.js</pre><pre>import { useColorScheme } from &#39;react-native-appearance&#39;<br>import { colors } from &#39;theme&#39;</pre><pre>const ButtonPrimary = ({ onPress, children }) =&gt; { <br>const colorScheme = useColorScheme()<br>  return (<br>    &lt;TouchableOpacity <br>      onPress={onPress} <br>      style={{ <br>        backgroundColor: colorScheme === &#39;dark&#39; <br>          ? colors.buttonPrimaryBgDark <br>          : colors.buttonPrimaryBg <br>      }}<br>    &gt;<br>      {children}<br>    &lt;/TouchableOpacity&gt;<br>  )</pre><pre>export default ButtonPrimary</pre><p>I mean… it would work. But it’s not very readable and all that logic around selecting a colour is now in our component and every other component we might want to influence, which with a theme could be most presentational components.</p><p>So it’s not practical. But it is easily fixed.</p><p>I will create my own hook that will <em>use </em>the useColorScheme hook and as well as returning my <em>themed </em>colours. It can also return the colour scheme, should I need it. This will mean a couple of changes to my colors object that we wrote earlier, but nothing too drastic. Looking at that first;</p><pre>// theme/index.js</pre><pre>const palette = {<br>  palette01: &#39;#000000&#39;,<br>  palette02: &#39;rgba(255,255,255,1)&#39;,<br>}</pre><pre>export const colors = {<br>  paragraphText: palette.palette01,<br>  buttonPrimaryBg: palette.palette02,<br>  headingText: palette.palette01,<br>}</pre><pre>export const themedColors = {<br>  default: {<br>    ...colors,<br>  },<br>  light: {<br>    ...colors,<br>  },<br>  dark: {<br>    ...colors,<br>    buttonPrimaryBg: palette.palette01,<br>    paragraphText: palette.palette02,<br>  },<br>}</pre><p>Again, nothing too exciting going on here — just the addition of a new object themedColors this is where we will do the theming. light and default are doing the same thing at the moment, simply spreading in the original colour set, but dark is now having some of those original colours overwritten with a theme specific set (notice how the colours are now inverted for dark vs light .</p><p>Now for the hook.</p><pre>// theme/hooks.js</pre><pre>import { useColorScheme } from &#39;react-native-appearance&#39;</pre><pre>import { themedColors } from &#39;.&#39;</pre><pre>export const useTheme = () =&gt; {<br>  const theme = useColorScheme()</pre><pre>  const colors = theme ? themedColors[theme] : themedColors.default</pre><pre>  return {<br>    colors,<br>    theme,<br>  }<br>}</pre><p>We return the colours and the theme from our custom hook. The colors will already be assigned to the users preferred theme (if it’s available), falling back to the default if nothing is selected or defined.</p><p>Usage of this hook becomes strikingly similar to our original implementation of the ButtonPrimary .</p><pre>// ButtonPrimary/index.js</pre><pre>...</pre><pre>import { useTheme } from &#39;theme/hooks&#39;</pre><pre>const ButtonPrimary = ({ onPress, children }) =&gt; {<br>  const { colors } = useTheme()<br>  return (<br>    &lt;TouchableOpacity <br>      onPress={onPress} <br>      style={{ <br>        backgroundColor: colors.buttonPrimaryBg <br>      }}<br>    &gt;<br>      {children}<br>    &lt;/TouchableOpacity&gt;<br>  )<br>}</pre><pre>export default ButtonPrimary</pre><p>All we need to do is import the custom hook and deconstruct the colours from there, instead of directly from our theme 🎉</p><p>This is scalable and manageable for a big roll out across the whole application.</p><h3>The downside</h3><p>There is always one… we have to write our colour style inline, which is a bit of a bummer. You can still spread in the rest of your styles too if you need to, but it does make it a <em>tiny </em>bit messier. It seems to me that it’s an OK trade off for themed styles throughout.</p><h3>Expanding the example</h3><p>This just shows how to use the users device settings and it’s only limited to iOS. You could expand the hook to include settings from the user with relative ease, meaning a user could decide on their in-app settings to override the device settings.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc299bec206d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/react-native-dark-mode-and-theming-dc299bec206d">React Native Dark Mode and Theming</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CSS Object-fit Fallback]]></title>
            <link>https://medium.com/@alexborton/css-object-fit-fallback-f5b015767433?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5b015767433</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[object-fit]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Tue, 09 May 2017 21:56:00 GMT</pubDate>
            <atom:updated>2017-05-09T21:56:00.779Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was first written 26th of May, 2016 during my time at </em><a href="https://www.superrb.com/news/object-fit-fallback"><em>Superrb</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RDFzaNJ0Aaz1fb_6MEOaHA.jpeg" /></figure><p>The <strong>object-fit</strong> CSS property allows you to define how an image will appear in it&#39;s area. It behaves in much the same way as some of the background image properties, but allows you to use an actual <strong>img</strong>. Unfortunately, there is some <a href="http://caniuse.com/#feat=object-fit"><strong>support limitations</strong></a> with all the IE&#39;s and suprisingly, even Edge have not yet adopted the functionality, with it&#39;s future support also unknown.</p><p>Fortunately, it is fairly straight forward for us to write a neat little Javascript/jQuery fallback combined with <a href="https://modernizr.com/download?setclasses&amp;q=object%20fit"><strong>Modernizr feature detection</strong></a>.</p><p>Assuming you have come across the <strong>object-fit</strong> property by now, i won&#39;t go too far into it&#39;s capabilities, but you can get a <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit"><strong>detailed overview on it here</strong></a>. The main types of <strong>object-fit</strong> we have found really useful are <strong>cover</strong> and <strong>contain</strong>. If you are familiar with the <strong>background-image</strong> types, you will recognise these and have a grasp on how they are output.</p><p>Let’s look at some code. A standard implementation of object-fit might look like this in your CSS;</p><pre><strong>figure {</strong><br><strong>    width: 100%;<br>    height: 400px;<br>}</strong></pre><pre><strong>figure img {<br>    object-fit: cover;<br>    width: 100%;<br>    height: 100%;<br>}</strong></pre><p>And your markup;</p><pre><strong>&lt;figure&gt;<br>    &lt;img alt=&quot;This is an image&quot; src=&quot;/image.jpg&quot;&gt;<br>&lt;/figure&gt;</strong></pre><p>The containing <strong>figure</strong> sets the area and the image always fills it, using a <strong>cover</strong> crop fit-type. If you look at this in IE, the image is stretched around and horrible because <strong>object-fit</strong> is totally ignored. Here we need a fallback.</p><pre><strong>function tkObjectFit() {<br>    $(&#39;img.objFit&#39;).each(function(){<br>        var imgSrc = $(this).attr(&#39;src&#39;);<br>        var fitType = &#39;cover&#39;;<br><br>        if($(this).data(&#39;fit-type&#39;)) {<br>            fitType = $(this).data(&#39;fit-type&#39;);<br>        }<br><br>        $(this).parent().css({ &#39;background&#39; : &#39;transparent url(https://medium.com/&quot;&#39;+imgSrc+&#39;&quot;) no-repeat center center/&#39;+fitType, });<br>        $(this).remove(); });<br>}</strong></pre><p>Let’s walk through what is happening here;</p><ul><li>Loop through all the images with a class of <strong>objFit</strong>.</li><li>Get the <strong>src</strong> of the image to use later</li><li>Set the fitType to <strong>cover</strong> by default</li><li>Test if there is another fit-type required (currently the only alternative is <strong>contain</strong>)</li><li>Add the <strong>background-image</strong> inline css to the parent container, including the fit-type</li><li>Finally, remove the original image</li></ul><p>There are a couple of changes we want to make to our markup so the fallback can loop through any object-fit images;</p><pre><strong>&lt;figure&gt;<br>    &lt;img alt=&quot;Object fit image&quot; src=&quot;/image.jpg&quot; <br>        class=&quot;objFit&quot;<br>        data-fit-type=&quot;cover&quot;&gt;<br>&lt;/figure&gt;</strong></pre><p>The important part is the class on the <strong>img</strong>, the <strong>data-fit-type</strong> is optional and can be totally omitted if you are wanting the <strong>cover</strong> fit type.</p><p>Finally, just call the function if the Modernizr test for object-fit fails.</p><pre><strong>if(!Modernizr.objectfit) {<br>    tkObjectFit();<br>}</strong></pre><p>The fallback assumes some kind of container (usually a <strong>figure</strong>) but could be anything really, as long as it has a <strong>display: block</strong></p><p>Hopefully this will help some people utilise this powerful and dynamic CSS attribute.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5b015767433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[WebP SASS Mixin]]></title>
            <link>https://medium.com/@alexborton/webp-sass-mixin-4341b80030c0?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/4341b80030c0</guid>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[gulp]]></category>
            <category><![CDATA[sass]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webp]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Tue, 09 May 2017 21:55:28 GMT</pubDate>
            <atom:updated>2017-05-09T21:55:28.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1xV7NRfQ_n3_M56RNMY_pQ.jpeg" /></figure><p><em>This article was first written 3rd of March, 2017 during my time at </em><a href="https://www.superrb.com/news/webp-sass-mixin-for-background-images"><em>Superrb</em></a><em>.</em></p><p>You might not have heard of the WebP image format and there is probably a reason for that; it has failed to really take off within (most) mainstream browsers. So why are we even talking about it? Well, the format was <a href="https://developers.google.com/speed/webp/"><strong>developed by Google</strong></a>, and this means that all Chrome browsers do support the format.</p><p>So why do we need <em>another</em> image format? WebP boasts <a href="https://developers.google.com/speed/webp/docs/webp_lossless_alpha_study#results"><strong>really impressive image compression</strong></a> (around 26%) for lossless images. Importantly, it can contain an alpha channel for transparency. This allows us to have a legitimate alternative for PNG images with the potential to save a massive amount in file size. Granted, support at the moment <a href="http://caniuse.com/#feat=webp"><strong>is not great</strong></a>, but the big plus is that Chrome <em>does</em> support the format and it looks like <a href="https://www.cnet.com/news/apple-ios-macos-tests-googles-webp-graphics-to-speed-up-web/"><strong>Safari</strong></a> and <a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1294490"><strong>Firefox</strong></a> support <em>might</em> not be too far away. Modernizr allows us to <a href="https://modernizr.com/download?setclasses&amp;q=Webp"><strong>detect browser support for WebP</strong></a>, so there is no excuse not to give it a shot.</p><p>I decided to write a little SASS mixin for using WebP for structural and background images for a recent build. Let’s take a look.</p><pre><strong>@mixin webp-background($img, <br>    $color: transparent,<br>    $repeat: repeat,<br>    $attachment: scroll,<br>    $position: center,<br>    $size: auto,<br>    $type: ‘.png’) {<br> background: $color url(https://medium.com/%E2%80%98/frontend/img/#{$img}.webp%E2%80%99) $repeat $attachment $position / $size;<br> .no-webp &amp; {<br> background-image: url(https://medium.com/%E2%80%98/frontend/img/#{$img}#{$type}%E2%80%99);<br> }<br>}</strong></pre><p>All the mixin is doing is looking for an image by it’s filename and building it as a background image with the filetype of WebP. If WebP is not supported (as detected by Modernizr), we can fallback to the original filetype. The other settings allow us to build the entire background with all of it’s settings complete (size, original file type, repeat etc.)</p><p>Lets look at how to use the mixin.</p><p><strong>@include webp-background($img: &#39;background-img&#39;);</strong></p><p>This is the basic usage. The only required parameter is the name of the image. Notice there is no file extension as this is applied by our mixin. Based on the settings in our mixin, this will look for <strong>/frontend/img/background-img.webp</strong> for those browsers that can and <strong>/frontend/img/background-img.png </strong>for those that can&#39;t.</p><p>There are plenty of other settings included for you to fine tune for each use or globally with the defaults in the mixin. For example, if you wanted to use a JPG instead, you can pass that file extension through to the mixin;</p><p><strong>@include webp-background($img: &#39;background-img&#39;, $type: &#39;.jpg&#39;);</strong></p><p>This mixin will assume that you have the WebP files converted, which you can do manually, online or build them into your Gulp/Grunt asset compiling process. Let’s have a look at what your gulp task might look like.</p><pre><strong>gulp.task(‘images’, function() {<br> var sink = clone.sink();</strong></pre><pre><strong> return gulp.src(config.img)<br>     // Only optimize changed images<br>    .pipe(plugins.changed(config.dist.img))</strong></pre><pre><strong>    // Imagemin<br>    .pipe(plugins.imagemin({<br>        optimizationLevel: 3,<br>        progressive: true,<br>        svgoPlugins: [{<br>            removeViewBox: false<br>        }]<br>     }))</strong></pre><pre><strong>    .pipe(sink) // clone image<br>    .pipe(webp()) // convert cloned image to WebP<br>    .pipe(sink.tap()) // restore original image</strong></pre><pre><strong>    // Set destination<br>    .pipe(gulp.dest(config.dist.img))</strong></pre><pre><strong>    // Show total size of images<br>    .pipe(plugins.size({ title: ‘images’ }));<br>});</strong></pre><p>This requires the use of gulp-webp and gulp-clone. I can run this function as part of my watch/build and it does all the converting of images for me.</p><p>Ultimately, this means I am able to fit a progressive enhancement into my workflow seamlessly; it’s an all-round win. Hopefully the snippets featured above will get you on track to doing the same.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4341b80030c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optimised and truly responsive images with srcset and sizes]]></title>
            <link>https://medium.com/@alexborton/optimised-and-truly-responsive-images-with-srcset-and-sizes-522835c0ae97?source=rss-54452b006873------2</link>
            <guid isPermaLink="false">https://medium.com/p/522835c0ae97</guid>
            <category><![CDATA[image-optimization]]></category>
            <category><![CDATA[responsive-design]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[srcset]]></category>
            <dc:creator><![CDATA[Alex Borton]]></dc:creator>
            <pubDate>Tue, 09 May 2017 13:23:14 GMT</pubDate>
            <atom:updated>2017-05-09T13:23:44.789Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was first written 3rd of November, 2015 during my time at </em><a href="https://www.superrb.com/news/responsive-images-with-srcset-and-sizes"><em>Superrb</em></a><em>.</em></p><p>Responsive websites are not new anymore. In fact, those sites that aren’t responsive are frowned upon by many, as the usage of mobile and other “smaller than desktop” devices can make up more that 50% of total site traffic.</p><p>We have been making responsive websites for many years now and the one element that has been lagging behind has been the <strong>img</strong> element. By this, we are referring to pixel based pictures, like a photo. Many of our websites are very image heavy, utilising fantastic photography, often displayed at full browser width. The main problem this poses is file size. Without separating out your mobile users to a different version of your website, or using separate background images and not using the <strong>img</strong> element at all, you are left with javascript solutions which can result in double-downloads and excessive content that is not used.</p><h3>Enter srcset and sizes</h3><p>This is actually not that new, but as with anything of this nature, it takes a long time for the <a href="https://html.spec.whatwg.org/multipage/embedded-content.html#attr-img-srcset"><strong>schema to be approved</strong></a> and rolled out and for the <a href="http://caniuse.com/#feat=srcset"><strong>browsers to adopt</strong></a> in a consistent and practical way. The good thing about the <strong>srcset</strong> and <strong>sizes</strong> markup is that you can roll it out as a progressive enhancement without any detrimental side effects and no additional markup, just some new attributes. This means that if the browser is capable, it can make full use - if not, there is no problem at all, you don&#39;t even need<em> </em>to have any javascript fallbacks in place (even <a href="https://github.com/scottjehl/picturefill"><strong>though they do exist</strong></a>).</p><p>The CMS we are now using at Superrb allows us to use powerful image filtering techniques to reference the same image and run it through to the correct resizing rules to be displayed in the right places, at the right sizes.</p><h3>What are srcset and sizes?</h3><p>The <strong>srcset</strong> is exactly what is sounds like; a set of sources for one image. Just as you would add a <strong>src</strong> to an image (a required attribute for any image), you would also include your <strong>srcset</strong>. A <strong>srcset</strong> can include as many images as you like and each image is accompanied by it&#39;s original width in pixels, represented with a <strong>w</strong>*.</p><p>The <strong>sizes</strong>, again, is fairly self explanitory. It defines the sizes at which the image will be displayed on screen. This can contain fixed widths or media queries, or a combination of both. And again, can have multiple declarations.</p><p>When the <strong>srcset</strong> and <strong>sizes</strong> are combined, something really smart happens; the browser itself can decide which image to display. They can take into account the browser width, pixel density download speed and any images that may have already been cached, in order to determine which of the images you have specified will be best for this particular serving. Think of the <strong>srcset</strong> and <strong>sizes</strong> as guidelines for the browser as to how the image will be displayed and the browser does all the thinking as to what should be displayed. A little bit like magic.</p><h3>The code in practice</h3><p>Lets get to it and take a look at a bit of markup and read through what is going on here.</p><pre><strong>&lt;img alt=&quot;This is our image alternative text&quot;<br>     src=&quot;image.jpg&quot;<br>     srcset=&quot;image-smallest.jpg 719w,<br>             image-medium.jpg 1019w,<br>             image.jpg 1400w&quot;<br>     sizes=&quot;100vw&quot;&gt;</strong></pre><p>The first thing to notice is that this is regular markup for an <strong>img</strong>, all it has is some extra attributes.</p><ul><li><strong>srcset</strong>. This is a comma separated list of image paths followed width in pixels and a <strong>w</strong> to indicate this*.</li><li><strong>sizes</strong>.<strong> </strong>Another comma separated list of widths that the image will be displayed at. There is just one definition in this example that tells the browser what size the image is displayed at. In this case, we are saying that the image will always be 100% of the viewport width (<strong>vw</strong>). You could also use <strong>px </strong>or <strong>em</strong> here to define your measurement value.</li></ul><p>Often with responsive designs, the content stacks and displays differently on different viewport widths. For example, we might want to dispay 2 of these items next to each other on tablet and 3 on desktop. This means the width of the image would change relating to the viewport, depending on the size. So how would be tell the browser this is the case? Take a look at the code below.</p><pre><strong>&lt;img alt=&quot;This is our image alternative text&quot;<br>     src=&quot;image.jpg&quot;<br>     srcset=&quot;image-smallest.jpg 719w,<br>             image-medium.jpg 1019w,<br>             image.jpg 1400w&quot;<br>     sizes=&quot;(min-width: 1020px) 33.33vw, (min-width: 720px) 50vw, 100vw&quot;&gt;</strong></pre><p>If you are familiar with media queries in CSS (and you really should be by now!), you will recognise exactly what is happening here. Lets break it down.</p><ul><li>The <strong>srcset</strong> has not changed as we are using the same set of images at the same widths.</li><li>The <strong>sizes</strong> now defines two extra break points. At a minimum width of 720px (our tablet break point), the image will be 50% of the viewport. At 1020px, the image will be 33.33% of the viewport.</li></ul><p>So with this intelligent specification, the browser can make an informed decision as to what image will be served; that might not necessarily mean the largest image on the largest browser width.</p><p>The <strong>vw </strong>measurement is a handy one, but not always totally practical if you have gutters and borders to take into account. Although you don&#39;t have to be totally accurate with the sizes you are defining in the sizes attribute, it will help to be as close as possible - the more info you can provide, the better. Let&#39;s look at this final example taken straight from the new Superrb site image page part.</p><pre><strong>&lt;img alt=&quot;This is our image alternative text&quot;<br>     src=&quot;image.jpg&quot;<br>     srcset=&quot;image-smallest.jpg 719w,<br>             image-medium.jpg 1019w,<br>             image.jpg 1400w&quot;<br>     sizes=&quot;(min-width: 1600px) 1224px, (min-width: 1020px) calc(100vw - 140px), (min-width: 720px) calc(100vw - 90px), calc(100vw - 60px)&quot;&gt;</strong></pre><p>This image will always be “full width”, but in the case of the Superrb site, there are various gutters and borders and a maximum width to take into account. Now we can use the <strong>calc()</strong> definition in our attribute to allow the browser to figure some stuff out totally on the fly. With the same <strong>srcset</strong>, our <strong>sizes</strong> here says the following;</p><ul><li>By default, the image will be 100% the viewport width, minus 60px (30px of gutter and border off each side).</li><li>At tablet portrait, the gutters get a bit bigger; 90px total.</li><li>At tablet landscape/small desktop; 140px total.</li><li>Finally, when we get to 1600px (largest desktop), the whole website container will be capped and the image won’t get any wider than 1224px.</li></ul><p>One final thing to note in all the examples is that the <strong>src </strong>is always set. This is required, not only for a fallback for those dummy browsers (Edge, i&#39;m talking to you. Expect <a href="http://caniuse.com/#feat=srcset"><strong>full support in the next release</strong></a>), but for valid markup; we don&#39;t want to break anything here and we don&#39;t need to either. We have chosen to use the full size image as the default. This might not be appropriate in all cases as you could serve a 1400px image on a 640px device. You could introduce another image size of <em>image-largest.jpg</em> for example at the full 1400px and reduce the original to 1000px to allow you to bridge the gap a little better.</p><h3>*The w (width) value</h3><p>No doubt you will take some time to look into the <strong>srcset</strong> and <strong>sizes</strong> attributes a little further (here is some <a href="https://responsiveimages.org/"><strong>good reading</strong></a>) and you will come across another sizing value of <strong>x</strong>. This works slightly differently and the reason it is ommitted from this article is because I have yet to find a reason to use it over the <strong>w</strong> measurement. The <strong>x</strong> measurement is read as multiple and refers directly to pixel density. <strong>2x </strong>or <strong>3x </strong>for example for more dense screens so that no image quality is lost. You would also use this measurement without the <strong>sizes</strong> attribute. I think this was implemented slightly earlier than <strong>w</strong> and before the <strong>sizes</strong> attribute and tends to be used with the element. It doesn&#39;t seem to be as &quot;smart&quot; as the <strong>sizes</strong>and <strong>w</strong> measurement.</p><h3>To conclude</h3><p>The use of the <strong>srcset </strong>and <strong>sizes</strong> attributes on your images is a really clean, smart way to optimize for the future (and current) web. You can do this today (there really is no reason not to) and find great support throughout the best browsers. Chrome will even tell you which image is being served in the inspector. If you open up your network tab in Safari, Chrome or Firefox and reload your page with the screen width set to small, you can see exactly which image is downloaded and your jaw may hit the ground as you realise the bandwidth and total page size you are saving.</p><p>The only drawback I can truly see with this is the need to save multiple versions of the same image. This could be very time consuming, but if you have a modern CMS, you might well have this capability just a few lines of code away.</p><p>Keep your designers happy with blistering image quality and your dev line manager satisfied with minimal load time and bandwidth usage, but it’s the client that wins ultimately with literally the best of both (all) worlds.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=522835c0ae97" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>