<?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 George Griffiths on Medium]]></title>
        <description><![CDATA[Stories by George Griffiths on Medium]]></description>
        <link>https://medium.com/@griffadev?source=rss-354dacf0b321------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*q4wK4M1HIOu0M3br9G47HA.jpeg</url>
            <title>Stories by George Griffiths on Medium</title>
            <link>https://medium.com/@griffadev?source=rss-354dacf0b321------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:18:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@griffadev/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[How trip yourself up with React hooks and break production]]></title>
            <link>https://griffadev.medium.com/how-trip-yourself-up-with-react-hooks-and-break-production-8c9117f7c5e1?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c9117f7c5e1</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 10:10:34 GMT</pubDate>
            <atom:updated>2022-01-10T12:27:34.793Z</atom:updated>
            <content:encoded><![CDATA[<h4>Recently I started working in a new React codebase, here is a story of how I “corrected” some hooks code and broke a feature in production.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a0Gl_74mK33JI_v0BCzccg.png" /><figcaption>A snippet of some problem code I’ll talk about today</figcaption></figure><p>React is so ubiquitous now it’s pretty difficult to avoid it if you want to be employed and working in Web application development. React hooks in some ways pushed the ecosystem forward but in other ways have made React applications harder to debug and easier to subtly break things without realising, if you stop following the rules.</p><p>In this article is a story and some lessons about how I “corrected” some React code to follow the “rules” of hooks and broke the feature because the existing code happened to violate some of the other React “rules”, in a way that was not immediately obvious.</p><h3>Writing about React is scary</h3><p>Whenever I write a React article I question whether or not it is a good idea to do so because with its popularity can come some unhelpful comments and responses. To get this out of the way early here some replies on some previous comments I’ve received on React articles:</p><ul><li>“Your team just wrote sloppy react code. End of story.” — I’d hate to work on a team with this person, jeez.</li><li>“React is NOT a framework, it’s a JavaScript library.” — I call it a framework just because it annoys people, for some reason, and I will continue to do so.</li><li>“This is just an opinion piece” — ????? It’s a blog post?</li></ul><p>Anyways… to the article, I promise the above is the only sarcastic/cynical part of the post and I think that there is some useful learning in this story to help me grow and hopefully others can find it useful to when working with the React framework.</p><h3>The scenario</h3><p>The codebase that I work on is not open source, however the issue that I ran into could be extracted distilled into some example code as the core problems with the code centre around using some of the built in React hooks such as ‘useMemo’ and handling the mutation of state.</p><p>To demonstrate the problem I developed a completely unoriginal Todo-list example, hopefully the mundaneness of the code will help to skip over the boring bits and get to the issues with the code more quickly!</p><p>To demonstrate the problem with the code I have developed 3 examples all implementing the same Todo application:</p><ul><li>one with the original implementation “before” I refactored and broke it</li><li>one with my refactor which broke the code in a specific way</li><li>one with the changes I’d probably make in addition to my original refactor to fix the code.</li></ul><blockquote><em>Full code examples will be available at the end of each section.</em></blockquote><p>In order to reproduce the bug I experienced in the other codebase I needed the following:</p><ul><li>Some code to add some state from some data from the “server”</li><li>React Context API (Technically optional)</li><li>use of useMemo to transform some data from the “server”</li><li>A button to “save” the state to the server</li><li>Some optimisation logic to check if we should submit the changes to the server or not.</li></ul><h3>Implementation</h3><p>The implementation of the TodoList isn’t too important, I scaffolded it out using V<a href="https://vitejs.dev/">ite</a>. The important aspects of the code in this article live inside of a custom <a href="https://reactjs.org/docs/context.html">Context</a> provider that implements the functionality of the TodoList.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0311a76f37fbd46293425d47375d0d4/href">https://medium.com/media/e0311a76f37fbd46293425d47375d0d4/href</a></iframe><p>The TodoProvider is where we will focus on this article, it allows me to implement the logic for adding/deleting and saving todo items and share this between components.</p><p>Each of the components use aspects of the context provided by TodoProvider, for example, here is how the AddTodo component accesses the functionality to add a todo item:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d36029384f519f4c7338e592870f5a8a/href">https://medium.com/media/d36029384f519f4c7338e592870f5a8a/href</a></iframe><p>I’ll add in full code sandbox links at the end of each section.</p><h3>The original implementation</h3><blockquote><em>Remember, this code is not the actual code from the codebase that I work on but is an example distilled from the issue that I came across.</em></blockquote><p>The first thing that the TodoProvider does is fetch some data from the &quot;server&quot;, in this case I&#39;ve hardcoded a json file with some todo items in it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0af931cece5f7b97058f523f2cfc0958/href">https://medium.com/media/0af931cece5f7b97058f523f2cfc0958/href</a></iframe><p>Below I setup a context and fetch the JSON. It might seem odd to you that I am setting the API response into useState, this is a little contrived and just for the demo, before I get any &quot;your code sucks comments&quot;. In the case of the real codebase this would have been a graphql useQuery hook.</p><p>There is a good reason why I am storing the response and not the the TODOs themselves, because I need to do a transform on the data and this is the closest way I could mimic was the original code was doing without introducing some fancy http client hook like <a href="https://www.npmjs.com/package/react-query">react-query</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0d66c3636ec42c5042a656c129bbc86/href">https://medium.com/media/f0d66c3636ec42c5042a656c129bbc86/href</a></iframe><p>The second part of the code uses useCallback to create a function that converts the array of items into a map of todo items where the key is the id e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df1ea807ab6a8799453b6c1ea23733e5/href">https://medium.com/media/df1ea807ab6a8799453b6c1ea23733e5/href</a></iframe><p>If you think the use of useCallback here is strange and useMemo would make sense, we both had the same thought and I wonder if you would end up introducing the same bug that I did by refactoring and correcting the code!</p><p>Now we’re fetching Todo Items we want a way of adding new items. Before we do that I’m going to introduce a new concept to the above implementation, the notion of “draft todos”, these are modified or new todo items which have not been saved back to the server just yet. To make that happen I add in:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91fad8782234df2cd16a818eb3f94ccb/href">https://medium.com/media/91fad8782234df2cd16a818eb3f94ccb/href</a></iframe><p>The purpose of the useEffect is so that on initialisation the draft todos equal the existing todo items.</p><p>In the new lines, if it wasn’t clear before, hopefully it would be now that useCallback here is quite strange indeed because in order to read the existing you need to execute the existingTodos as a function.</p><blockquote><em>The keen eyed here will notice that this means a new map is being created each time you call the function, resetting the data back to the initial state from the json file. This also means the reference to the </em><em>Map is different each time meaning unless you pass the output of the function around you aren&#39;t comparing the same map! This is key to the issue later on when </em><em>useMemo is used instead!</em></blockquote><h3>Adding and removing Todo items</h3><p>These next two lines are more or less the existing code which was in place to add or remove items, and were exported onto the context.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5789759bfaabdb892521ed429a89d953/href">https://medium.com/media/5789759bfaabdb892521ed429a89d953/href</a></iframe><p>These code examples also looked a little off to me too, but I couldn’t quite understand why or put two and two together, at first. What the code is doing:</p><ul><li>Adding or Removing item from todo list</li><li>Making a new Map with the entries from the previous map and setting it to the state.</li></ul><p>There was in fact a comment next to the new Map() line which mentioned that this is needed in order to cause React to update, but it hadn&#39;t quite clicked with me that this was a bit of a problem.</p><p>If you hadn’t noticed already, the lines above were mutating the previous map in both the add and remove methods, and then making a copy of it, polluting the previous data. Without any other changes this might not be a big deal at all, a bit bad in terms of best practice of not mutating objects in React, especially those used as state, but it works, but now let’s take a look at the code for saving the new items.</p><h3>Saving items to the “server”</h3><p>The code below is quite contrived and is missing the context as to why it was needed. But what the code does is check if the data had changed before sending it, it was a bit of an optimisation and there were other reasons too, but that’s not important, let’s take a look.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cedd13210625c5e5e5ff1d610cb3dbef/href">https://medium.com/media/cedd13210625c5e5e5ff1d610cb3dbef/href</a></iframe><p>Most of the above code doesn’t matter but the general idea is that the two maps are being compared to one another. Here again strikes the existingTodos() which as we established before essentially &quot;resets&quot; the Map back to the original data from the server. It is in fact this property of code with the useCallback ensuring that existingTodos() is the original data from the server that makes this code work at all because the add and remove operations mutate the original array. If it wasn&#39;t for existingTodos() always fetching the un-mutated data the code would not function!</p><p>I suggest that this is an extremely obscure bug that only happens to not presents itself because of the use of useCallback to expose a function negates the mutation operations on the original map, instead of useMemo for example. Sadly, for me, I didn&#39;t notice this at the time... and I refactored it.</p><p>I’ve published a <a href="https://codesandbox.io/s/react-hooks-with-usecallback-and-mutations-pmmij">code-sandbox</a> with the full code for this example that uses useCallback.</p><h3>How I broke production</h3><p>As suggested to earlier, when working in this area of the code I took the chance to tidy up the code to use useMemo instead of useCallback. Unfortunately, this made the code fall over, and to make things even more fun I was going on vacation later that week, luckily someone in my team came in and reverted back to using useCallback, hopefully I&#39;ll be able to make the change to make the code less of a trap with the mutation of the Maps when I return, which I&#39;ll discuss at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ads1CbRXyglJKzG2osoisw.png" /><figcaption>A diff of the changes made (note the diff is the wrong way around red is new code on left)</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5477094ef71841a30d4ecf6e43b42876/href">https://medium.com/media/5477094ef71841a30d4ecf6e43b42876/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdc622d8c74019ba008519bbe5f14c8b/href">https://medium.com/media/cdc622d8c74019ba008519bbe5f14c8b/href</a></iframe><p>This change got through testing and code review, and was seemingly correct. However, due to the mutating of the original Map in the add/remove functions (which I’d missed), the first time you added or deleted something it would not be tracked as a change, meaning if you only added or removed one item in the list the request would not be sent to the server because the entries in the existingTodos had been mutated making the Maps essentially equal (not in terms of reference but contents, which is what the server cared about).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*OWFk_u4Ie4DzdfpHBBKkmQ.gif" /><figcaption>Here&#39;s the bug in action!</figcaption></figure><p>Here is a <a href="https://codesandbox.io/s/use-memo-broken-code-with-mutations-lqk1u?file=/src/TodoContext.jsx">code-sandbox</a> with the full code and demo that introduces the bug.</p><blockquote><em>Note that the checking and unchecking of items in the demo does not have an issue with mutating the original Map.</em></blockquote><h3>Missed in testing</h3><p>As noted above the issue where changes are incorrectly not reported only appears for the first change. The reason being that if you make two changes the code happens to work (sort of) because the array set by useMemo in this example never changes after its been mutated the one time, but the code for adding or removing items will stop modifying the original Map after the first mutation, instead it uses the latest draft todos map. Incidentally, the real testing scenario was a bit more complex and involved reordering items, so you might be able to see how this scenario could get missed.</p><p>This would be incredibly difficult to unit test as well, with the code being split across contexts and multiple components, unless you were testing the full end to end interactions you might not catch this at all!</p><h3>My suggested fix</h3><p>The fix for the code is straight-forward and goes back to the original highlighted issue, the add and remove functions mutating the original map, they should not do this. Alternatively before setting the existing entries to the draftTodos variable you could make a copy then, either would work, although I think I prefer avoiding mutations at the point of new data - in the add and remove functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56ffd9f52f7ba9a1da7a382693481f40/href">https://medium.com/media/56ffd9f52f7ba9a1da7a382693481f40/href</a></iframe><p>Here is a <a href="https://codesandbox.io/s/working-todo-list-with-usememo-ns4px">code-sandbox</a> of what I believe is functional code.</p><h3>Learnings</h3><p>I suppose one of the main lessons here is to always be aware of where code could potentially be mutating state, especially before introducing something like a useMemo into the code base.</p><p>More importantly, when refactoring code from an uncommon pattern (the useCallback) to something more typical it’s important to fully understand why that code might have happened in the first place, it’s likely it might be a workaround for another issue. Another learning on my part is that this would had made good sense to start a dialogue with the person who wrote the original code, although that’s easy to say in retrospect, there are many contributors.</p><p>Perhaps code comments might have saved this or some more unit tests, it’s hard to say. I can say for sure that we did do lots of testing in this area before shipping the bug to production but I suppose because it’s a bug that only happens on the first mutation and fixes itself if you do subsequent changes that might help to explain why it was missed. It’s possible that some end to end test automation of this functionality might have caught this, as it seems likely that a human tester would go for the more complex scenario over a more basic test, e.g. a single mutation which might be present in an automated test.</p><p>Variable names can lie, the name of the variable also had the word existing in it in the other codebase too making it seem like this variable reference was representative of the original unmodified state, but due to the mutations it was not. I suppose it&#39;s a learning that you cannot always trust that a variable is what is says it is.</p><p>Maybe just don’t useMemo or useCallback or things that complicate the code — the work this component was doing to convert an array into a map, and ensure it wasn’t happening every render could well be redundant or overkill, part of my issue with react hooks is they can force you to introduce complexity for something as simple as converting from one data type to another and in doing this you can get struck by subtle bugs such as code mutating objects incorrectly or the incorrect use of react hooks ghastly dependency arrays.</p><h3>Summary</h3><p>I suppose some people might read this and have the take that you should simply “Get Gud”, but I’d suggest to take a step back and think about how ubiquitous React is and how many developers of differing experience can be working on a code base, I think it’s examples like this which help to show that it’s super easy to break things by modifying to use a different React hook or mutating something that should not have been mutated, and no Typescript can’t save you here, this was a Typescript codebase!</p><p>It might also be a fair argument to suggest that the bug presented here is not React specific, but I can say for sure the complexity that React can bring just to avoid rendering, or not rendering, does not help.</p><p>If you want to read about another instance of discussing bugs and areas of growth, I wrote about another scenario here from my previous role: <a href="https://griffadev.medium.com/memory-leaks-and-why-should-you-never-write-such-bad-code-even-for-tests-334cad6f98b2">Memory leaks and why should you never write such bad code.</a></p><p>Thank you for reading! If you want to read more of my work, please follow me on Medium or on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>, or get me a <a href="https://ko-fi.com/griffadev">coffee</a> if you feel like it ☕.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c9117f7c5e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensure your site automatically updates in future!]]></title>
            <link>https://griffadev.medium.com/ensure-the-copyright-year-on-your-site-automatically-updates-in-future-f99c1ea8fd7?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/f99c1ea8fd7</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[html]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Sat, 01 Jan 2022 13:46:00 GMT</pubDate>
            <atom:updated>2022-01-07T18:48:27.134Z</atom:updated>
            <content:encoded><![CDATA[<h4>If you are using a static site generator you might want to have some static content that periodically updates, such as a year, let’s see how you can automate it!</h4><p>Every year you probably want to ensure your copyright header on your site(s) is up to date, if you manage lots of sites you will want to automate this!</p><figure><img alt="Out of date copyright header." src="https://cdn-images-1.medium.com/max/992/1*S3GbMaf_yWuRvWMxAZb3Sw.png" /><figcaption>Out of date copyright header</figcaption></figure><h3>To solve this you might want to periodically build your website on Netlify (or similar), the answer isn’t that straight forward and some tools (Github Actions) have gotchas.</h3><p><strong>Another use case:</strong> I recently launched a re-write of my brothers Guitar teaching business website: <a href="https://www.cgguitar.co.uk/">cgguitar.co.uk</a>, during this rewrite I implemented a feature where I wanted to fetch <a href="https://griffadev.medium.com/adding-dynamic-content-from-an-api-to-a-static-website-at-build-time-1e086e696442">YouTube playlists at build time.</a></p><p>To achieve my goals, I wanted to scheduled builds of my Netlify website periodically. Netlify doesn’t have this feature built in, however what Netlify does have is a ‘webhook’ which you can call trigger to your build.</p><p>In this post I offer two ways to trigger this build, using Github Actions or CircleCI. Using Github Actions can have a significant downside, depending on the use case, continue read to find more about that!</p><h4>Finding your build hook in Netlify</h4><p>Login to Netlify and navigate to your site settings and local the “Build &amp; deploy” section, your build hook will be in there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*V-APkv1GqnoKHfQE.png" /><figcaption>Netlify build hook</figcaption></figure><p>You can test this out by making a curl request in your terminal, you should see it trigger your Netlify website build:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6037c0a4be4024578f4e3c4f70d6525/href">https://medium.com/media/e6037c0a4be4024578f4e3c4f70d6525/href</a></iframe><blockquote>Important: Ensure you keep <em>NETLIFY_BUILD_HOOK_TOKEN</em> secret, otherwise anyone can call your build and potentially cause you to go over your build quota.</blockquote><h4>Can Github Actions do this?</h4><p>Github actions let you perform continuous integration in Github, they seem like a perfect fit here…</p><p>In your Github repository, in the following folder .github/workflows, you could create:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f1facb92bd63a79666629ac14bd3476/href">https://medium.com/media/5f1facb92bd63a79666629ac14bd3476/href</a></iframe><p>The above configuration will run every day at around 15:00.</p><p>You will want to secure your build_hook token in a secret on Github.</p><p>I did this originally and thought job done right? Well, not quite.</p><blockquote>Github Actions are disabled on projects after 60 days if there is no activity on the repository, meaning bye bye scheduled builds.</blockquote><p>The above limitation might be okay, depending on your use case, but for my case where I wanted to make sure I was fetching the latest videos from a YouTube playlist, this was no good because the website’s code itself may not be updating very often, but there may be new videos added.</p><h4>Using CircleCI instead</h4><p>One alternative to Github actions is to use CircleCI to do this instead, it has a generous free tier too so there should be no charge for this.</p><p>You can create a configuration like this:</p><ul><li>Create a folder in your Git repository called .circleci</li><li>Create a file called config.yml</li></ul><p>Populate the config.yml with something like the following (you can use a different image if you wish). This will build every day at 3PM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6a58e61ea99e7887c93f8f01804210f/href">https://medium.com/media/b6a58e61ea99e7887c93f8f01804210f/href</a></iframe><p>Now you can create a project in CircleCI and you should be able to test your build. NETLIFY_BUILD_HOOK_TOKEN will need to be set as an environment variable, in a similar way to Github, in the setting of CircleCI for your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mA4CPUKe5NvNGKmV.png" /><figcaption>CircleCI scheduled build</figcaption></figure><p>I posted a full article here about how to pull data from the YouTube API periodically to embed dynamic YouTube playlists without needing to expose your API key to the client: <a href="https://griffadev.medium.com/adding-dynamic-content-from-an-api-to-a-static-website-at-build-time-1e086e696442">https://griffadev.medium.com/adding-dynamic-content-from-an-api-to-a-static-website-at-build-time-1e086e696442</a></p><p>If you want to read more of my work, please follow me on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>, or get me a <a href="https://ko-fi.com/griffadev">coffee</a> if you feel like it ☕.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f99c1ea8fd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beautiful drag and drop interactions with react hooks]]></title>
            <link>https://griffadev.medium.com/beautiful-drag-and-drop-interactions-with-react-hooks-9689d945856d?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/9689d945856d</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Sun, 19 Dec 2021 22:43:10 GMT</pubDate>
            <atom:updated>2021-12-20T11:47:31.916Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we’ll explore how you could build a drag and drop sortable table using @dnd-kit and react-table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tr1MmR01eLgAM7LZkJL4kw.png" /><figcaption>Drag and drop table using react-table and dnd-kit.</figcaption></figure><p>Drag and drop table using react-table and dnd-kit.</p><p>When looking for drag and drop libraries in React there are a lot of options, some of the popular ones are:</p><p>Many of the libraries out there are great but some come with some large downsides, namely:</p><ul><li>Are intended for specific use-cases or are too restrictive.</li><li>Have a large dependency tree, for example some bundle in redux!</li><li>Have inconsistent browser support.</li></ul><p>One common thing also brought up when looking at these libraries is those that opt to “use the platform” more by utilising the HTML drag and drop APIs and those that deliberately choose to not use it to overcome browser inconsistencies and help improve support for a variety of inputs such as touch, mouse and keyboard.</p><p>As part of this investigation I seriously considered react-beautiful-dnd, whilst it has great support and demos, I hit a few stumbling blocks along to way. It&#39;s <a href="https://bundlephobia.com/package/react-beautiful-dnd@13.1.0">footprint</a> was also a hard sell to add into the application for a single use-case. I also encountered <a href="https://github.com/atlassian/react-beautiful-dnd/issues/316">this issue</a> whilst I was investigating a different use case where I wanted horizontal and vertical re-ordering in a grid.</p><p>After trying out some other libraries I eventually settled on @dnd-kit, which I have to say is absolutely fantastic. It is technically still in beta, but despite this its documentation is quite mature. On the <a href="https://docs.dndkit.com/">docs</a> site it says the following:</p><blockquote><em>dnd kit is currently in beta. Issues and bugs should be expected for early releases. The core concepts are stable, but some of the APIs may change in the future.</em></blockquote><h3>So why is this library great?</h3><p>It is a lightweight, hooks-based, utility driven library which gives you helpful primitives and allows you to opt in for additional features, therefore making the library only as large as your use case requires it be, depending on what you need.</p><p>The easiest way to get started I think is to work through some of the code in some of their code <a href="https://codesandbox.io/examples/package/@dnd-kit/core">sandbox demos</a>. I’m personally a big fan of the <a href="https://codesandbox.io/s/py6ve">sortable image grid example</a>, try breaking down the code to see how things work.</p><p>The first step to using dnd-kit is to install the packages you need. The library is separated into small micro-libraries, which each provide additional utilities.<br> The minimum you will require is the package@dnd-kit/core (~11KB gzipped).</p><p>Some other useful packages with dnd-kit provides:</p><ul><li>@dnd-kit/sortable - building blocks to build sortable interfaces .(~3KB gzipped)</li><li>@dnd-kit/utilities - dnd-kit utilities to help with integration. (~1.3KB gzipped)</li><li>@dnd-kit/modifiers - modifiers to change behavior of drag and drop, for example restricting the drag and drop movement to vertical or horizontal. (~3.4KB gzipped)</li><li>@dnd-kit/accessibility - Hooks to assist with accessibility for example screen reader announcements. (~499B gzipped)</li></ul><h3>Webpack problems</h3><p>Note, in my use I found that webpack had some issues de-duplicating @dnd-kit/core which is used inside of @dnd-kit/sortable. Aside from adding to bloat, if this dependency is not de-duplicated the DndContext provided by dnd-kit will not work. If you run into this you can force it use the same copy of the core library, using an alias in your webpack.config.js.</p><pre>resolve: { <br> alias: { <br> <br> &quot;@dnd-kit/core&quot; : path. resolve (__dirname, &quot;node_modules/@dnd-kit/core&quot; ) , <br> } <br> }</pre><h3>Learning dnd-kit</h3><p>The best way that I can recommend to understand the library before we get to the example using react-table is to take a look at the example I mentioned earlier ( <a href="https://codesandbox.io/s/py6ve">sortable image grid example</a>).</p><p>One thing to highlight that is important and quite cool about the library is its DragOverlay component, which you can use to render a custom react component to visualise your dragged item differently when it is being dragged, for example adding a drop shadow, which you&#39;ll notice in my sortable table example a little later. It also offers you the opportunity to change how the original rendered item is rendered when it is being dragged by using the isDragging property from useSortable (or useDraggable), for example change it&#39;s opacity or color to help indicate the drop area to the user, this is also shown in my up-coming example.</p><p>If you prefer to learn through videos, whilst learning the API I watched some of this video before getting my hands stuck into the code.</p><h3>What could be better?</h3><p>The library has some really fantastic examples of how to use it on its <a href="https://5fc05e08a4a65d0021ae0bf2-unebtvimdp.chromatic.com/">storybook</a>, however they do suffer from the classic problem that storybook often presents, they are great as showcases but not very good at demonstrations of how to adapt the example to use the code for yourself. By that I mean, it’s very hard to find and understand the code written, and often suffers from the problem of “too much code re-use for demos”, although if i’m honest I think this is a problem with Storybook not the library itself.</p><p>For example, it’s really hard to un-pick what the code in the example is doing, you end up having to search through github and reverse engineer complex examples and across multiple files, for example:</p><p>The other thing that makes me sad is that this great library is locked into the React ecosystem, but I must admit, the ergonomics of using custom hooks here is quite nice.</p><h3>Using react table</h3><p><a href="https://www.npmjs.com/package/react-table">react-table</a> is another lightweight and customisable react library, it allows users to use utilities and hooks to build up tables for their UIs. This description may sounds quite similar to what I described before about dnd-kit where you can use a series of utilities and hooks to implement drag and drop. It is for this reason that react-table and dnd-kit fit together really nicely.</p><p>To help demonstrate this, I took the “basic” example of react-table from their examples here: <a href="https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic">https://codesandbox.io/s/github/tannerlinsley/react-table/tree/master/examples/basic</a> and then added in drag and drop support, let&#39;s have a look how.</p><h3>Hooking it up</h3><p>In order to add support there are roughly these steps:</p><ul><li>Install the dnd-kit packages: @dnd-kit/core, @dnd-kit/modifiers, @dnd-kit/sortable, @dnd-kit/utilities.</li><li>Wrap the table in DndContext and SortableContext.</li><li>Provide an array of string item ids to SortableContext to allow items to be sorted.</li><li>Implement drag event handlers for re-ordering items in the array.</li><li>Render a row using the useSortable hook passing in the id of the row.</li><li>Render a drag handle button component.</li><li>Render the CSS transform of the row when dragging.</li><li>Rendering the DragOverlay for a custom view of the row when dragging.</li><li>When a row is being dragged change it’s background color and hide the data, using the isDragging property, to act as a &quot;slot&quot; for the user to drop into.</li></ul><p>Here is an implementation of how you could go about doing drag and drop re-orderable rows with dnd-kit and react-table: <a href="https://codesandbox.io/s/react-table-drag-and-drop-sort-rows-with-dnd-kit-btpy9">https://codesandbox.io/s/react-table-drag-and-drop-sort-rows-with-dnd-kit-btpy9</a></p><p>This example isn’t really focused on making it look “pretty”, it needs lots of styling to make it more production ready but hopefully you get the idea.</p><p>One really important thing that is missing in the example is custom screen reader messages for accessibility, you will want to do this to help make sure that your application is inclusive of everybody. There is a great example on the <a href="https://docs.dndkit.com/guides/accessibility">dnd-kit accessibility page</a>.</p><p>I’m excited to explore difference uses for this library, once you get the hang of it it’s really powerful!</p><p>Thank you for reading! If you want to read more of my work, please follow me on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>, or get me a <a href="https://ko-fi.com/griffadev">coffee</a> if you feel like it ☕.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9689d945856d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Just a friendly reminder that React isn’t really Just JavaScript (Don’t nest Functional Components)]]></title>
            <link>https://griffadev.medium.com/just-a-friendly-reminder-that-react-isnt-really-just-javascript-don-t-nest-functional-components-a6a822dddd?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6a822dddd</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Sun, 07 Nov 2021 13:37:21 GMT</pubDate>
            <atom:updated>2022-01-10T17:56:02.447Z</atom:updated>
            <content:encoded><![CDATA[<p>This is my first blog post I’ve written about React, despite reluctantly using it every day due to the UK frontend job market. I’ll probably regret talking about such a popular Framework, oh and it is a Framework 😉.</p><p>Recently, I was writing an animated slide-in sidebar component, which could be opened to reveal some additional details for another component in the page. One of my goals was to ensure that the tab and focus order of the page made sense when the details pane was opened, namely, I wanted to be able to “steal” focus on open and restore focus back to the original button on close. For example on button press (with space-bar) you should be able to open the details panel, have the panel but focused and close it again with the space-bar. Focus is then returned back to the original button and you can hit “tab” to move to the next item.</p><p>Here is a simplified example of what I was building, with some HTTP Status code kitties, try it out for yourself over in <a href="https://codesandbox.io/s/http-status-cats-working-8tr1l?file=/src/App.jsx">this Code sandbox</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*f7NFS7xiscPsGrHzfUPV4g.gif" /><figcaption>Animation showing using the keyboard and focus state to open and close a panel</figcaption></figure><p>Here is the code for the App, this was hastily written HTML which i’m sure could do with being improved.</p><pre>import &quot;./styles.css&quot;;<br>import { useState } from &quot;react&quot;;<br>import { Sidebar } from &quot;./Sidebar&quot;;<br>export default function App() {<br>  const statusCodes = [500, 404, 403, 401, 418, 420, 301, 302, 200, 201, 204];<br>  const [selectedCode, setSelectedCode] = useState(null);</pre><pre>  const Codes = (<br>    &lt;ul&gt;<br>      {statusCodes.map((code) =&gt; (<br>        &lt;li key={code}&gt;<br>          &lt;button onClick={() =&gt; setSelectedCode(code)}&gt;{code}&lt;/button&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  );</pre><pre>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;h1&gt;HTTP Status Cats&lt;/h1&gt;<br>      {Codes}<br>      &lt;Sidebar<br>        onClose={() =&gt; setSelectedCode(null)}<br>        ariaLabel={`${selectedCode} status code info`}<br>        open={Boolean(selectedCode)}<br>      &gt;<br>        &lt;h2&gt;{selectedCode}&lt;/h2&gt;<br>        &lt;img<br>          alt={`Cat demonstrating HTTP status code: ${selectedCode}`}<br>          src={`https://http.cat/${selectedCode}.jpg`}<br>        /&gt;<br>      &lt;/Sidebar&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>And the sidebar, which is where the “focus stealing/restoring” happens:</p><pre>import { useEffect, useRef, useState } from &quot;react&quot;;</pre><pre>export const Sidebar = ({ ariaLabel, open, onClose, children }) =&gt; {<br>  const [previousFocus, setPreviousFocus] = useState();<br>  // now focus inside something, for arguments sake, the close button<br>  const closeBtnRef = useRef(null);<br>  useEffect(() =&gt; {<br>    if (open) {<br>      setPreviousFocus(document.activeElement);<br>      closeBtnRef?.current?.focus();<br>    }<br>    // bit of a hack putting aria label in here so triggers if another option selected.<br>  }, [open, ariaLabel, closeBtnRef]);</pre><pre>  return (<br>    &lt;aside aria-label={ariaLabel} aria-hidden={open ? &quot;false&quot; : &quot;true&quot;}&gt;<br>      &lt;button<br>        disabled={!open}<br>        ref={closeBtnRef}<br>        onClick={() =&gt; {<br>          // restore previous focus<br>          previousFocus?.focus();<br>          onClose();<br>        }}<br>      &gt;<br>        Close X<br>      &lt;/button&gt;<br>      {open &amp;&amp; children}<br>    &lt;/aside&gt;<br>  );<br>};</pre><p>This code was working correctly, and then I was working on another pr based on a branch with new changes that I pulled in and I noticed that the focus navigation had started failing.</p><blockquote><em>Actually, a unit test, which tested the focus interactions started failing which is actually pretty awesome! React Testing Library moved unit testing forward SO MUCH in comparison to Enzyme it’s great. If it could only run by default inside a browser instead of Jest, that would be great. By default I mean, commonplace in the industry, i’m sure it’s achievable.</em></blockquote><p>In my example above the new PR had added the equivalent of the Codes variable which is in the above snippet:</p><pre>const Codes = (<br>  &lt;ul&gt;<br>    {statusCodes.map((code) =&gt; (<br>      &lt;li key={code}&gt;<br>        &lt;button onClick={() =&gt; setSelectedCode(code)}&gt;{code}&lt;/button&gt;<br>      &lt;/li&gt;<br>    ))}<br>  &lt;/ul&gt;<br>);</pre><pre>&lt;h1&gt;HTTP Status Cats&lt;/h1&gt;;<br>{<br>  Codes;<br>}</pre><p>Except, that wasn’t what was added, this was:</p><pre>const Codes = () =&gt; (<br>  &lt;ul&gt;<br>    {statusCodes.map((code) =&gt; (<br>      &lt;li key={code}&gt;<br>        &lt;button onClick={() =&gt; setSelectedCode(code)}&gt;{code}&lt;/button&gt;<br>      &lt;/li&gt;<br>    ))}<br>  &lt;/ul&gt;<br>);</pre><pre>&lt;h1&gt;HTTP Status Cats&lt;/h1&gt;;<br>{<br>  &lt;Codes /&gt;;<br>}</pre><p>The difference is very subtle, but very important, what had been added by making Codes a function was a functional React component nested inside of another functional component. Remember Codes was a variable inside of App. This is the sort of thing which can easily not get picked up in code review but it breaks a lot of things.</p><p>Here is a broken example: <a href="https://codesandbox.io/s/http-status-cats-broken-fiu72?file=/src/App.jsx:508-554">https://codesandbox.io/s/http-status-cats-broken-fiu72?file=/src/App.jsx:508-554</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*FMkVtveamTH5EymzBl__Xw.gif" /><figcaption>Animation showing broken focus on close of the panel</figcaption></figure><p>What’s going on here is React is rendering the contents of the “App” component on each render and because the inner component is not memoized or anyway react is just throwing it in the bin and re-rendering. Internally this will be causing the DOM element to be removed and re-added thus breaking the focus state being returned to the original button.</p><p>Seeing this in the code, it was a non obvious fix, especially when reviewing another persons code, it got me thinking on some things:</p><ul><li>Would we have even caught this if we didn’t have good tests?</li><li>Would we have ever found the cause of it months later when the code wasn’t as fresh in the mind?</li><li>If React is “Just Javascript” how come it so royally breaks one of JavaScript best features of nesting functions and creating closures.</li><li>Why isn’t this front and centre of React docs and default lint rules?</li></ul><p>I did some digging on the last two points:</p><p>The only reference to nested functions that I could find in the official documentation comes from the old classic <a href="https://reactjs.org/docs/hooks-rules.html">“Rules of Hooks”</a> page: Don’t call Hooks inside loops, conditions, or nested functions, no mention of nested components though.</p><blockquote><em>As an aside, I love the the fact that the mechanism that React is now mostly entirely based on, “hooks”, requires a list of rules to help prevent you from writing “Just JavaScript”.</em></blockquote><p>As for a lint rules, there does appear to be one which you can turn on in the popular eslint-plugin-react - <a href="https://github.com/yannickcr/eslint-plugin-react/blob/HEAD/docs/rules/no-unstable-nested-components.md">no-unstable-nested-components</a>, maybe i&#39;ll suggest to my team that we do. I can&#39;t think of a good reason when you would want to nest functional component, even if you&#39;re getting fancy and using useMemo, surely you&#39;d just be better off writing simpler code.</p><p>I find it fun to think that such a tiny change in the code that looks so innocent can break quite a lot in the rendering of React components and something I learnt from this is i’m really going to do my best to make sure I write good sets of unit tests that test both “interactions” and “accessibility” as it’s so easy for these things to regress!</p><p>If you enjoyed this, you might also be interested in reading:</p><p><a href="https://griffadev.medium.com/how-trip-yourself-up-with-react-hooks-and-break-production-8c9117f7c5e1">How trip yourself up with React hooks and break production</a></p><p>Thank you for reading! If you want to read more of my work, please follow me on Medium or Twitter <a href="https://twitter.com/griffadev">@griffadev</a>, or get me a <a href="https://ko-fi.com/griffadev">coffee</a> if you feel like it ☕.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6a822dddd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building progress indicator cards with a single css property]]></title>
            <link>https://griffadev.medium.com/building-progress-indicator-cards-with-a-single-css-property-77cc07bb6178?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/77cc07bb6178</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Wed, 20 Oct 2021 11:17:29 GMT</pubDate>
            <atom:updated>2021-10-20T11:17:29.923Z</atom:updated>
            <content:encoded><![CDATA[<h4>I recently had to implement an indicator of progress onto a card component, I challenged myself to see if this could be done with a single css property, here’s how.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iNGgG-fPDLRmUkmM.jpeg" /><figcaption>Image of progress cards html component</figcaption></figure><p>Here is a full demo of the css which I’ll show you how to build, by learning the structure of the css background shorthand property.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fembed%2Fpreview%2FRwZRBeJ%3Fdefault-tabs%3Dcss%252Cresult%26height%3D600%26host%3Dhttps%253A%252F%252Fcodepen.io%26slug-hash%3DRwZRBeJ&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fpen%2FRwZRBeJ&amp;image=https%3A%2F%2Fassets.codepen.io%2F5583571%2Finternal%2Fscreenshots%2Fpens%2FRwZRBeJ.default.png%3Ffit%3Dcover%26amp%3Bformat%3Dauto%26amp%3Bha%3Dfalse%26amp%3Bheight%3D360%26amp%3Bquality%3D75%26amp%3Bv%3D2%26amp%3Bversion%3D1634679177%26amp%3Bwidth%3D640&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/74fca4186855fbb95a94680093c5e23b/href">https://medium.com/media/74fca4186855fbb95a94680093c5e23b/href</a></iframe><p>Before today I’ve always shied away from full understanding all of the shorthand property capability that is baked into the background attribute but today i&#39;m going to change that, let&#39;s work it out together, let&#39;s deconstruct this bit of css that constructs the progress indicator card together:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e18be6d607d260502dbbd7be55ed4a46/href">https://medium.com/media/e18be6d607d260502dbbd7be55ed4a46/href</a></iframe><p>You might be thinking, why do this with a single css property? You could just do this with multiple css properties or html elements, heck even the built in meter html element. These things are all true however there may be some cases where just manipulating a single css property to create effects like this is handy:</p><ul><li>You’re in a design system and you can only change the background property.</li><li>You’re in some system where you are unable to modify the HTML.</li><li>It’s fun.</li></ul><h4>Breaking down the css background property</h4><p>Prior to experimenting to create this effect i’d never really gone into too much detail about the capabilities of the background property in css, but it is really quite fantastic! The fact that you can apply multiple backgrounds and their properties using a single css property is very powerful and not something i’d really appreciated before.</p><p>To understand css snippet from above it would probably be a good idea to expand into using the non-shorthand background properties, to help understand and breakdown what’s going on above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd5d976d77e315b94aaebdd846bb95df/href">https://medium.com/media/bd5d976d77e315b94aaebdd846bb95df/href</a></iframe><p>is equivalent to:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9f0501e6a9c71c1f5bda7d09f985802/href">https://medium.com/media/e9f0501e6a9c71c1f5bda7d09f985802/href</a></iframe><p>What is going on is that we have two backgrounds:</p><ul><li>a linear-gradient which starts off green #65ad60, moving to the right and at 30% turns into light cream #faebd1.</li><li>a block sand-like color of #ffdc9b.</li></ul><p>Note how we are separating the background with a comma ,. The same is done for background-size. background-repeat has just one value because I want the same value for each background, but I could have done background-repeat: no-repeat, no-repeat.</p><p>For the background-size property we first have width, followed by height. So the first background size says a width of 100% and a height of 10% which gives us the height of the progress bar. The no-repeat is important, without it the background would just duplicate itself until it filled 100% of the image, as repeat is the default. It&#39;s probably useful to note that you may have multiple background images too, which can be an image url or a gradient.</p><h4>Converting to shorthand</h4><p>To convert the background-image, background-color, background-size and background-repeat to the shorthand background it&#39;s similar to the long form properties. There is a slightly different syntax for background-size as you also need to account for background-position which is a property which I have omitted from my long hand, it would be something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d50e7625883c95a86ad6c258984c8f6/href">https://medium.com/media/2d50e7625883c95a86ad6c258984c8f6/href</a></iframe><p>In order to specify the background-size when using the background shorthand you must also specify the position, to do this you separate the position and the size with a forward-slash /.</p><p>For example, here is the first of the backgrounds:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f5dd89034179b4934ecdc77f84be15ef/href">https://medium.com/media/f5dd89034179b4934ecdc77f84be15ef/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97ede2531a4f4627b99f04632e4011ca/href">https://medium.com/media/97ede2531a4f4627b99f04632e4011ca/href</a></iframe><p>Whilst writing this article I came across <a href="https://shrthnd.volume7.io/">this handy website</a> that generates the shorthand for you, test it out with the above css, you should get a single background property generated for you!</p><blockquote>Internally it looks like this website uses this package: <a href="https://github.com/frankmarineau/shrthnd.js.">https://github.com/frankmarineau/shrthnd.js.</a></blockquote><p>Hopefully you can now see how we got to the final css, by adding in thebackground-color and position values after a comma ,.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/579fd023604ea9706e0c65b4e51f3f65/href">https://medium.com/media/579fd023604ea9706e0c65b4e51f3f65/href</a></iframe><p>There is a lot more to the css background property, as always, your best bet for research is <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background">MDN</a>.</p><h4>Spicy CSS Custom properties</h4><p>Now we’ve had a play with the background property, let’s see if we can make the css a little more useful, by introducing css custom properties we now have the possibility of re-using the same css with different values for percentage “progress”, or changing the background colors.</p><blockquote>If you are new to CSS Custom properties Kevin Powell does a great introduction over <a href="https://www.youtube.com/watch?v=PHO6TBq_auI">here</a>.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da799cb4f25eefc24888b973b6f8bbc5/href">https://medium.com/media/da799cb4f25eefc24888b973b6f8bbc5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c3d7017e12485d51965e16ca1bac1c1/href">https://medium.com/media/9c3d7017e12485d51965e16ca1bac1c1/href</a></iframe><p>Hopefully you can see how you can change the look of each “card” just by modifying the css custom property for that card only.</p><p>Here is a live demo of the html and css: <a href="https://codepen.io/georgegriff/pen/RwZRBeJ">https://codepen.io/georgegriff/pen/RwZRBeJ</a></p><h4>Make it a component</h4><p>You could next choose to create a re-usable component, for example a Web Component, that could set the css custom properties and add appropriate aria attributes.</p><p>It’s important to note that this css-based progress indicator is purely decoration, you will want to ensure that users with screen readers are able to understand what the component is conveying, using aria attributes in your HTML, or appropriate text labels.</p><blockquote>You can learn about ARIA basics on MDN <a href="https://developer.mozilla.org/en-US/docs/Learn/Accessibility/WAI-ARIA_basics">here</a>.</blockquote><p>Thank you for reading! If you want to read more of my work, please follow me on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>, or get me a <a href="https://ko-fi.com/griffadev">coffee</a> if you feel like it ☕.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77cc07bb6178" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding dynamic content from an API to a static website at build time]]></title>
            <link>https://griffadev.medium.com/adding-dynamic-content-from-an-api-to-a-static-website-at-build-time-1e086e696442?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e086e696442</guid>
            <category><![CDATA[eleventy]]></category>
            <category><![CDATA[11ty]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Wed, 23 Jun 2021 16:22:08 GMT</pubDate>
            <atom:updated>2021-06-23T16:24:49.820Z</atom:updated>
            <content:encoded><![CDATA[<h4>You may not need client side JavaScript to add dynamic content from an API. In this article I will show the approach I recently took to embed YouTube playlists into an website created by a static site generator (Elventy), and how this approach lends itself to less JavaScript and progressive enhancement.</h4><p>I recently launched a re-write of my brothers Guitar teaching business website: <a href="https://www.cgguitar.co.uk/">cgguitar.co.uk</a>, during this rewrite I had some guiding principles which I believe are best practices when building any website:</p><ul><li>Use the right tool for the job. You don’t need a metric-ton of JavaScript for most websites minimum user experiences.</li><li>Provide a great baseline experience with No JavaScript whatsoever.</li><li>Limit the number of calls to external services to keep the page load fast.</li></ul><p>In this post I’ll describe my approach to getting embedded YouTube playlist content into the website, at build time, reducing the number calls to YouTube client side to only the embedded video and thumbnails, no calls out to the YouTube Data API. In addition to this, i’ll show you how you can keep the site up to date with easy to configure cron jobs (scheduled builds).</p><p>The feature that I built, that I will explain, is an embedded YouTube playlist component which fetches all the data and stats for YouTube playlists at build time and renders their video metadata/thumbnails directly into the HTML. You can check out the feature live over at <a href="https://www.cgguitar.co.uk/videos/#guitar-lessons">https://www.cgguitar.co.uk/videos/#guitar-lessons</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ng--S6qiNacOAXoI.png" /><figcaption>Embedded YouTube Playlists in the CG Guitar website</figcaption></figure><h4>The problem with client side</h4><p>Calling out to external APIs/services from your client side JavaScript can introduce you many problems, to name a few:</p><p><strong>Security</strong> — if you want to hide your token or keep it secure you either have to:</p><ul><li>Ensure your token only works on your websites domain, but this doesn’t stop people using it from outside of a web browser.</li><li>Add some complex proxy set up where you hide the token on a server you manage, requires having a server or proxy configuration.</li></ul><p><strong>Rate limiting/charges</strong> — most APIs have limits to the number of API calls you can make, or will start charging you for usage:</p><ul><li>Your website content doesn’t scale, each visitor would be using your token to call the external services for every visit.</li><li>You could end up incurring accidental charges!</li></ul><p><strong>JavaScript needed</strong> — In order to show the data you want to show to user, you need to serve JavaScript to your users:</p><ul><li>Depending on Network speed or the amount of JavaScript on the page the user has to wait for the JS to download before seeing any content.</li><li>A user may choose to disable JavaScript.</li><li>JavaScript may fail to load entirely, rendering a useless experience to users.</li></ul><h4>Moving your calls to external APIs to build time</h4><p>This is approach is not a silver bullet, not every feature would support this, e.g. if you want to work with user submitted content. However, if all you are showing is content that changes infrequently, moving the data fetching to build time can be a really great solution.</p><p>The static site I built for my brothers’ business uses <a href="https://11ty.dev/">Eleventy</a>, a fantastic static site generator. I wrote about getting started with 11ty in<a href="https://griffadev.medium.com/how-i-got-started-with-11ty-190f321d1028"> How I got started with 11ty.</a></p><p>The next section will assume some knowledge about 11ty, or static site generators in general.</p><p>11ty has a plugin called <a href="https://www.11ty.dev/docs/plugins/cache/">@11ty/eleventy-cache-assets</a> which you can use to fetch any data you like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ce3b0bba604bb74c8a1af2e8733a3a6/href">https://medium.com/media/1ce3b0bba604bb74c8a1af2e8733a3a6/href</a></iframe><p>The awesome thing about this plugin is that once the data is fetched it is cached so future local builds do not have to re-fetch data, meaning your builds can remain lightning fast which is a common characteristic of any 11ty project.</p><h4>Embedding YouTube playlists at build time</h4><p>For my feature I decided I wanted to be able to pick and choose which YouTube playlists that I wanted to show in the website, it is however possible to fetch all YouTube playlists for an account too. I wanted to be able to choose so that I could add, order and describe new playlists in my CMS (Netlify CMS).</p><p>The playlists in the website are defined as markdown in the code in a folder named <a href="https://github.com/Georgegriff/cgguitar-site/tree/main/src/playlists">playlists</a>, Netlify CMS is configured to <a href="https://github.com/Georgegriff/cgguitar-site/blob/178a8ae66a4b22f4566dfe579b748369abf0f297/admin/config.yml#L649">read these files</a> e.g:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79cb721a2e7b98874cdf32812a3680f3/href">https://medium.com/media/79cb721a2e7b98874cdf32812a3680f3/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/0*MotuHqKdZfng9C1g.png" /><figcaption>Netlify CMS showing defined playlists</figcaption></figure><p>The first step to getting my playlists into 11ty is to define them as a collection, to do this inside of the src/playlists folder I create a <a href="https://github.com/Georgegriff/cgguitar-site/blob/main/src/playlists/playlists.json">playlists.json</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a1c5d382576edd6cd6f66bf1739bb2f/href">https://medium.com/media/8a1c5d382576edd6cd6f66bf1739bb2f/href</a></iframe><p>This creates an 11ty collection of all of the playlists, with their “id”, “name” and “descriptions”.</p><p>Inside of my videos page I can then work with this collection in my Nunjucks template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c738a25d7c7dd54bdd19928a58541f41/href">https://medium.com/media/c738a25d7c7dd54bdd19928a58541f41/href</a></iframe><blockquote>If you are unfamiliar with template languages in 11ty you can read about them over <a href="https://www.11ty.dev/docs/templates/">here</a>.</blockquote><p>I’ll show what partials/video-playlist.njk is later on in the article.</p><p>fetchYouTubePlaylists is where the magic happens and where we will start to use @11ty/eleventy-cache-assets. This is an 11ty filter which is defined in my .eleventy.js config file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e716c861d7969c6c5653a5c31d43ff9/href">https://medium.com/media/4e716c861d7969c6c5653a5c31d43ff9/href</a></iframe><p>Let’s take a dive a layer deeper: getPlaylists is making a call to getPlaylistItem which is where i&#39;m actually doing the data caching.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd2c7ce35a5b926a94aa1fa749d3aa3/href">https://medium.com/media/5fd2c7ce35a5b926a94aa1fa749d3aa3/href</a></iframe><p>This function is looping through all of my playlists and fetching the items (videos) in that playlist. It is also adding the name, description and direct link to YouTube for the whole playlist.</p><p>Now for getPlaylistItem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cbd09f1a0352db2e9f41ce8b6b3c418/href">https://medium.com/media/5cbd09f1a0352db2e9f41ce8b6b3c418/href</a></iframe><p>The first few things this function does is:</p><ul><li>Set base url for YouTube API: <a href="https://www.googleapis.com/youtube/v3/playlistItems">https://www.googleapis.com/youtube/v3/playlistItems</a></li><li>Set the max number of items in a playlist to return on a page</li><li>Pass in APIKey and build up url in accordance with the <a href="https://developers.google.com/youtube/v3/docs/playlistItems/list">API Docs</a>.</li></ul><blockquote>You will want to store your API key as an environment variable e.g. const apiKey = process.env.YT_API_KEY;. For production you can add this environment variable where ever you choose to build/host the site e.g. on Netlify.</blockquote><p>Next up it fetches some extra metadata. fetchMetaInfo fetches things like view count and likes, this is another API call which we would be concerned about if this was client side, but since it&#39;s build time, who cares! Implementation available on <a href="https://github.com/Georgegriff/cgguitar-site/blob/178a8ae66a4b22f4566dfe579b748369abf0f297/src/_filters/youtube.js#L57">Github</a>.</p><p>Finally i’m looping through all the data and returning an array of videos for each playlist and a flag hasMore if the playlist has more than then 20 items shown. In my HTML when I see this flag I add an link out to YouTube to watch the full playlist.</p><p>The above code a modified version of the original, where i’m doing a a few extra things you can checkout the full version on <a href="https://github.com/Georgegriff/cgguitar-site/blob/178a8ae66a4b22f4566dfe579b748369abf0f297/src/_filters/youtube.js#L6">Github</a>.</p><h4>Progressive Enhancement</h4><p>Now I have the website fetching the external data, let’s see how I could approach displaying the content in the HTML.</p><p>When designing an dynamic experience its a good idea to think about what is the minimal experience you can provide without needing JavaScript, and build from there. You could start out very simply and just load a link &lt;a&gt; to the YouTube videos, perhaps the thumbnail could open a tab to YouTube, this needs no JS at all, and is what I did:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81a2fcaeb3422aa1c387df8b5d388a4f/href">https://medium.com/media/81a2fcaeb3422aa1c387df8b5d388a4f/href</a></iframe><p>You will see that i’m wrapping the whole code in a youtube-playlist Custom Element. When the component loads without JavaScript it is just a link out to YouTube, which is then upgraded to a full playlist experience. This will disable the default &quot;link&quot; behavior too.</p><p>I’m not going to go into the implementation of my Web Component in this post but you can check out the source code on <a href="https://github.com/Georgegriff/cgguitar-site/blob/178a8ae66a4b22f4566dfe579b748369abf0f297/src/scripts/components/youtube-playlist/YoutubePlaylist.js">Github</a>. The general idea is to consume &lt;li&gt; list items as child content inside of my &lt;youtube-playlist&gt; and when JavaScript loads move this content in the Shadow DOM, and make them look pretty/interactive.</p><p>Here is my full Nunjucks template for my html:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ef3feab3dacb66b9b4f9bf9bafffb3f/href">https://medium.com/media/7ef3feab3dacb66b9b4f9bf9bafffb3f/href</a></iframe><p>Using Web Components like this is a perfect way of enhancing a base HTML experience with limited JavaScript.</p><h4>Periodically building your website</h4><p>In order to keep the YouTube playlists up to date I want to be able to build the website every day on schedule.</p><p>There are many options when it comes to periodically building a website, I wrote about my approach to doing this in:<a href="https://griffadev.medium.com/scheduled-builds-a-for-website-on-netlify-c3ba95b9ecec"> Scheduling builds on Netlify</a>. In brief, I opted to use Circle CI to call my Netlify build hook every day at 3 PM. I tried Github Actions but there is a major limitation to using an Action for this use case, which I go into in the linked article.</p><h4>Summary</h4><p>I hope this article was helpful and you can see some of the advantages to moving dynamic content that changes infrequently to be rendered at build time.</p><p>If you want to read more of my work, please follow me on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>, or get me a <a href="https://ko-fi.com/griffadev">coffee</a> if you feel like it ☕.</p><p>Write Medium in Markdown? Try <a href="https://markdium.dev/">Markdium</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e086e696442" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Natural language search for blog posts using TensorflowJS]]></title>
            <link>https://griffadev.medium.com/natural-language-search-for-blog-posts-using-tensorflowjs-3dad21585a60?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dad21585a60</guid>
            <category><![CDATA[tensorflow]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tensorflowjs]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Thu, 22 Apr 2021 14:31:05 GMT</pubDate>
            <atom:updated>2021-04-22T15:19:19.133Z</atom:updated>
            <content:encoded><![CDATA[<h4>I’ve been learning TensorflowJS and Machine Learning, as an experiment, I thought I would implement a search across my current blog posts using sentence similarity on natural language, running in the browser.</h4><p>In this post i’ll go into how you can get started using pre-trained Tensorflow models to do Machine learning in the browser, examine some of the potential gotchas, such as not blocking the main thread with custom logic and consider the impact of the size of models on UX.</p><p>The demo that I developed as part of this article is a “search engine” using my blog posts as a data set, which I converted into an API, the idea being: can I find blog posts based on a search query by a user, by comparing the similarity of the query with a blog posts title and description?</p><p>Search is a solved problem and there are better ways of achieving the same thing, but I created this to learn and to have a bit of fun!</p><p>If you want to check out a live demo for what I built in this post, I’ve <a href="https://griffa.dev/experiments/natural-language-search/">hosted it on my website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MJ6HNetnxH6UPUojkGXGHA.png" /><figcaption>Screen capture of demo of Natural language post search</figcaption></figure><h4>Sentence similarity with TensorflowJS</h4><p>I’m going to explain how this all works with a smaller example rather than the full demo that I linked earlier, but the source code for the example is available on <a href="https://github.com/Georgegriff/griffadev/tree/main/src/experiments/natural-language-search">Github</a>, it’s the same code, just with things like UI simplified.</p><p>First up, let’s load in the library we are going to use. We’re just going to load them from a CDN, when you’re just experimenting, you don’t want to be messing around with build processes.</p><p>Create a HTML file called index.html, with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/299b683ad00dcd22727405ebb6f38fc5/href">https://medium.com/media/299b683ad00dcd22727405ebb6f38fc5/href</a></iframe><p>We’re loading in two libraries here, the first is TensorflowJS and the second is a the Universal Sentence Encoder model, which uses TensforflowJS, you can read about <a href="https://github.com/tensorflow/tfjs-models/tree/master/universal-sentence-encoder">over here</a>.</p><blockquote>If you want to code along, host your files on a local dev server. I personally recommend the <a href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer">Live Server VS Code extension</a>.</blockquote><p>Next, create index.js add the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60cda5a8ccb2bfbd824a68c127b0c1a7/href">https://medium.com/media/60cda5a8ccb2bfbd824a68c127b0c1a7/href</a></iframe><blockquote>In Chrome, and other browsers soon, you won’t need to wrap the code in an IIFE because you could use <a href="https://caniuse.com/?search=top%20level%20await">top level await instead</a>.</blockquote><p>This code is loading the model, and then passing our userQuery of &quot;Sharing to social media&quot; and our array of blogPosts into the model. Doing this converts the sentences into vectors (arrays) with 512 entries in the vector for each sentence, this is how the model sees the sentence. Universal sentence encoder has been trained on a large vocabulary and is encoding the provided data based on the data it saw during training.</p><p>To help make this a bit clearer, blogPostsTensor and userInputTensor will be an instance of <a href="https://js.tensorflow.org/api/latest/#tensor2d">tensor2d</a>. These are 2D arrays (on the GPU) with 512 entries in each of the arrays, which represents a provided phase.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d16052eb98edcf66d7ef61eaa85f9871/href">https://medium.com/media/d16052eb98edcf66d7ef61eaa85f9871/href</a></iframe><p>Next, in order to find potentially good results based our input sentence we need to check how similar our input vector is to the vectors of the blog post titles, we can achieve this by calculating Cosine Similarity between the vectors, which will give us a value between -1 and 1. 1 being most similar and -1 being not very similar at all.</p><p>I’m not going to explain the mathematics of cosine similarity, but i’ve provided an implementation of it. If you want to know how it works, there are lots of great explanations on YouTube, <a href="https://www.youtube.com/watch?v=5lvS8078ykA">such as this one.</a>.</p><p>Define these at the top of your index.js file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef38e844baf6ebdb2191e72a1daee177/href">https://medium.com/media/ef38e844baf6ebdb2191e72a1daee177/href</a></iframe><p>I tried to implement this maths purely in TensorflowJS, so that I could take advantage of the GPU, but after much trial and error, I could not find a solution. If anyone knows how to do this I’d love to hear about it. Doing this calculation myself is performing a large tradeoff of having these calculations happen on the main thread, which can cause bad UX, i’ll explain this in more detail towards the end of the post, including ways around this.</p><p>Now lets use the functions in our code,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37a9a49307fdb6e46b1bd8dbcc01faf2/href">https://medium.com/media/37a9a49307fdb6e46b1bd8dbcc01faf2/href</a></iframe><p>On the last line of the above example we’re updating the text of an element with id “initial-example-results”, to make this work, let’s add the following to your html file, inside the &lt;body&gt; tag.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9550849f67533682d538c87f439538a3/href">https://medium.com/media/9550849f67533682d538c87f439538a3/href</a></iframe><p>Here’s a link to the code we’ve built so far: <a href="https://codesandbox.io/s/tensorflow-js-hardcoded-blog-search-0q5o9">https://codesandbox.io/s/tensorflow-js-hardcoded-blog-search-0q5o9</a></p><h4>Turning posts into an API</h4><p>My blog is written using the static site generator tool Eleventy. If you haven’t heard of <a href="https://www.11ty.dev/">Eleventy</a> and you’re into building fast websites, seriously check it out, it’s awesome. I’m not going to explain how Eleventy works, but I wrote a post about how <a href="https://griffa.dev/posts/how-i-got-started-with-11ty/">I got started with Eleventy</a>.</p><p>To create an API out of my blog posts I generate a JSON file in the form of a <a href="https://jsonfeed.org/">JSON Feed</a>, which can be hosted on my server.</p><p>Here’s my template for my json feed, this template is based on the <a href="https://github.com/11ty/eleventy-base-blog">11ty base blog</a>. The templating syntax being used is Nunjucks, and comes supported out of the box with Eleventy.</p><p>If you are curious and want to check out the source code of my blog it’s over here on <a href="https://github.com/Georgegriff/griffadev">Github</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5936e3da315f6aa20fdf78c616514a47/href">https://medium.com/media/5936e3da315f6aa20fdf78c616514a47/href</a></iframe><p>This template is iterating through my blog posts and populating a JSON array with post data, as well as some other site metadata, ultimately the result is a JSON file which i can request on my server: <a href="https://griffa.dev/feed/feed.json.">https://griffa.dev/feed/feed.json.</a></p><p>Now I have an API which I can use in my search, success!</p><p>We can now update our code sample to pull data from this api instead of hard-coding it. Add this function to the top of “index.js”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/68aee7f18f8d529cf2efe71eeadb55e2/href">https://medium.com/media/68aee7f18f8d529cf2efe71eeadb55e2/href</a></iframe><p>Replace the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0fcb463cc1da039c3fbb1af97a9c829f/href">https://medium.com/media/0fcb463cc1da039c3fbb1af97a9c829f/href</a></iframe><p>with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3196a92961e9ab2707037ce56e474dfb/href">https://medium.com/media/3196a92961e9ab2707037ce56e474dfb/href</a></iframe><p>Also replace</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/029b795161ed85a0d471d905d453b89f/href">https://medium.com/media/029b795161ed85a0d471d905d453b89f/href</a></iframe><p>with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f35ca77ed5bcd75c7191e535b2715826/href">https://medium.com/media/f35ca77ed5bcd75c7191e535b2715826/href</a></iframe><p>Here’s a link to the code we’ve built so far: <a href="https://codesandbox.io/s/tensorflow-js-blog-search-3k7x2">https://codesandbox.io/s/tensorflow-js-blog-search-3k7x2</a></p><h4>ML in the browser, why?</h4><p>Hopefully the examples so far have made sense, I thought i’d take a moment to talk about some of benefits and tradeoffs of doing Machine learning in the browser with TensorflowJS.</p><p>One of the first things you might think of when you think Machine learning in JavaScript is it’s slow, well that’s where one of the great things about TensorflowJS comes in, it performs all of its expensive calculations on the GPU, under the hood it’s utilising WebGL shader programs to achieve this.</p><p>Running Machine learning in the browser opens up the possibilities of offering Machine learning in applications without needing to build complex server architectures, or learning another language. It also means that it’s possible to provide on-device Machine learning to users, without their data ever hitting a server.</p><p>One of the other great things about the JavaScript ecosystem is its ability to not just run in the browser, but on the server too, with NodeJS. TensorflowJS is also available in Node JS, where it can be bound directly to the Tensorflow API, the same API that the python implementations of the library consume. I’ve considered the possibility of modifying my experiment in this blog post so that when I generate my static site at build time with Eleventy, I could run the model against my data and pre-generate the data for my blog posts, that might be cool.</p><p>The final great thing is that it is possible to convert/re-use models created by the other Tensorflow ecosystems (Python etc) so that they run in the browser.</p><p>Now for one of the big trade offs, Machine learning models can be large, there is a lot of work going to make these models smaller and smaller, but the model used in this demo for example is approximately 28 MB. To be fair, for a general purpose natural language model, this is quite impressively small. Many of these models, are split into chunks so that the model can be downloaded in parallel, which improves things a bit. This tradeoff might be acceptable if it unlocks the ability to provide a good enough UX, without the need to hit a server, which once the model is downloaded can be lightning fast. The model can only be as fast the end-user machine it’s running on, which, especially on mobile, can vary dramatically.</p><p>In applications you might be able to do some different things to make this tradeoff worth it, for example:</p><ul><li>Enabling good caching headers</li><li>Using service workers to background fetch and cache the model, and enable the feature</li><li>Allowing users to opt in/out</li><li>Offer the feature as a progressive enhancement that enables once downloaded</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*pLy86uBr0bUQxkpj.png" /><figcaption>Chrome network panel showing model chunks downloading.</figcaption></figure><p>With the above tradeoffs in mind it might, or might not, make sense to do ML in the browser. Where you need to try and run your models immediately as the site/app loads, or end user device constraints are a problem, maybe server side is the better choice.</p><p>When using JavaScript it’s always important to not block the main thread, I mentioned above that Tensorflow utilises the GPU for its calculations, but as soon as you stop using its API you’re back in the JS main thread, and if you perform expensive calculations there ,you are at risk of providing a bad UX to your users.</p><p>The sample in this post is guilty of this, when performing the cosineSimilarity calculations, let&#39;s fix it.</p><h4>Unblocking the main thread</h4><p>In the browser you can create additional threads called “Workers”, these are isolated threads, that do not have access to any DOM APIs, or variables in the main thread. The only way to communicate between the main thread is via postMessage, which can be cumbersome.</p><p>There is an absolutely fantastic library <a href="https://www.npmjs.com/package/comlink">Comlink</a> that makes working with Worker threads basically invisible, it allows you to work with functions as if they were on the main thread, I believe it achieves this using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy">Proxy</a> objects, hiding the need to work with postMessage directly 🎉.</p><p>Let’s convert our example to use Comlink and move our maths off the main thread.</p><p>We’re going to import the Tensorflow libraries in our worker instead so your HTML should look like this.</p><p>Let’s also add in some user input, to make the demo a bit more spicy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba8c36fa356b46dc45f0b01327389b8e/href">https://medium.com/media/ba8c36fa356b46dc45f0b01327389b8e/href</a></iframe><p>Next up, delete all of the code in “index.js”. Now in “index.js” lets add the code to work with our new “worker.js” file and update the UI.</p><p>We’re going to add all of the same code, except this time, expose a function called “search” which returns our predictions. There are few other changes too, such as using importScripts to import the libraries into the Worker.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc7fc4b1e115d12d27a62c4153485d64/href">https://medium.com/media/fc7fc4b1e115d12d27a62c4153485d64/href</a></iframe><p>Now, let’s use our new SearchService in &quot;index.js&quot;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b54ee17446e167df345ea58ae717bb65/href">https://medium.com/media/b54ee17446e167df345ea58ae717bb65/href</a></iframe><p>If you load this demo code up in the browser you should get similar result to before, but with the heavy-work offloaded to a Worker thread.</p><p>Here’s a live demo project for reference: <a href="https://codesandbox.io/s/tensorflow-js-with-web-workers-blog-searching-1shbq">https://codesandbox.io/s/tensorflow-js-with-web-workers-blog-searching-1shbq</a></p><p>Hopefully you can see from the example how you can offload work into a worker using Comlink, you can also build for production using popular tools such as Rollup, but I won’t cover that here.</p><p>One of the neat things about using Worker threads is because they don’t have access to the DOM you are forced to separate your application logic from your UI, making your code more modular and reusable in the future.</p><h4>Future thoughts</h4><p>In case you missed the links earlier:</p><ul><li>Source code: <a href="https://github.com/Georgegriff/griffadev/tree/main/src/experiments/natural-language-search">https://github.com/Georgegriff/griffadev/tree/main/src/experiments/natural-language-search</a></li><li>Demo: <a href="https://griffa.dev/experiments/natural-language-search/">https://griffa.dev/experiments/natural-language-search/</a></li></ul><p>If I was to continue this idea through i’d probably explore some of the following:</p><ul><li>Making the code more production ready using module imports and a build tool chain.</li><li>Investigate ways to use TensorflowJS at build time of my blog to pre-calculate embeddings for posts.</li><li>See if there is in-fact ways to do cosine similarity directly in TensorflowJS, again, i’d love to know if anybody knows how!</li></ul><p>I hope to continue my Machine learning journey, I have some other blog related ideas that I might try to explore in the future:</p><ul><li>Recommending similar blog posts</li><li>Text summary generation of blog posts.</li></ul><p>I’m fairly early on in my AI learning journey, but one of the initial resources that helped me out and inspired me was watching content from <a href="https://twitter.com/jlengstorf">Jason Lengstorf</a> from his <a href="https://www.learnwithjason.dev/">Learn with Jason</a> series, which I highly recommend. One of the truly awesome things about this series is closed captioning is provided, making this content more accessible to everybody 🎉.</p><p>At the time of writing there are 3 sessions relating to Machine Learning and TensorflowJS, here is one of them:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWIHZ7kjJ35o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWIHZ7kjJ35o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWIHZ7kjJ35o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/da6f853eabdc60ef5e52b60befc73897/href">https://medium.com/media/da6f853eabdc60ef5e52b60befc73897/href</a></iframe><p>I hope this was a good read, if you feel like reading more of my work, please follow me on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>, or get me a <a href="https://ko-fi.com/griffadev">coffee</a> if you feel like it ☕.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dad21585a60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type checking global JavaScript libraries in VS Code for when you just want learn and code.]]></title>
            <link>https://griffadev.medium.com/type-checking-global-javascript-libraries-in-vs-code-for-when-you-just-want-learn-and-code-1f2230a6c6e1?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f2230a6c6e1</guid>
            <category><![CDATA[tensorflowjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Sun, 18 Apr 2021 14:31:37 GMT</pubDate>
            <atom:updated>2021-04-18T14:31:37.462Z</atom:updated>
            <content:encoded><![CDATA[<h4>Sometimes when you’re prototyping and learning a new library you want a quick way to get type-checking/intellisense/auto-complete to assist with your learning. Here is a quick way to enable type checking without fully opting into TypeScript.</h4><p>I’ve been learning a little bit of artificial intelligence/machine learning in my spare time and I recently started learning a little TensorflowJS. The quickest and simplest way of getting TensorflowJS is a good old script tag. When you are experimenting and prototyping you <em>really</em> don’t want to waste time with build tools.</p><p>Whilst this tutorial explains setting up basic type-checking for TensorflowJS it should work for any global library that has TypeScript documentation. When building a production project you may want to consider build tools, but for Machine learning experiments, I find you just want to get to the coding using documentation and examples.</p><p>This post explains how you can prototype with files from a CDN whilst opting in to certain nice-to-have features of TypeScript that can assist with learning a library, without fully adopting TypeScript.</p><p>You can just load TensorflowJS like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2d145d2e0ffc7fb32b5013b2bf7982f4/href">https://medium.com/media/2d145d2e0ffc7fb32b5013b2bf7982f4/href</a></iframe><p>Doing so will make the library available on the global window object as tf</p><p>e.g.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02e849a0078bc19202606baaff8e50d4/href">https://medium.com/media/02e849a0078bc19202606baaff8e50d4/href</a></iframe><p>One downside to doing this is that when you are working with Tensorflow you won’t get any auto-complete in your IDE/Editor, because there are no import references for VS Code (or other) to analyze, unlike if you were to use ES6 Imports or Common JS require statements.</p><p>Let’s take a look at how we can make no changes to the code but give you some nice type checking, and the real bonus for learning a library: inline documentation, which is so fantastic.</p><blockquote>Whilst this tutorial explains how to enable type-checking and library documentation in VS Code, it may work for other IDEs, the reason VS Code is so great here is its built in TypeScript support.</blockquote><h4>Type checking on a global library</h4><p>Create a directory and open it up in VS Code.</p><blockquote>If you don’t have it yet, you can download VS Code over <a href="https://code.visualstudio.com/download">here</a>.</blockquote><p>Create a simple HTML file called index.html with two script imports, one for the library and one for your code. We won&#39;t actually boot up this file on a server and load it in a browser in this tutorial, but i&#39;m putting this in for completeness.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e454c16623b78ffa1c6422faa80a38a/href">https://medium.com/media/6e454c16623b78ffa1c6422faa80a38a/href</a></iframe><p>The reason for creating a separate index.js instead of inline JavaScript in a &lt;script&gt;, is as far as I could find, type checking does not seem to work in HTML files. If there is a way to get it to work easily, I&#39;d love to know!</p><p>If you don’t have one yet, first initialise an NPM project in your directory, you may be able to do this without an NPM project by using global libraries with -g, I haven&#39;t tried this though.</p><blockquote>If you don’t have NodeJS and NPM installed you can download it here: <a href="https://nodejs.org/en/">https://nodejs.org/en/</a>.</blockquote><p>Install the TensorflowJS library, we won’t actually be using the code in the library, this is for just referencing the types, which come along with the NPM module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c7fdf3e69457eebe23f9d086b0acc4c/href">https://medium.com/media/2c7fdf3e69457eebe23f9d086b0acc4c/href</a></iframe><p>Next up we’re going to create a <a href="https://www.typescriptlang.org/docs/handbook/declaration-files/by-example.html">TypeScript declaration file</a>. In this file we’re going to tell TypeScript that the TensorflowJS library will be available on the global Window interface with a variable named tf</p><p>Create a file called index.d.ts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3b6268443142276f12fc75747b9957/href">https://medium.com/media/6e3b6268443142276f12fc75747b9957/href</a></iframe><p>Now finally create index.js and open it up.</p><p>Inside the file put the following at the top:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87574eb241837a8549221cf87a7b01e3/href">https://medium.com/media/87574eb241837a8549221cf87a7b01e3/href</a></iframe><blockquote>If you want find out more about the notation with the triple-slashes, you can find out more in the <a href="https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html">TypeScript documentation</a></blockquote><p>Now here comes the magic, when typing you will now get auto-complete, for example if you type tf. you should get some suggestions 🥳.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qHPY5wL5QTf4CfYd.png" /><figcaption>When typing ‘tf.’ VS Code now provides auto-completion.</figcaption></figure><p>But the really fantastic thing here, and where it can really help if you are learning the library, is if the library author provides good function documentation you have that available right in your editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EGw_SC5OlW3OLB4_.png" /><figcaption>VS Code documentation for the tensor2d function.</figcaption></figure><h4>Adding simple Type-checking</h4><p>You can also add strict type-checking with single comment in a file.</p><p>In index.js add the following to the top of your file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/456f6a132161b3fd6a78130276cbc9ea/href">https://medium.com/media/456f6a132161b3fd6a78130276cbc9ea/href</a></iframe><p>You should now see that when you code you will get type warning, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1fcRos6DcLJmBcDo.png" /><figcaption>Code: ‘tf.tensor2d(420)’, showing error Argument of type ‘number’ is not assignable to parameter of type ‘TensorLike2D’, in VS Code</figcaption></figure><p>Congratulations, you have now adopted TypeScript! If you wanted to, you could even define your own types in index.d.ts.</p><p>If you want to learn more about ways of adopting TypeScript in small ways, this is a really great video that shows the different “degrees” of adopting TypeScript in a project, without needing to go “all in”.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FBHYgpbPC4wM%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DBHYgpbPC4wM&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FBHYgpbPC4wM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f64621de4360f5005e0c5f872c112bc4/href">https://medium.com/media/f64621de4360f5005e0c5f872c112bc4/href</a></iframe><h4>Learning TensorflowJS</h4><p>If you want to learn more about Machine learning/Tensorflow, I got inspired by watching content from <a href="https://twitter.com/jlengstorf">Jason Lengstorf</a> from his <a href="https://www.learnwithjason.dev/">Learn with Jason</a> series, which I highly recommend (if it wasn’t obvious already). One of the truly awesome things about this series is closed captioning is provided, making this content more accessible to everybody 🎉.</p><p>At the time of writing there are 3 sessions relating to Machine Learning and TensorflowJS, here is one of them:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FWIHZ7kjJ35o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DWIHZ7kjJ35o&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FWIHZ7kjJ35o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/da6f853eabdc60ef5e52b60befc73897/href">https://medium.com/media/da6f853eabdc60ef5e52b60befc73897/href</a></iframe><p>I hope this was a good read, if you feel like reading more of my ramblings, please follow me on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f2230a6c6e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory leaks and why should you never write such bad code, even for tests]]></title>
            <link>https://griffadev.medium.com/memory-leaks-and-why-should-you-never-write-such-bad-code-even-for-tests-334cad6f98b2?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/334cad6f98b2</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 18:41:44 GMT</pubDate>
            <atom:updated>2021-03-18T18:41:44.399Z</atom:updated>
            <content:encoded><![CDATA[<h4>That feeling when you see some awful code, and then realise you wrote it. Here’s a story of how some bad code I wrote in a unit test, made it into production and caused a memory leak in a NodeJS application.</h4><p>A project that I work on started showing crashed Pods in our Kubernetes (K8s) cluster, which runs a NodeJS server in a container, it was failing with a dreaded “OOMKilled” (Out of memory killed) error, which sent me down the path of learning about profiling NodeJS applications for memory leaks.</p><p>If you don’t know much about Kubernetes, that doesn’t matter for this article, the fact the NodeJS application is running in K8s is incidental to the tale, and I will only mention it briefly when discussing debugging in Kubernetes.</p><p>I learnt a lot through investigating this memory leak, not just about memory profiling, but about the risk of writing “quick and dirty code”, even if it’s not for production use.</p><p>Here is an obfuscated and simplified explanation of the terrible, terrible code that I originally wrote.</p><h4>The bad code</h4><p>So, a few months ago I wrote some code some unit tests which exercised some file validation logic. When I wrote this code I needed to get access to the supported file extensions for the validator, for doing some checks, which lived somewhere else, so I very lazily dumped the file extensions onto an object that I was processing in the test, just for test purposes, right? it’ll be fine.</p><p>My simplified version of the production module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ea80ba51097a0b61e3fcb3838bb1f0d/href">https://medium.com/media/0ea80ba51097a0b61e3fcb3838bb1f0d/href</a></iframe><p>What’s happening here is a function is exported which exposes other modules via a dynamic require statement. This dynamic require statement is very important to the memory leak and i&#39;ll come back to it.</p><blockquote>As an aside using require like this in the code is blocking, so it might not be the best thing to use. For more modern code we could use import() in ES Module code.</blockquote><p>Now for the bad code, I had in my unit test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c348b5e9ab514dd053a036685f0fde9/href">https://medium.com/media/2c348b5e9ab514dd053a036685f0fde9/href</a></iframe><p>This code is terrible for so many reasons, but it was only for unit tests. This code looks weird, I know, but in context of what I used this for in our tests does make sense, I promise, but this simplified sample is to demonstrate the memory leak.</p><p>Unfortunately, only for unit tests ended up not being true, and here is my first learning from this experience:</p><blockquote>Any code that you write anywhere, including inside of unit tests, could be copied by any well meaning developer adapting the code for their use case.</blockquote><p>This happened, and unfortunately the “just for test” code with the supportedExtensions = [] and .push(&quot;.pdf&quot;) came along for the ride, even though it wasn&#39;t needed at all for the production use case.</p><h4>Why is this a memory leak?</h4><p>So on the face of it if you were to look at the myValidators.map code it doesn&#39;t look like i&#39;m holding any references to the supportedExtensions object once badFunction its finished. But that assumption ignores that the Array, or the contents of it, that validators() supplies could be retained in memory forever.</p><blockquote>Objects in Memory are available for Garbage collection when there are no references to the object anymore and nothing is holding on to those objects. This is a massive over-simplification, I’ll link a great talk later in this article which describes it much better than I ever could.</blockquote><p>Do you remember this line of code?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85293c5061da325f5905ea5a5498dfcf/href">https://medium.com/media/85293c5061da325f5905ea5a5498dfcf/href</a></iframe><p>A NodeJS module is being imported into the current scope, the important thing about NodeJs modules though is that:</p><p>No matter how many times you import a module you always get the a reference to the same module object, so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ace234a22781e674479aa3905c2a02c/href">https://medium.com/media/9ace234a22781e674479aa3905c2a02c/href</a></iframe><p>This means that even if we lose all references to the imported module, it wont be garbage collected. In this case, this is extremely problematic because validator.supportedExtensions.push(&quot;.pdf&quot;); will add a new entry to an array, that lives on this module object forever, every time the function is called. Imagine if this was on an REST API call (it was). Yikes.</p><p>A couple more learnings here:</p><ul><li>Mutating objects in an array someone else passed to you is dangerous, you have no idea what references are held to that object, your modifications may never be garbage collected.</li><li>If you do have to put bad non-production code in, put a massive comment around it warning future developers, not to copy it.</li><li>Avoid changing objects you don’t control.</li></ul><p>On a somewhat related note to the learnings above, Jake Archibald recently wrote about the risks of calling methods with potentially non-future proof parameters, it’s a good read: <a href="https://jakearchibald.com/2021/function-callback-risks/">https://jakearchibald.com/2021/function-callback-risks/.</a></p><h4>Memory profiling and finding the problem code</h4><p>When I first realised that we might have a Memory leak I first wanted to make sure I knew what tools where at my disposal, I headed to YouTube and found this great video on the topic.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FhliOMEQRqf8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DhliOMEQRqf8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FhliOMEQRqf8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1bae42eab67931f28719fc19c080b37/href">https://medium.com/media/c1bae42eab67931f28719fc19c080b37/href</a></iframe><p>One way to profile for memory leaks in NodeJS is to use the --inspect flag when running your process e.g. node --inspect index.js This starts a remote debugging session by default on port 9229. I find that the best way to hook into this is via the Chrome Developer Tools.</p><p>If you open the Developer Tools when you have a node --inspect process running you should notice a new Node logo, like the one shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ITz3S16T4IS80INE.png" /><figcaption>Open dedicated DevTools for NodeJS</figcaption></figure><p>When you activate this mode, a new window will open where one of the tabs in the new window is “Memory”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/0*6k5tKvrBe0MS43dx.png" /><figcaption>Memory profiling options in NodeJS dedicated DevTools for NodeJS</figcaption></figure><p>To try and find the issue I selected the option “Allocation instrumentation timeline”, I then proceeded to run our application tests which had caused the original “OOMKilled” on our cluster. After these tests ran I stopped the instrumentation and proceeded to sort through the results. I found that sorting by size and then searching the largest allocated objects helped me find the problem.</p><p>Sure enough after filtering through a lot of noise I found something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aqttOCIx3XjsDEDq.png" /><figcaption>Shows lots of memory allocated to the “supportedExtensions”</figcaption></figure><p>Luckily for me, I know our codebase quite well and was able to identify the problem area based on the variable name of the large array and also the array contents, which is where to my shame I found my awful code being used inside of an API call.</p><h4>Memory profile in Kubernetes</h4><p>Memory profiling in Kubernetes is quite similar to when you are running locally, you need to end up with a server on your machine exposing a debugging session.</p><p>Recommendations:</p><ul><li>Scale your deployment down to 1 replica.</li><li>Edit your deployment so your NodeJS server sets the --inspect flag</li><li>Disable liveness and readiness probes for the container, otherwise K8s may kill your session whilst debugging.</li><li>Increase your memory limits and requests, profiling can take up to 2x more memory than usual.</li><li>Locate the pod you want to debug and run kubectl port-forward pod-name 9229 this will result in the same debugging session as earlier running on your machine, forwarded from the K8s cluster.</li></ul><h4>Reproducing the memory leak with demo code</h4><p>If you want to have a play reproducing the memory leak you could do this:</p><ol><li>Create the following folder and file: validators/name.js Can be empty module exports:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47bf2a27570755161ef1af4f37f5c8e0/href">https://medium.com/media/47bf2a27570755161ef1af4f37f5c8e0/href</a></iframe><ol><li>Create validate.js</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/696fcacb5eeb4339df0af64e9759c843/href">https://medium.com/media/696fcacb5eeb4339df0af64e9759c843/href</a></iframe><ol><li>Create bad-code.js</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78000a2a32bf12955618f0199d03233e/href">https://medium.com/media/78000a2a32bf12955618f0199d03233e/href</a></iframe><ol><li>Run node --inspect bad-code.js You will need NodeJS installed <a href="https://nodejs.org./">https://nodejs.org.</a></li><li>Open Chrome developer tools, you should see the NodeJS logo which says “Open dedicated DevTools for NodeJS”</li><li>Run the profiling techniques as described in the previous section.</li></ol><h4>Learnings</h4><p>I learnt a lot through this experience.</p><ul><li>Avoid writing sloppy code, even if it is non-production.</li><li>Mutating data that is passed to you is dangerous, you have no idea what references are held to that object, your modifications may never be garbage collected.</li><li>How to Memory profile in NodeJS</li></ul><p>I hope this was a good read, if only to laugh at my terrible code, if you feel like reading more of my ramblings, please follow me on Twitter <a href="https://twitter.com/griffadev">@griffadev</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=334cad6f98b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a responsive, progressively enhanced, masonry layout with only CSS and HTML’]]></title>
            <link>https://griffadev.medium.com/building-a-responsive-progressively-enhanced-masonry-layout-with-only-css-and-html-998b2de89cf2?source=rss-354dacf0b321------2</link>
            <guid isPermaLink="false">https://medium.com/p/998b2de89cf2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[George Griffiths]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 16:44:49 GMT</pubDate>
            <atom:updated>2022-01-08T22:43:30.088Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a responsive, progressively enhanced, masonry layout with only CSS and HTML</h3><h4>Masonry layouts, think bricks, think Pinterest, have had many solutions in the web over the years. Many use too much JavaScript, but there is some exciting new things coming to CSS grid to enable Masonry layouts. But you don’t have to wait, you could implement today, using progressive enhancement. Progressive enhancement is like technical debt that fixes itself.</h4><p>A few days ago I found that I had talked myself into re-designing a website. The website is for my brothers’ <a href="https://cgguitar.co.uk/">guitar teaching business</a> which I had previously worked a few years ago, when I was a student. (if you click that link and view it before the rework, yeah I know the site needs work, that’s what i’m doing here).</p><p>As part of the redesign I was trying to think of ways to lay out testimonials from students, which may have varying length/content, I stumbled onto the idea of using a masonry layout (think bricks, think Pinterest).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yz5N66LjRTDlDBkY.png" /><figcaption>Mock masonry design testimonials that inspired this tutorial</figcaption></figure><p>There are many ways to go about building out a Masonry layout, this CSS tricks article lays out a few of the options, <a href="https://css-tricks.com/piecing-together-approaches-for-a-css-masonry-layout/">Approaches for a CSS Masonry Layout</a>.</p><p>When looking into the solution I knew I wanted to adhere to a couple of rules:</p><ul><li>No committing the huge sin of using JavaScript for layout.</li><li>It’s okay if the experience upgrades or downgrades based on browser support.</li></ul><h4>What are we building</h4><ul><li>Masonry layout using grid-template-rows: masonry</li><li>CSS Columns as a fallback</li></ul><p>This article will explain how to build out the following responsive masonry cards layout with only HTML and CSS. This final demo uses some features only available in Firefox, behind a flag, which is detailed in the article.</p><p>Here is the full finished demo code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fembed%2Fpreview%2FXWjxvBa%3Fheight%3D600%26slug-hash%3DXWjxvBa%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fpen%2FXWjxvBa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc6d4f9c91b68d3e1cc67a1a034a9cec/href">https://medium.com/media/dc6d4f9c91b68d3e1cc67a1a034a9cec/href</a></iframe><h4>You’d think CSS Grid could do it</h4><p>CSS Grid is amazing, and you’d think it would have shipped with a simple way of doing masonry layouts, the initial versions of the spec however, did not ship anything to really help out with these layouts.</p><p>But fear not, Firefox has something cooking!</p><blockquote>Before I continue, the specification we’re going to look into is experimental, and at the time of writing only is available in Firefox behind a flag, however, this article will outline how you could use the feature today and fallback to another approach for browsers without support.</blockquote><h4>Enabling Masonry layout in Firefox</h4><p>It’s January 2021, i’m using Firefox 84.0.2, depending on how the spec has progressed, you may not need to enable this flag, it may even be available in other browsers, <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout">this link may have more information</a>.</p><p>To enable in Firefox:</p><ol><li>type about:config into your address bar</li><li>Accept the warnings</li><li>In the search box find: layout.css.grid-template-masonry-value.enabled and enable it.</li></ol><p>Over on MDN you can find this article: <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout/Masonry_Layout">CSS Grid Layout &gt; Masonry Layout</a></p><p>It details, an example very similar to this:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fembed%2Fpreview%2FqBaJeQK%3Fheight%3D600%26slug-hash%3DqBaJeQK%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fpen%2FqBaJeQK&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6267b97bef76f03bd6fd4ae76d88e2b/href">https://medium.com/media/e6267b97bef76f03bd6fd4ae76d88e2b/href</a></iframe><p>With this small amount of CSS we can get a layout which is almost what we want already, exciting! It has hardcoded sizing, lets improve it, and enable responsive masonry layouts,</p><h4>Building out our example</h4><p>Let’s start with a fresh example, starting with a little html and “lorem ipsum” to generate some “bricks” for masonry layout.</p><p>To see the effect you will need to be view these examples in a browser that supports masonry layouts (at the time of writing Firefox behind a flag).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fembed%2Fpreview%2FMWjPNLp%3Fheight%3D600%26slug-hash%3DMWjPNLp%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fpen%2FMWjPNLp&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3eb846b447afc20c62130f0ec1e45e85/href">https://medium.com/media/3eb846b447afc20c62130f0ec1e45e85/href</a></iframe><p>This code will result in a masonry style layout, which automatically reduces the number of columns as the screen shrinks down, until you reach a single column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uwyn3JxioB2U16dP.gif" /><figcaption>Animated resizing of demo showing masonry layout with responsive columns with css grid</figcaption></figure><p>If you run this example you should notice that there is no clean edge on the bottom, it has a wonky bottom.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sWjrtKuh9Y6CiyY-.png" /><figcaption>Image of result of demo showing masonry layout without a flat bottom</figcaption></figure><blockquote>No one likes a soggy wonky bottom.</blockquote><p>The masonry specification also allows for a new property: align-tracks, which you can set to stretch to fix this problem.</p><p>align-tracks also has some other <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/align-tracks">support modes</a>, beware of potential issues with align-tracks if you want a masonry layout where a &quot;brick&quot; can span multiple columns, hopefully these things will get ironed out as the spec progresses.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/319ea6bceda987a880b7051f5f2236c2/href">https://medium.com/media/319ea6bceda987a880b7051f5f2236c2/href</a></iframe><p>And now as if by magic, the bottom edge is now straight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ECZ2ljAqedp1rZxE.gif" /><figcaption>Image of result of demo showing masonry layout without a straight bottom</figcaption></figure><h4>What about a fallback</h4><p>Okay, so now we made something work in a single browser only, and it’s not even shipped there, not ideal. Let’s try to achieve something similar, this time with CSS columns.</p><p>I’d never used CSS columns before looking into them for implementing this masonry layout, they are actually quite clever, and they can made to be responsive, without media queries, which we will take a look at now.</p><p>For this example, i’m going to start to make use of <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/--*">CSS Custom Properties</a> which will become extremely useful once we enable our progressive enhancement, we can use these variables to share sizes and other config.</p><p>For the css we’re going to make use of some column properties:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8e7eca39abf2a68a0b15cb944f2a90c/href">https://medium.com/media/b8e7eca39abf2a68a0b15cb944f2a90c/href</a></iframe><p>Setting a column-width will set a minimum width of a column before columns need to shrink down, meaning on smaller devices we can get a single column, the same as with our CSS grid implementation.</p><p>If you want to set a specific number of columns you can use the column-count property. You could adjust the number of columns using CSS media queries too, if you wanted to:</p><p>Optional example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6a5ac800d8431ecd719213fcd1d77d8/href">https://medium.com/media/e6a5ac800d8431ecd719213fcd1d77d8/href</a></iframe><p>We’re not going to do that, we’re just going to make use of column-width and allow our columns to grow up to a maximum card width.</p><p>Same html as before, with some changes to the css:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fembed%2Fpreview%2FLYRgwaJ%3Fheight%3D600%26slug-hash%3DLYRgwaJ%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fpen%2FLYRgwaJ&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/571503e4fccb4aa4efbd6eeef3cbb4da/href">https://medium.com/media/571503e4fccb4aa4efbd6eeef3cbb4da/href</a></iframe><p>The result is very similar, however, there are two main differences:</p><ul><li>The order of items goes down the columns as opposed to across the rows with css grid. Columns: ⬇️ Grid: ➡️</li><li>We have the wonky bottom back (there is no easy fix with css columns)</li></ul><p>The first difference may be a deal breaker, depending on the use case, for me, order didn’t really matter very much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1wafm9vFvHnnm6Ed.gif" /><figcaption>Animated resizing of demo showing masonry layout with responsive columns with css columns</figcaption></figure><h4>Progressive enhancement</h4><p>Now we’ve seen how to implement a masonry layout in the future and with a fallback, lets put it all together with the magical @supports keyword in css.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/472d0a802a4de661a8f1c6a2383a5838/href">https://medium.com/media/472d0a802a4de661a8f1c6a2383a5838/href</a></iframe><p>Again, with no changes to the HTML again, we’re going to implement an @supports just for the masonry layout using css grid:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44219fba2aa26aa18c9549d3b8b19298/href">https://medium.com/media/44219fba2aa26aa18c9549d3b8b19298/href</a></iframe><p>Now with this example, depending on what your browser supports, you can either get the CSS Grid or the CSS Columns version.</p><p>As long as the grid-template-rows: masonry doesn&#39;t change between now and more browsers shipping, we have just written some CSS that will automatically upgrade itself over time, fixing the technical debt/UX &quot;bug&quot; of a wonky bottom and vertical ordering instead of horizontal.</p><h4>Bonus round</h4><p>In my implementation I was toying around with having different cards backgrounds every nth “brick” in the masonry layout.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60ed71bf73264d3329f43162726b7103/href">https://medium.com/media/60ed71bf73264d3329f43162726b7103/href</a></iframe><p>There are some really neat tricks you can do with the nth-child property in CSS, some useful background reading if you are new to this:</p><ul><li><a href="https://css-tricks.com/how-nth-child-works/">How nth-child Works</a></li><li><a href="https://css-tricks.com/useful-nth-child-recipies/">Useful :nth-child Recipes</a></li></ul><p>Here’s the full demo:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fembed%2Fpreview%2FXWjxvBa%3Fheight%3D600%26slug-hash%3DXWjxvBa%26default-tabs%3Dhtml%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io&amp;display_name=CodePen&amp;url=https%3A%2F%2Fcodepen.io%2Fgeorgegriff%2Fpen%2FXWjxvBa&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc6d4f9c91b68d3e1cc67a1a034a9cec/href">https://medium.com/media/dc6d4f9c91b68d3e1cc67a1a034a9cec/href</a></iframe><p>Thanks for reading all the way through, I hope this was useful and one day soonish we will be able to easily deal with wonky bottoms in just CSS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998b2de89cf2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>