<?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 Akash Hamirwasia on Medium]]></title>
        <description><![CDATA[Stories by Akash Hamirwasia on Medium]]></description>
        <link>https://medium.com/@AkashHamirwasia?source=rss-c73eddb5c7ed------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*A_TAWU2XNicfMgjPoECzeg.jpeg</url>
            <title>Stories by Akash Hamirwasia on Medium</title>
            <link>https://medium.com/@AkashHamirwasia?source=rss-c73eddb5c7ed------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 22:19:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@AkashHamirwasia/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[Full-page theme toggle animation with View Transitions API]]></title>
            <link>https://medium.com/@AkashHamirwasia/full-page-theme-toggle-animation-with-view-transitions-api-43db0beed341?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/43db0beed341</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[view-transitions-api]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Fri, 12 Apr 2024 18:32:02 GMT</pubDate>
            <atom:updated>2024-04-12T18:35:35.677Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObY6hJ9Fc1aoXlfAv57b4g.png" /></figure><h3>Video version of this blog</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FQs1EOL2ccD8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DQs1EOL2ccD8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FQs1EOL2ccD8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a0f6a587e62a6725cb6fcdbb24510a3/href">https://medium.com/media/8a0f6a587e62a6725cb6fcdbb24510a3/href</a></iframe><p>The Telegram app has a very interesting animation for its dark mode toggle where the dark theme grows from the switch to cover the rest of the app. I always wondered how this worked under the hood and how it could be replicated on the web. I’m glad to share that this is finally possible on the web thanks to the <a href="https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API">View Transitions API</a> coming to the browsers.</p><p>This blog post will be going over implementing the following animation for a dark theme toggle switch using the View Transitions API. I’ll be doing this in a React project, but the View Transitions API is fundamental to browsers so you can use vanilla JavaScript or any other framework/library of your choice.</p><h3>How does View Transitions API work?</h3><p>The interaction I’m building here would become easy to understand once we take a look at how the View Transition API works under the hood:</p><ol><li>When the API is accessed to start a view transition, the browser captures the current state of the page as a screenshot. This is called the “Old” state of the page.</li><li>Then, the API runs some code that updates the page to the next state which it should animate to.</li><li>Now that the browser has the next state ready, it captures it as another screenshot. This is called the “New” state of the page. The user at this point is still seeing the “Old” state of the page and all of these updates to the “New” state have only happened in memory but haven’t been rendered on the display yet.</li><li>With the “Old” and “New” screenshots of the page, the browser loads these in ::view-transition-old and ::view-transition-new pseudo-elements.</li><li>Finally, a CSS animation is run between these two pseudo-elements which reveals the ::view-transition-new pseudo-element.</li><li>When the animation ends, these pseudo-elements are removed and the browser proceeds to render the already loaded “New” state of the page(From step 3) on the screen.</li></ol><p><a href="https://akashhamirwasia.com/blog/full-page-theme-toggle-animation-with-view-transitions-api/#how-does-view-transitions-api-work"><strong>View an interactive demo explaining the above steps</strong></a></p><h3>Implementing the animation in React</h3><p>The following code is a basic implementation of a dark theme toggle switch which stores the state of the switch in a React state variable and has an associated effect to toggle the dark class on the &lt;html&gt; element based on the state of the switch. The toggle switch component is implemented using <a href="https://www.radix-ui.com/primitives/docs/components/switch">Radix UI</a> for simplicity but you can use any component library/custom switch component you might have.</p><pre>import { useState, useEffect } from &#39;react&#39;;<br>import * as Switch from &#39;./Switch&#39;;<br>import { IconMoon, IconSun } from &#39;./Icons&#39;;<br><br>export default function App() {<br>  const [isDarkMode, setIsDarkMode] = useState(false);<br><br>  const toggleDarkMode = (isDarkMode) =&gt; {<br>    setIsDarkMode(isDarkMode);<br>    // Animation code goes here<br>  };<br><br>  useEffect(() =&gt; {<br>    if (isDarkMode) {<br>      document.documentElement.classList.add(&#39;dark&#39;);<br>    } else {<br>      document.documentElement.classList.remove(&#39;dark&#39;);<br>    }<br>  }, [isDarkMode]);<br><br>  return (<br>    &lt;div className=&quot;h-screen w-screen flex items-center justify-center bg-white dark:bg-gray-950&quot;&gt;<br>      &lt;Switch.Root checked={isDarkMode} onCheckedChange={toggleDarkMode}&gt;<br>        &lt;Switch.Thumb&gt;<br>          {isDarkMode ? &lt;IconMoon /&gt; : &lt;IconSun /&gt;}<br>        &lt;/Switch.Thumb&gt;<br>      &lt;/Switch.Root&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>To use the View Transitions API, we need to call the document.startViewTransition() function and pass a callback that defines how the page should update to the next state which it should animate to(Step 2 from <a href="https://akashhamirwasia.com/blog/full-page-theme-toggle-animation-with-view-transitions-api/#how-does-view-transitions-api-work">How View Transitions API work</a>).</p><p>Our initial instinct would be to simply move the setIsDarkMode call inside this callback function. After all, this is what triggers the update on the page to the dark theme. While this is in the right direction, there is a small flaw in our understanding. React does not update the DOM immediately after a state update. DOM updates are asynchronous and can happen well after the setState call has happened. Thus, after calling setIsDarkMode(isDarkMode), it is not guaranteed that the DOM is in its new state(i.e. dark theme state in this example) when the callback in doucment.startViewTransition() ends.</p><p>This is a problem, as the startViewTransition() needs the new state of the page so that it can perform the animation. So how can we solve this?</p><figure><a href="https://akashhamirwasia.com/blog/full-page-theme-toggle-animation-with-view-transitions-api/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2Tz0dPN0kJgGpvZ6aEvag.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer and open reading experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43db0beed341" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Internals of async / await in JavaScript]]></title>
            <link>https://medium.com/@AkashHamirwasia/internals-of-async-await-in-javascript-3dde480c8b72?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/3dde480c8b72</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[internal]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Fri, 14 Jul 2023 11:42:15 GMT</pubDate>
            <atom:updated>2024-04-12T18:32:41.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CA1LReC01rkytYRicMtXrw.png" /></figure><h3>Video version of this blog</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsB_P0m9ggTU%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsB_P0m9ggTU&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsB_P0m9ggTU%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cf53cf3c50e68474056307d397e2228/href">https://medium.com/media/0cf53cf3c50e68474056307d397e2228/href</a></iframe><p>If you have ever used JavaScript in the past, there is a high chance you have encountered the <a href="https://javascript.info/async-await">async / await</a> syntax. async / await makes it easy to define asynchronous logic in a synchronous way that our brains can comprehend better. Some of you JavaScript veterans might know that async / await is merely a <a href="https://en.wikipedia.org/wiki/Syntactic_sugar">syntactic sugar</a> over the existing <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises API</a>. This means that we should be able to achieve the functionality of async / await in JavaScript without using async and await keywords albeit with some verbosity. This is exactly what I wanted to explore in this post.</p><h3>What are we trying to achieve?</h3><p>Let’s look at some boilerplate code to understand what we are trying to achieve.</p><pre>function wait() {<br>  return new Promise((resolve, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>      resolve(&#39;Timeout resolved&#39;);<br>    }, 2000);<br>  });<br>}<br><br>async function main() {<br>  console.log(&#39;Entry&#39;);<br><br>  const result = await wait();<br>  console.log(result);<br><br>  console.log(&#39;Exit&#39;);<br>  return &#39;Return&#39;;<br>}<br><br>main().then(result =&gt; {<br>  console.log(result);<br>});</pre><p>The output of the above code:</p><pre>Entry<br>// Pauses for 2 seconds<br>Timeout resolved<br>Exit<br>Return</pre><p>Given the above code snippet and its respective output, can we re-write the main() function to <strong>not use</strong> async and await keywords, but still achieve the same output? Conditions being the following:</p><ul><li><strong>Cannot use Promise chaining within </strong><strong>main()</strong>. This makes the problem trivial and deviates from the original goal. Promise chaining might work in the contrived example above but it does not capture the complete essence of async / await and the problems it solves.</li><li><strong>Not changing any function signatures</strong>. Changing function signatures would require updating function calls as well which is complex in a large project with many interdependent functions. So try not to change any function signatures.</li></ul><p>Even though I have defined the conditions above, if you feel stuck and don’t see a way forward without breaking the above conditions, do take the liberty to try that approach. Maybe breaking the condition will lead you to an approach that satisfies the above condition. No one is expected to come up with the right solution on their first try(even I didn’t while preparing this 🙂).</p><h3>Playground</h3><p>This blog post is hands-on and I strongly suggest you use the below playground to test out your ideas to implement something like async / await without using async and await keywords. The rest of the post has hints and solutions on how you can achieve this, but feel free to take a moment and try out some code whenever you get an idea to proceed.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Finternals-of-async-await-in-javascript-playground-7fqgjn%3Fexpanddevtools%3D1%26fontsize%3D14%26hidenavigation%3D1%26module%3D%252Fsrc%252Findex.js%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F7fqgjn&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F7fqgjn%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ccbdcca0c551c9fa025d0d55d209535/href">https://medium.com/media/9ccbdcca0c551c9fa025d0d55d209535/href</a></iframe><h3>Hint #1: Looking at pausing and resuming a function execution</h3><p>At a high level, what does async / await do? Well, it <strong>pauses</strong> the execution of the async function whenever it encounters an await statement. And <strong>resumes</strong> the execution when the awaited promise is resolved(or throws an error). A natural question to ask here would be how to go about pausing and resuming a function’s execution. Functions tend to execute to completion right?</p><p>Is there a native feature in JavaScript that mimics this behavior? Yes! It’s <strong>Generators</strong>.</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator">Generators</a> are a special type of function that can return multiple pieces of data <strong>during</strong> its execution. Traditional functions can return multiple data by using structures like Arrays and Objects, but Generators return data whenever the caller asks for it, and they <em>pause</em> execution until they are <em>asked to continue to generate</em> and return more data.</p><p>I won’t be diving deep into what Generators can do, please use the linked reference. Here’s a code snippet explaining the concept of Generators, try to follow the comments to understand what is happening.</p><figure><a href="https://akashhamirwasia.com/blog/internals-of-async-await-in-javascript"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWCNQKkVtqFxif3edT7bKQ.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer and open reading experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3dde480c8b72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Expandable tags with Framer Motion and React]]></title>
            <link>https://medium.com/@AkashHamirwasia/expandable-tags-with-framer-motion-and-react-c22b9f77e10c?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/c22b9f77e10c</guid>
            <category><![CDATA[framer-motion]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[components]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Thu, 04 May 2023 11:57:28 GMT</pubDate>
            <atom:updated>2024-04-12T18:33:04.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-KHqfeT3_QZYv2_rC9jquA.png" /></figure><h3>Video version of this blog</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FRe-1Jnljt_Y%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DRe-1Jnljt_Y&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FRe-1Jnljt_Y%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/fd3b90ec699f0e465ccbab6b054d766f/href">https://medium.com/media/fd3b90ec699f0e465ccbab6b054d766f/href</a></iframe><p><a href="https://www.framer.com/motion/">Framer Motion</a> is arguably one of the most powerful libraries for UI animation with React. I recently got a chance to play around with this library in-depth for some of the stuff I’m working on at Razorpay. In this video blog post, I plan to share some of my learnings by building an expandable tag component whose content changes when the user hovers over them. I’ll be discussing various edge cases in a component like this and also how Framer Motion makes complex layout animations a breeze!</p><h3>Changing the content of an element when user hovers over them</h3><p>Hover-related styling is very straightforward with CSS because of the :hover pseudo-selector, but it’s not very clear how the content of an element can be changed on hover. Thankfully, JavaScript exposes two events - onMouseEnter and onMouseLeave which get fired when the mouse enters(hovers) an element or leaves(unhovers) the element respectively. These events can be used to update a state variable in React which is then used to conditionally render the content of the element.</p><pre>function ExpandableTag({ unhoveredText, hoveredText }) {<br>  const [isHovering, setIsHovering] = useState(false);<br>  return (<br>    &lt;div<br>      className=&quot;inline-block rounded-lg relative text-gray-300 bg-gray-900 ring-1 ring-gray-800 px-4 py-1.5 tracking-wider text-sm font-medium whitespace-nowrap&quot;<br>      onMouseEnter={() =&gt; setIsHovering(true)} <br>      onMouseLeave={() =&gt; setIsHovering(false)} <br>    &gt;<br>      {isHovering ? hoveredText : unhoveredText}<br>    &lt;/div&gt;<br>  );<br>}</pre><p>We have a basic implementation of the component ready, but there are two problems:</p><ul><li><strong>There is no animation</strong>. The content changes instantly which might not be a good UX in this scenario and some subtle animation can polish this component even more.</li><li><strong>The dreaded flicker of doom.</strong> This is a hard one to catch but in a case where your hovered text is lesser than the unhovered text, the user can cause the component to enter into a flickering state where the content of the component changes continuously.</li></ul><h3>Adding fade-in / out animation to the content</h3><p>To solve the first problem, let’s start by adding simple fade-in and fade-out on the changing content within the tag. When the user hovers over the tag, the unhovered text fades out and hovered text fades in. This plays in reverse when the user hovers out. This is very easy to do in Framer Motion with the motion component and the <a href="https://www.framer.com/motion/animate-presence/">AnimatePresence</a> component. The AnimatePresence component should be used whenever there is an exit animation defined for the motion component. In our case, this would be the fade-out animation when the content is <strong>exiting</strong> the UI.</p><pre>function ExpandableTag({ unhoveredText, hoveredText }) {<br>  const [isHovering, setIsHovering] = useState(false);<br>  return (<br>    &lt;div<br>      className=&quot;inline-block rounded-lg relative text-gray-300 bg-gray-900 ring-1 ring-gray-800 px-4 py-1.5 tracking-wider text-sm font-medium whitespace-nowrap&quot;<br>      onMouseEnter={() =&gt; setIsHovering(true)}<br>      onMouseLeave={() =&gt; setIsHovering(false)}<br>    &gt;<br>      &lt;AnimatePresence&gt;<br>        &lt;motion.span initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}&gt;<br>          {isHovering ? hoveredText : unhoveredText}<br>        &lt;/motion.span&gt;<br>      &lt;/AnimatePresence&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>This alone does not solve the problem, Framer Motion does not know when your animations should run, so by default, it only runs when the component is first mounted. We want the animation to run when the user hovers and unhovers the element(as that is when the contents change), and this is already tracked by the isHovering state variable. To tell Framer Motion to run the animations, we can simply set the key prop such that it changes when we want the animations to run. In our case, that would be setting the key to something based on isHovering state variable.</p><p>Also, since we don’t want the entry animations to run when the component is first mounted, we can opt out of this behavior by setting the initial prop in the AnimatePresence component to false</p><pre>function ExpandableTag({ unhoveredText, hoveredText }) {<br>  const [isHovering, setIsHovering] = useState(false);<br>  return (<br>    &lt;div<br>      className=&quot;inline-block rounded-lg relative text-gray-300 bg-gray-900 ring-1 ring-gray-800 px-4 py-1.5 tracking-wider text-sm font-medium whitespace-nowrap&quot;<br>      onMouseEnter={() =&gt; setIsHovering(true)}<br>      onMouseLeave={() =&gt; setIsHovering(false)}<br>    &gt;<br>      &lt;AnimatePresence<br>        initial={false} <br>      &gt;<br>        &lt;motion.span<br>          initial={{ opacity: 0 }}<br>          animate={{ opacity: 1 }}<br>          exit={{ opacity: 0 }}<br>          key={isHovering ? &#39;hovering&#39; : &#39;unhovering&#39;} <br>        &gt;<br>          {isHovering ? hoveredText : unhoveredText}<br>        &lt;/motion.span&gt;<br>      &lt;/AnimatePresence&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><figure><a href="https://akashhamirwasia.com/blog/expandable-tags-with-framer-motion-and-react"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jWCNQKkVtqFxif3edT7bKQ.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer and open reading experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c22b9f77e10c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create stunning 3D text with custom fonts in Three.js]]></title>
            <link>https://medium.com/@AkashHamirwasia/create-stunning-3d-text-with-custom-fonts-in-three-js-bd659b97e5ef?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd659b97e5ef</guid>
            <category><![CDATA[react-three-fiber]]></category>
            <category><![CDATA[fonts]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webgl]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 13:29:48 GMT</pubDate>
            <atom:updated>2024-04-12T18:33:25.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5imGNfDNXN4-issw8H80g.png" /></figure><p>When doing anything 3D on the web, the first library that comes up in a developer’s mind is Three.js. Three.js provides high-level abstractions to draw 3D graphics using WebGL in the browser. I have been playing around with it quite a bit recently for 3D text rendering and realized that using custom font faces is a pain, especially when you want a simple way to render custom fonts from CDNs like Google Fonts, Fontsource. There’s very little documentation on this topic online and I hope this article helps in filling that gap.</p><h3>Elements of 3D text rendering</h3><p>Let’s take a look at the different pieces involved at high level for rendering Text in Three.js.</p><h3>TextGeometry</h3><p>Three.js exposes a <a href="https://threejs.org/docs/#examples/en/geometries/TextGeometry">TextGeometry</a> class which is specialized for creating the underlying geometry for a text. Think of “geometry” as a set of vertices, edges, faces – basically the structure of the object. TextGeometry has various options to customize font face, size, thickness, bevel, etc. The example usage of this class in the documentation shows the following code snippet.</p><pre>const loader = new FontLoader();<br><br>loader.load(&#39;fonts/helvetiker_regular.typeface.json&#39;, function (font) {<br>  const geometry = new TextGeometry(&#39;Hello three.js!&#39;, {<br>    font: font,<br>    size: 80,<br>    height: 5,<br>    // other options...<br>  });<br>});</pre><h3>FontLoader</h3><p>Notice the FontLoader class in the above snippet? It is responsible for creating a <a href="https://threejs.org/docs/#examples/en/loaders/FontLoader">FontLoader</a> instance that deals with <strong>loading custom fonts</strong> that can be used by TextGeometry to create the text in that font face.</p><p>The load() method of the FontLoader instance takes a file path / URL to the font file and a callback function which gets called with the loaded font data. This font data can then be passed to TextGeometry&#39;s constructor for creating a text geometry in that font.</p><h3>Mesh and Material</h3><p>The text geometry cannot be rendered as is, it has to first be converted to a Mesh object. A Mesh holds the geometry definition and the materials applied to it which is used by the renderer to render that object. In the <a href="https://akashhamirwasia.com/blog/create-stunning-3D-text-with-custom-fonts-in-threejs#mesh-and-material">example here</a>, I assign a <a href="https://threejs.org/docs/?q=materia#api/en/materials/MeshStandardMaterial">MeshStandardMaterial</a> to the Text object. You can read more about the options that can be set in the material at the documentation linked with it.</p><p>Seems straightforward until you notice something strange in that font file path — &#39;fonts/helvetiker_regular.typeface.json&#39;. See that <strong>.json</strong> extension? Seems weird right? Most of us are familiar with standard font file formats like <strong>TTF</strong>, <strong>WOFF</strong>, <strong>WOFF2</strong>, etc. but the FontLoader only understands font files in <strong>.json</strong> format! My next question was – how do I convert my existing font files in one of the standard font file formats mentioned above to the JSON format supported by FontLoader?</p><h3>Facetype.js</h3><p>The documentation of FontLoader class talks about a tool called <a href="https://gero3.github.io/facetype.js/">facetype.js</a> which can be used for converting font files to the JSON format. The tool asks you to choose a font file, and it converts it to a JSON or a JS file. The JSON file can then be included in the source code and loaded in Three.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bZS45OIAUFUV03QZ.jpg" /></figure><p>The <a href="https://github.com/gero3/facetype.js">GitHub repo</a> of the project indicates that it is not published as a library that can be used in other projects. This kinda leaves us with two options if we want to load fonts dynamically from something like <a href="https://fonts.google.com/">Google Fonts</a>:</p><ol><li>Download <em>all the</em> font source files(in TTF format) from Google Fonts, convert them to static JSON format using the facetype.js tool, then include them in the source code of the project and load them in Three.js. This is not scalable as the Google Fonts library is ever-expanding and each font has various font weights(normal, semi-bold, bold, etc.) and font styles(normal, italicized). Converting each of them to JSON format and serving them from our servers is a waste of resources — time, bandwidth, and even money 💸!</li><li>Use the <a href="https://github.com/gero3/facetype.js/tree/gh-pages/javascripts">JavaScript files</a> from the source code of facetype.js. The JS files can be included in the source code of the project and Google Fonts CDN and APIs can be used to fetch the required TTF font files. Once the file is fetched, the relevant functions can be called(from the JS files that were included from facetype.js) to convert the TTF data to JSON format <strong>on-the-fly</strong>. Finally, this JSON data can then be loaded in Three.js. This approach is far better than the previous method but the downside to it is that it includes external JS scripts without a package manager. We won’t get any future updates if the scripts change(unless the changes are manually included in our project), and it may be tricky to use it with ES6-imports and TypeScript.</li></ol><figure><a href="https://akashhamirwasia.com/blog/create-stunning-3D-text-with-custom-fonts-in-threejs"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuOpSfrshL01mELuZ-Xriw.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer and open reading experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd659b97e5ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Variant Groups in TailwindCSS]]></title>
            <link>https://medium.com/@AkashHamirwasia/variant-groups-in-tailwindcss-2d189e3b14b7?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d189e3b14b7</guid>
            <category><![CDATA[tailwind-css]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[build-tool]]></category>
            <category><![CDATA[vites]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 12:22:41 GMT</pubDate>
            <atom:updated>2024-04-12T18:33:35.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>Variant Groups in Tailwind CSS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dhk8yvnjfabP8aIdh8P7EA.png" /></figure><h3>Video version of this blog</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrChBDxzRAwM&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrChBDxzRAwM&amp;image=http%3A%2F%2Fi.ytimg.com%2Fvi%2FrChBDxzRAwM%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/a359a187379092d571bc531c59e45fd1/href">https://medium.com/media/a359a187379092d571bc531c59e45fd1/href</a></iframe><p>One of the things I like about build tools is the amount of customization it gives you to do “magical” things. With a correctly configured build tool, you can improve the life of a developer without them even realizing it! This is exactly what I explored very recently with Tailwind CSS and Vite. To add support for one of the most requested features in Tailwind CSS — <strong>Variant Groups</strong> using build tool modifications.</p><h3>What’s a variant group?</h3><p>Before going into what variant groups are, let’s first recall what <strong>“variants”</strong> are in Tailwind CSS.</p><p>Variants in Tailwind CSS are a way to apply certain utility styles when a particular condition defined by that variant is met. There are a ton of variants available, from pseudo selectors like hover:, focus:, to breakpoints like sm:, lg:, to crazier ones like dark: for applying styles when dark mode is turned on.</p><p>Thus, we can make use of these variants to style various states of a particular element declaratively. Here’s an example of an input element in React styled with Tailwind CSS (this one is right from their <a href="https://tailwindcss.com/docs/hover-focus-and-other-states#form-states">docs</a>):</p><pre>&lt;input<br>  type=&quot;text&quot;<br>  className=&quot;mt-1 block w-full px-3 py-2 bg-white border<br>    border-slate-300 rounded-md text-sm shadow-sm<br>    placeholder-slate-400<br>    focus:outline-none focus:border-sky-500 focus:ring-1<br>    focus:ring-sky-500<br>    disabled:bg-slate-50 disabled:text-slate-500<br>    disabled:border-slate-200 disabled:shadow-none<br>    invalid:border-pink-500 invalid:text-pink-600<br>    focus:invalid:border-pink-500 focus:invalid:ring-pink-500&quot;<br>/&gt;</pre><p>That’s a looooong list of classes! This isn’t even complete yet, we have to <em>stack</em> other variants for dark mode support, responsive styles, etc. and the list only grows from here.</p><p>If you take a look at the classes again, you’ll notice that a few things are repeated multiple times. Yes, its focus:, disabled:, invalid:, and focus:invalid: variants repeat multiple times for each utility class. Can we reduce this duplication? It should reduce the cumbersome of typing each of these variants multiple times and also make the code a bit more terse and easy to read.</p><h4>👋 Say hello to <strong>Variant groups</strong>!</h4><p>Variant groups solve exactly this. It’s a way to <strong>group utility classes</strong> sharing a common variant to eliminate the repeating variant applied to individual utility classes. Classes like hover:bg-purple-500 hover:text-white become hover:(bg-purple-500 text-white) where bg-purple-500 and text-white are implicitly a part of the hover: variant that has been collectively applied to the group.</p><p>Using variant groups, the code above for the input can be updated to the following:</p><pre>&lt;input<br>  type=&quot;text&quot;<br>  className=&quot;mt-1 block w-full px-3 py-2 bg-white border<br>    border-slate-300 rounded-md text-sm shadow-sm<br>    placeholder-slate-400<br><br>    focus:(outline-none border-sky-500 ring-1 ring-sky-500)<br><br>    disabled:(bg-slate-50 text-slate-500 border-slate-200 shadow-none)<br><br>    invalid:(border-pink-500 text-pink-600)<br><br>    focus:invalid:(border-pink-500 ring-pink-500)&quot;<br>/&gt;</pre><p>This is easier for both the eyes and the fingers which type them! It brings in a subtle organization in the code too, with styles for a particular state grouped neatly in a single place. As good as it looks, Tailwind CSS does not currently support variant groups like this. There are various <a href="https://github.com/tailwindlabs/tailwindcss/discussions/8337">discussions</a> around this topic but most of them lead to an unfortunate dead-end.</p><h3>Why don’t variant groups work?</h3><p>This is quite easy to explain. What we’ve just done with grouping multiple classes into a single unit is not a concept defined in the CSS spec. A class name string like invalid:(border-pink-500 text-pink-600) is interpreted as two different classes:</p><ul><li>invalid:(border-pink-500 ,</li><li>text-pink-600)</li></ul><p>There’s no concept of grouping with parenthesis and the second class above does not have any idea about the variant context it is in(here invalid:).</p><p>Thus, even if Tailwind CSS was somehow able to generate the correct styles for the above classes, <strong>the browser won’t understand how these individual classes are related</strong>.</p><h3>But hey, Windi CSS already does this!</h3><p>Yes, <a href="https://windicss.org/">Windi CSS</a> already has this <a href="https://windicss.org/features/variant-groups.html#variant-groups">exact feature</a> we are looking for, and it works really well out-of-the-box. So how is it able to solve the above limitation? Should I just use Windi CSS?! My answer to the second question would be a yes <em>if you can</em> 😛, as Windi CSS has almost complete feature-parity with Tailwind CSS along with some extra features(like Variant groups).</p><p>But that’s not the complete solution. If you are already using Tailwind CSS and moving to Windi CSS is difficult(as both are technically built in different ways), we need some approach(and <em>hacks</em>) to get variant groups working in Tailwind CSS.</p><h3>Build tools to the rescue</h3><p>The way we can solve the above browser limitation is by expanding the class names to the long format so that the browser can understand them. The developer gets to write short-form variant group syntax, but the browser magically gets the long-form expanded syntax which it is already able to understand.</p><p>invalid:( border-pink-500 text-pink-600 )</p><p><em>gets converted to</em></p><p>invalid:border-pink-500 invalid:text-pink-600</p><p><em>automagically!</em></p><p>When this conversion happens is an important decision to make. We could have a simple JS function that does this conversion in the <strong>runtime</strong>, or we can also leverage the build tools and do this conversion at the <strong>build time</strong> itself. The advantage of doing it in the build time is that it reduces the overhead at the runtime and allows you to do more important things rather than transforming class names! So, let’s go ahead and write some build time configs to perform these transformations.</p><figure><a href="https://akashhamirwasia.com/blog/variant-groups-in-tailwindcss"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fuOpSfrshL01mELuZ-Xriw.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer and open reading experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d189e3b14b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an expressive API for custom confirm dialogs in React]]></title>
            <link>https://medium.com/@AkashHamirwasia/building-an-expressive-api-for-custom-confirm-dialogs-in-react-da9e6bc84f26?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/da9e6bc84f26</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[api-development]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Thu, 11 Aug 2022 19:18:49 GMT</pubDate>
            <atom:updated>2024-04-12T18:33:53.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U4TC0d3NpN0s5mRnA_TByA.png" /></figure><h3>Video version of this blog</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYulvC5C81zs%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYulvC5C81zs&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/63f163101766f3901fe9640137aa9845/href">https://medium.com/media/63f163101766f3901fe9640137aa9845/href</a></iframe><p>Confirm Dialogs are one of the most common user interactions seen in today’s apps when the user tries to perform some critical action that cannot be undone. I’m sure you would have come across something like this before, be it the dialog you see while deleting a repo on GitHub, or a project on Google Cloud platform, they are fundamentally this interaction. In fact, all browsers have a native API built around this called <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm">Window.confirm()</a>, which takes the confirmation from a user for some action the developer has specified. While it’s not the most customizable in terms of looks and functionality, it does have an easy-to-use API.</p><h3>A simple Confirm Dialog in React</h3><p>Building a simple Confirm Dialog component is easy in React. Just build it on your existing Modal component or something new altogether. Imagine I have a &lt;Alert /&gt; component which takes the following props:</p><pre>&lt;Alert<br>  isOpen={true}             // Whether the dialog is open<br>  onClose={() =&gt; {}}        // Event when user closes the dialog or<br>                            // clicks on &#39;Cancel&#39;<br>  title=&quot;&quot;                  // Title of the dialog<br>  description=&quot;&quot;            // Description text of the dialog<br>  confirmBtnLabel=&quot;&quot;        // Text shown in the button which<br>                            // &quot;confirms&quot; the action<br>  onConfirm={() =&gt; {}}      // Event when user &quot;confirms&quot; the action<br>/&gt;</pre><p>It is quite easy to use this component as a consumer to show a Confirm Dialog. Just include it in your component code and add some extra state that controls the visibility. Then toggle this state in appropriate event handlers and perform the critical mutation only when onConfirm event of &lt;Alert /&gt; fires. This is how it looks:</p><pre>function Demo() {<br>  const [showAlert, setShowAlert] = useState(false);<br>  const handleDeleteAll = () =&gt; {<br>    // Perform your dangerous critical action here.<br>    // Remember to close your alert<br>    setShowAlert(false);<br>  };<br><br>  return (<br>    &lt;Button onClick={() =&gt; setShowAlert(true)}&gt;<br>      Delete all<br>    &lt;/Button&gt;<br>    &lt;Alert<br>      isOpen={showAlert}<br>      onClose={() =&gt; setShowAlert(false)}<br>      title=&quot;Delete all&quot;<br>      description=&quot;Are you sure you want to delete everything?&quot;<br>      confirmBtnLabel=&quot;Yes&quot;<br>      onConfirm={handleDeleteAll}<br>    /&gt;<br>  );<br>}</pre><p>Works right? Of course, it does. But let’s take a closer look at the flaws in the structure of the code above:</p><ul><li>The actual call to the function that performs the dangerous action has moved from the event which would have initiated it, to the onConfirm handler of the &lt;Alert /&gt; component, and it only sets the respective Confirm Dialog to be visible.<br>This is not a good thing to have especially from a code readability and maintenance perspective. If you try to find which action the &lt;Button&gt; is actually performing, you would have to find the state variable it is changing, then the corresponding &lt;Alert /&gt; component that is using this state, then look at the function it is calling in onConfirm event. Too many dependencies and indirect coupling.</li><li>Remembering to hide the dialog when you are <em>done with your action.</em> Notice on line 8 you have to remember to close the dialog once its job is done. You also have to repeat that same call on line 19. The consumer is responsible for controlling the visibility of the Confirm Dialog even though it is such a <em>one-time thing</em> with a fixed entry and exit flow.</li><li>Reusable component? Think again. The &lt;Alert /&gt; component encapsulates the UI to be shown and makes it reusable, but leaves the functionality to the consumer. Imagine adding more Confirm Dialogs to the same component and you’ll have a bunch of &lt;Alert /&gt; and corresponding state variables and the calls to their setters littered in your component code.</li></ul><h3>Inspiration</h3><p>Looking around for inspiration on what an <em>ideal</em> Confirm Dialog API could look like, I just so happened to stumble across the browser native window.confirm() API, which has been there since like forever! I did not expect it to work out in this scenario, thinking it’s too rigid and not very flexible. But I took a chance and refactored my code to use this API, to see how my code would be structured if I had a similar API but to show my custom Confirm Dialog.</p><p>After modifying the above, this is what we get:</p><pre>function Demo() {<br>  const handleDeleteAll = () =&gt; {<br>    const choice = window.confirm(<br>      &quot;Are you sure you want to delete everything?&quot;<br>    )<br>    if (choice) {<br>      // Perform your dangerous critical action here.<br>    }<br>  }<br><br>  return &lt;Button onClick={handleDeleteAll}&gt;Delete all&lt;/Button&gt;<br>}</pre><p>That’s it! A single one-liner that just replaced like 40–50% of my old code. If you don’t know how <a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm">window.confirm()</a> works, here’s a small summary:</p><ul><li>The function takes a string message that will be shown to the user in the dialog.</li><li>The dialog has two buttons — ‘Cancel’ and ‘Ok’.</li><li>If the user clicks on ‘Ok’, the function returns true, otherwise false.</li></ul><p>After seeing this change, I knew this was the kind of API I wanted. It solves all the flaws of previous code and there are no extra state variables or calls to setters to change the visibility of anything. All that is taken care of by the confirm method itself.</p><p>Apart from the readability benefits, this API also makes it very easy to add Confirm Dialog behavior to existing functions. Just add a function call and a guard to the critical mutation to run it only when the user clicks on ‘Ok’.</p><p>The only thing I wanted in this API was a higher degree of customizability of the Confirm Dialog shown to the user. This was easier with the previous approach thanks to the props exposed by the &lt;Alert /&gt; component.</p><h3>Let’s build the API</h3><p>One thing I immediately realized was to have a shared &lt;Alert /&gt; component across my entire app instead of having multiple &lt;Alert /&gt;s spread across many components. This decision was mainly because at any point in time, the user would only get to see one Confirm Dialog. There will not be a situation when there are two Confirm Dialogs shown to the user at the same time(at least for my use case).</p><p>Having a shared &lt;Alert /&gt; at a higher level would keep the logic of managing the visibility of the component at one place and make it easier for other components to <strong>“hook” into using this functionality</strong> when needed. This can be done using React Context. We can create a context provider that would manage the rendering of the Confirm Dialog and also expose a function that other components could “hook” into to use it.</p><pre>import { createContext, useContext, useState } from &quot;react&quot;<br><br>const ConfirmDialog = createContext()<br><br>export function ConfirmDialogProvider({ children }) {<br>  const [state, setState] = useState({ isOpen: false })<br><br>  return (<br>    &lt;ConfirmDialog.Provider value={setState}&gt;<br>      {children}<br>      &lt;Alert isOpen={state.isOpen} /&gt;<br>    &lt;/ConfirmDialog.Provider&gt;<br>  )<br>}<br><br>export default function useConfirm() {<br>  return useContext(ConfirmDialog)<br>}</pre><p>Just with this context setup, the consumer can now use the useConfirm hook to programmatically show the Confirm Dialog in a function call.</p><pre>import useConfirm from &quot;./ConfirmDialog&quot;<br><br>function Demo() {<br>  const confirm = useConfirm()<br><br>  const handleDeleteAll = () =&gt; {<br>    confirm({ isOpen: true })<br>    // Perform your dangerous critical action here.<br>  }<br><br>  return &lt;Button onClick={handleDeleteAll}&gt;Delete all&lt;/Button&gt;<br>}</pre><p>This brings us one step closer to the window.confirm() API, but there is no option to close the Confirm Dialog or show some custom title and description. Right now we are only allowing the consumer to control the isOpen prop of the shared &lt;Alert /&gt; component, can we update it to allow passing other props like title and description? Also, do we really want the consumer to set isOpen: true every time they want to show the Confirm Dialog? It’s clear that when the consumer is calling confirm(), they want to implicitly show the dialog. Let’s make these changes now.</p><pre>import { useState } from &quot;react&quot;<br><br>export function ConfirmDialogProvider({ children }) {<br>  const [state, setState] = useState({ isOpen: false })<br>  const confirm = (data) =&gt; {<br>    setState({ ...data, isOpen: true })<br>  }<br>  return (<br>    &lt;ConfirmDialog.Provider value={confirm}&gt;<br>      {children}<br>      &lt;Alert {...state} /&gt;<br>    &lt;/ConfirmDialog.Provider&gt;<br>  )<br>}</pre><p>We have created a new function called confirm in the context provider’s wrapper component which takes the props for &lt;Alert /&gt; as arguments and stores it in the local state along with setting isOpen to true. We then pass this function as a value of the context and update the &lt;Alert /&gt; component to spread all the values of state as props.</p><p>Now the consumer can simply call the confirm() function and set the title, description, and other props as they prefer without having to explicitly set isOpen to true.</p><pre>import useConfirm from &#39;./ConfirmDialog&#39;;<br><br>function Demo() {<br>  const confirm = useConfirm();<br><br>  const handleDeleteAll = () =&gt; {<br>    confirm({<br>      title: &quot;Delete all&quot;,<br>      description: &quot;Are you sure you want to delete everything?&quot; <br>      confirmBtnLabel: &quot;Yes&quot;,<br>    });<br>    // Perform your dangerous critical action here.<br>  };<br><br>  return (<br>    &lt;Button onClick={handleDeleteAll}&gt;<br>      Delete all<br>    &lt;/Button&gt;<br>  );<br>}</pre><figure><a href="https://akashhamirwasia.com/blog/building-expressive-confirm-dialog-api-in-react/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UwAzUMM2sjehBWSbos7CpA.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer and open reading experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da9e6bc84f26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to and not to build Sidebar layouts on the web]]></title>
            <link>https://medium.com/@AkashHamirwasia/how-to-and-not-to-build-sidebar-layouts-on-the-web-b8bf0444b315?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8bf0444b315</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[design-thinking]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Sat, 05 Mar 2022 11:26:45 GMT</pubDate>
            <atom:updated>2024-04-12T18:34:04.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tf2OTuZeHsApmAPjgd089w.png" /></figure><p>Sidebar layouts have become one of the most common layouts on the web today. There are various studies and articles online that show time and time again that users prefer vertical sidebar navigation layouts over horizontal navigation layouts because of the ease of navigation and flexibility it provides. I’m sure most of your day-to-day apps have some form of a sidebar.</p><p>On the web, there are countless ways of implementing this layout with HTML and CSS. Unfortunately, this flexibility has also led to <em>ugly</em> and <em>hacky</em> ways of building sidebars that sacrifice accessibility and code readability. In this article, I shall be going through some of these <em>not-so-good</em> approaches and also build towards an approach that I find works best for sidebar layouts.</p><h3>Understanding what we’ll be building</h3><p>We will be building a fairly basic layout where the sidebar shows on the left on the desktop with the rest of the content on the right. The content should scroll vertically when it overflows and the sidebar should remain stuck on the left side. I’ll only use HTML and CSS for all the demos, so that you can easily add them in your existing projects.</p><h3><strong>🤮 Approach 1: The </strong>absolute<strong>ly ugly way</strong></h3><p>Using absolute positioning to position the sidebar and then adding a margin to the rest of the content to offset the sidebar width is an approach I find lingering online oddly many times. I’m not sure in which case one should use this approach today over others, because speaking of browser support, even approach 2 has great browser support and is still better than this. Anyways, here’s the code and the result we get after a pretty basic implementation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fm5zopi&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fm5zopi&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fm5zopi%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/59d51f14b3871f12d1f82538b6d432e7/href">https://medium.com/media/59d51f14b3871f12d1f82538b6d432e7/href</a></iframe><p>While the above result looks exactly like how we want it to be, let’s peek under the hood to see some problems. If the rest of the content exceeds the height of the screen, it will require the user to scroll vertically. But this also causes the sidebar to scroll! We want the sidebar to be fixed when the user scrolls through the rest of the content. To fix this, we must make the content &lt;div&gt; scroll when it overflows and not the rest of the body. I like to call this <strong>“scroll hack”</strong>.</p><p>Let’s implement this change and see how it looks.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fjf5u91&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fjf5u91&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fjf5u91%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e200e82039ada988f16a4aed6b02bda/href">https://medium.com/media/6e200e82039ada988f16a4aed6b02bda/href</a></iframe><p>And things work as expected. Are we done? Let’s take a step back and see what we have done.</p><ol><li>Used position absolute on sidebar element to position it on the left side.</li><li>Added a margin to the rest of the content just to accommodate the space taken by the sidebar.</li><li>Implemented <em>scroll hack</em> to prevent the sidebar also from scrolling.</li></ol><p>Because of points 2 and 3, <strong>this approach is quite brittle</strong>. If you later on decide to change the width of the sidebar, you must also remember to update the margin on the rest of the content. While this can be improved by using CSS custom properties, I think you’ll still end up with ugly code later on if your application grows to have multiple sidebars(eg. like in Slack and Discord).</p><p>Point 3 is also bad for accessibility. Unless your sidebar also has a scrollbar, scrolling on the sidebar usually scroll through the main content of your app. This behavior can be seen in apps like Twitter, GitLab, DuckDuckGo. It gets very dirty to achieve this behavior with the absolute positioning approach.</p><p>A point to note in this approach is that while we are using absolute positioning on the sidebar, our end result is for a fixed sidebar that does not move when the user scrolls through the rest of the site. This brings us to the next approach where instead of using absolute, we shall try fixed positioning itself.</p><figure><a href="https://akashhamirwasia.com/blog/how-to-and-not-to-build-sidebar-layouts"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0clQ_NqbhPpBwv3_W9FfQQ.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer and open reading experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8bf0444b315" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building highlighted input field in React.js]]></title>
            <link>https://medium.com/@AkashHamirwasia/building-highlighted-input-field-in-react-js-8627c421f424?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/8627c421f424</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[input-field]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Thu, 23 Dec 2021 08:23:38 GMT</pubDate>
            <atom:updated>2022-01-06T07:34:17.701Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoSZgT0giV_xP2RX4U10qA.jpeg" /></figure><p>Creating an Input component that renders its contents differently based on the user’s actions or type of content is a challenge in web development today. Ask any web developer who has tried building one. I’m sure they would shed a tear or two and tell you how they tried building one using the outdated and non-standardized APIs, eventually giving up to a hefty 3rd party library.</p><p>In this post, I would like to share my experience trying to build something like this, the challenges I faced, and how I ended up with a sleek solution that’s not only simple to code but also achieves the functionality I was aiming for.</p><h3>What will I be building</h3><p>It is important to clearly define what I’ll be building, as I will <strong>not</strong> be showing you how to build a full-fledged rich text editor, or any type of WYSIWYG thing. My use-case might be very trivial, and the solution I’ll be presenting <strong>might not work</strong> for your use-case.</p><p>I wanted to build a <strong>single line</strong> text input field which <strong>highlights different parts</strong> of the input that <strong>match a given regular expression</strong>. An example of this type of input is Postman’s environment variable input fields as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*qgkGi_jAfQw5wT5VnemxmA.gif" /><figcaption><a href="https://www.postman.com/">Postman</a>’s environment variable input field demo</figcaption></figure><h3>contenteditable attribute</h3><p>Naturally, the first thing that comes to the mind to build something like this is to use the contenteditable attribute. It allows any HTML element&#39;s content to be edited by the user, and also render the HTML at the same time. Most RTE editors today make use of this attribute underneath to make things work. While it is an interesting attribute and might solve what I&#39;m building, it has a long list of flaws:</p><ul><li><strong>It is dangerous</strong> — This attribute allows the user to enter any valid HTML strings, and in turn, can render them on the browser. Clearly a room for tons of security attacks if the input is not sanitized correctly before storing it in some database.</li><li><strong>Too many edge cases</strong> — Rendering content differently is just one part of the puzzle. contenteditable attribute doesn&#39;t handle any of the extra edge cases that an &lt;input&gt; element handles for us. Things like copy-paste support, undo-redo histories, standard browser support, and many more which we take for granted when using &lt;input&gt;.</li><li><strong>Highly imperative, not declarative</strong> — All the APIs to control the behavior of this attribute are very imperative and low level. You are responsible for managing the cursor position, sanitizing the content. You’ll be writing more code to make basic things work than writing the code to define your needs.</li><li><strong>No UI framework support</strong> — At least from my research, none of the popular UI layer frameworks(React, Vue, etc.) control the rendering inside an element marked as contenteditable. So the developer is responsible for managing how and when things change</li></ul><figure><a href="https://akashhamirwasia.com/blog/building-highlighted-input-field-in-react"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1V9UiZeTwyTyore83DqAhA.png" /></a><figcaption>Why separate website? That’s because I want to provide a richer reading and coding experience to all my readers. 🙂</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8627c421f424" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Color Pop effect using BodyPix and Tensorflow.js]]></title>
            <link>https://medium.com/data-science/color-pop-effect-using-bodypix-and-tensorflow-js-a584ddc48a02?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/a584ddc48a02</guid>
            <category><![CDATA[google-photos]]></category>
            <category><![CDATA[tensorflowjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[bodypix]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 13:13:22 GMT</pubDate>
            <atom:updated>2022-12-08T14:39:26.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>Color Pop effect using BodyPix and TensorFlow.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFUAI82593bpul9wfxvRVg.png" /><figcaption>Photo of the girl found on <a href="https://unsplash.com/photos/tBWmzPuQo3w">Unsplash</a></figcaption></figure><p>One of my favorite little features of the Google Photos app is its <strong>Color Pop</strong> effect. The Color Pop(aka Color splash) effect makes the subject(usually a person) stand out from the rest of the image. The subject remains in color, but the background is made grayscale. This gives a pleasant look in most cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*Aka4tGMrafqHBsCQb_A3Dg.jpeg" /><figcaption>Example of color pop effect. Original left, Color pop right</figcaption></figure><p>While this feature works incredibly well, Google Photos only applies this effect to some images it finds easy to detect humans. This limits its potential and does not allow users to manually choose images to apply this effect. This left me thinking, is there any way to achieve a <em>similar effect</em> but with <em>my selection of images</em>?</p><p>Most apps don’t provide an automated solution. It requires users to manually paint this effect on their image, which is time-consuming and error-prone. Can we do something better? Something smart like Google Photos? Yes! 😉</p><p>Understanding how this effect can be achieved manually, I find the following two major steps:</p><ul><li>Creating a mask around people in the image (aka segmentation).</li><li>Using the mask to preserve the color of people, while making the background grayscale.</li></ul><h3>Segmenting people from the image</h3><p>This is the most important step in this process. A good result depends highly on how good the segmentation mask is created. This step requires some machine learning, as it’s already proven to work well in these cases.</p><p>Building and training a machine learning model from scratch would take too much time (<em>Says the person who doesn’t know ML</em> 😛), so I searched if there was a pre-trained model that I could use. A quick search led me to <a href="https://github.com/tensorflow/tfjs-models/tree/master/body-pix">BodyPix</a> which is a <a href="http://tensorflow.org/js/">Tensorflow.js</a> model that’s made for person segmentation and pose detection.</p><p><a href="https://github.com/tensorflow/tfjs-models/tree/master/body-pix">tensorflow/tfjs-models</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Jvrhdz0GlwCrsY5njOB_Tg.gif" /><figcaption>Live demo of BodyPix from its creators. Try it out <a href="https://storage.googleapis.com/tfjs-models/demos/body-pix/index.html">here</a></figcaption></figure><p>As you can see, it does a good job of detecting a person (including multiple people) in an image and works relatively fast on browsers. The rainbow-colored area is the <strong>segmentation map</strong> that we need. 🌈</p><p>Let’s set up a basic HTML file with the Tensorflow.js and BodyPix CDN scripts.</p><pre>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;title&gt;Color Pop using Tensorflow.js and BodyPix&lt;/title&gt;<br>  &lt;/head&gt;<br><br>&lt;body&gt;<br>  &lt;!-- Canvas for input and output --&gt;<br>  &lt;canvas&gt;&lt;/canvas&gt;<br>  <br>  &lt;!-- Load TensorFlow.js --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.2&quot;&gt;&lt;/script&gt;<br>  &lt;!-- Load BodyPix --&gt;<br>  &lt;script src=&quot;https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix@2.0&quot;&gt;&lt;/script&gt;<br>  <br>  &lt;!-- Color Pop code--&gt;<br>  &lt;script src=&quot;colorpop.js&quot;&gt;&lt;/script&gt;<br>  <br>&lt;/body&gt;<br>&lt;/html&gt;</pre><h4>Loading Image in Canvas</h4><p>Before segmentation, it is important to understand how to <strong>manipulate pixel data of images</strong> in JavaScript. An easy approach for this is to use HTML Canvas. Canvas makes it easy to read and manipulate pixel data of images, once loaded. It’s also compatible with BodyPix, win-win!</p><pre>function loadImage(src) {<br>  const img = new Image();<br>  const canvas = document.querySelector(&#39;canvas&#39;);<br>  const ctx = canvas.getContext(&#39;2d&#39;);<br><br>  // Load the image on canvas<br>  img.addEventListener(&#39;load&#39;, () =&gt; {<br>    // Set canvas width, height same as image<br>    canvas.width = img.width;<br>    canvas.height = img.height;<br>    ctx.drawImage(img, 0, 0);<br><br>    // TODO: Implement pop()<br>    pop();<br>  });<br><br>  img.src = src;<br>}</pre><h4>Loading BodyPix model</h4><p>The README of BodyPix does a good job of explaining how to use the model. An important part of loading the model is the architecture you use. ResNet is more accurate but slower, whereas MobileNet is less accurate but faster. While building and testing this effect, I’ll be using MobileNet. Later I’ll switch to ResNet and compare the results.<br>Note: It’s better to load the model once and reuse it for segmentation multiple times since it has to download the architecture each time the model is loaded. In the following examples, the model will get loaded every time the color pop effect is applied to an image(to keep the main functionality clear).</p><pre>async function pop() {<br>  // Loading the model<br>  const net = await bodyPix.load({<br>    architecture: &#39;MobileNetV1&#39;,<br>    outputStride: 16,<br>    multiplier: 0.75,<br>    quantBytes: 2<br>  });<br>}</pre><h4>Performing segmentation 👥</h4><p>BodyPix has a variety of functions to segment an image. Some are suited for body part segmentation, and others for single/multi-person segmentation. All of them are explained in detail on their <a href="https://github.com/tensorflow/tfjs-models/tree/master/body-pix">README</a>. segmentPerson() will work in this case as it creates a segmentation map for every person in the image in one single map. Also, it’s relatively faster than the rest of the methods.</p><p>segmentPerson() accepts a Canvas element as the input image, along with some configuration settings. internalResolution setting specifies the factor by which the input image is resized before segmentation. I’ll be using full for this setting, as I want crisp segmentation maps. I would strongly suggest you read about other settings and play around with those.</p><pre>async function pop() {<br>  // Loading the model<br>  const net = await bodyPix.load({<br>    architecture: &#39;MobileNetV1&#39;,<br>    outputStride: 16,<br>    multiplier: 0.75,<br>    quantBytes: 2<br>  });<br>  <br>  // Segmentation<br>  const canvas = document.querySelector(&#39;canvas&#39;);<br>  const { data:map } = await net.segmentPerson(canvas, {<br>    internalResolution: &#39;full&#39;,<br>  });<br>}</pre><p>The result after segmentation is an object(shown below). The major part of the result object is data which is a Uint8Array representing the segmentation map as an array of numbers. I have used ES6 destructuring to take out data as map. This will be used for applying the color pop to the image!</p><pre>{<br>  width: 640,<br>  height: 480,<br>  data: Uint8Array(307200) [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, …],<br>  allPoses: [{&quot;score&quot;: 0.4, &quot;keypoints&quot;: […]}, …]<br>}</pre><h3>Making background grayscale</h3><p>With the segmentation data ready, the next section involves implementing the color pop using the segmentation map to make background grayscale and preserve the color of people in the image. For this, the pixel-level operation of the image is needed, and this is where the canvas element shines. The getImageData() function returns ImageData which contains colors of each pixel in RGBA format. In the code below, I have used destructuring to extract useful data as imgData</p><pre>async function pop() {<br>  // ... previous code<br>  <br>  // Extracting image data<br>  const ctx = canvas.getContext(&#39;2d&#39;);<br>  const { data:imgData } = ctx.getImageData(0, 0, canvas.width, canvas.height);<br>}</pre><h4>Applying the effect</h4><p>With all the ingredients ready, here’s where the color pop magic happens! Let’s start by creating new image data. createImageData() creates a new ImageData where all our modifications to actual image data which will be stored.</p><p>Next, we iterate through pixels in the map, where each element is 1 or 0.</p><ul><li>1 indicates that a <strong>person was detected</strong> at that pixel.</li><li>0 indicates that <strong>no person was detected</strong> at that pixel.</li></ul><p>To make the code more readable, I have used destructuring to extract color data into r g b a variables. Then using the RGB values, appropriate gray color is calculated using the<strong> luminosity method</strong>. There are various ways to calculate the gray values. <a href="http://www.tannerhelland.com/3643/grayscale-image-algorithm-vb6/">This article</a> has a good list of some of these conversion formulas.</p><p>Finally based on the segmentation map value (0 or 1) gray or the actual RGBA color can be assigned to the new image data. Note that the corresponding gray color in RGB is calculated by assigning the same value of gray to all three channels.</p><p>After the processing of each pixel, the new image data is drawn back on the canvas using putImageData() function.</p><pre>async function pop() {<br>  // ... previous code<br>  <br>  // Creating new image data<br>  const newImg = ctx.createImageData(canvas.width, canvas.height);<br>  const newImgData = newImg.data;<br>  <br>  // Apply the effect<br>  for(let i=0; i&lt;map.length; i++) {<br>    // Extract data into r, g, b, a from imgData<br>    const [r, g, b, a] = [<br>      imgData[i*4],<br>      imgData[i*4+1],<br>      imgData[i*4+2],<br>      imgData[i*4+3]<br>    ];<br><br>    // Calculate the gray color<br>    const gray = ((0.3 * r) + (0.59 * g) + (0.11 * b));<br><br>    // Set new RGB color to gray if map value is not 1<br>    // for the current pixel in iteration<br>    [<br>      newImgData[i*4],<br>      newImgData[i*4+1],<br>      newImgData[i*4+2],<br>      newImgData[i*4+3]<br>    ] = !map[i] ? [gray, gray, gray, 255] : [r, g, b, a];<br>  }<br>  <br>  // Draw the new image back to canvas<br>  ctx.putImageData(newImg, 0, 0);<br>}</pre><p>The final image with the color pop effect can be seen applied to the original image. Yay! 🎉</p><h3>Exploring other architectures and settings</h3><p>I performed a few tests with the ResNet and MobileNet architectures. In all sample images, the size of one of the dimensions(width or height) of the image is 1080px. Note that the internal resolution for segmentation was set to full (No shrinking of image during segmentation).</p><p>For my tests, I used the following settings while loading the BodyPix model.</p><pre>// MobileNet architecture<br>const net = await bodyPix.load({<br>  architecture: &#39;MobileNetV1&#39;,<br>  outputStride: 16,<br>  quantBytes: 4,<br>});<br><br><br>// ResNet architecture<br>const net = await bodyPix.load({<br>  architecture: &#39;ResNet50&#39;,<br>  outputStride: 16,<br>  quantBytes: 2,<br>});</pre><h4>Test 1 — Single Person</h4><p>Here both the models detect the girl in the picture. ResNet has better-segmented this image compared to MobileNet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3o2a0u1gCdi9__x06xWs3w.jpeg" /><figcaption>Left to Right: Original sample, MobileNet, ResNet</figcaption></figure><h4>Test 2 — Multiple people</h4><p>This is a little trickier as it has many people with different poses and props around the image. Again ResNet has accurately segmented all the people in the image. MobileNet is also close but misses the edges here and there.<br>Both incorrectly segment a part of the cushion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8ZbONFA2yKla7kFEjeljg.jpeg" /><figcaption>Left to Right: Original sample, MobileNet, ResNet</figcaption></figure><h4>Test 3 — Facing back</h4><p>Another tricky one, where the girl in the image is facing back. Honestly, I was expecting inaccurate detection of the girl in the image, but both ResNet and MobileNet had no problem in this. The segmentation was inaccurate in both the architectures due to the dupatta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaRxp6BpcrSUys3BFnzrCQ.jpeg" /><figcaption>Left to Right: Original sample, MobileNet, ResNet</figcaption></figure><h4>The conclusion from the tests 📋</h4><p>It’s clear from the tests that ResNet performs better segmentation than MobileNet at a cost of higher time. Both do a good job of detecting multiple people in the same image but sometimes fail to segment accurately due to the clothing. Since BodyPix is meant to run with <em>Tensorflow.js in the browser(or in Node.js)</em>, it’s impressive to see how fast it performs when used with correct settings.</p><p>This is how I was able to create the Color Pop effect inspired by Google Photos. All in all, BodyPix is a great model for person segmentation. I would love to use this and Tensorflow.js in some of my future projects. You can find the source code and live working version here: <a href="https://glitch.com/~color-pop-effect">https://glitch.com/~color-pop-effect</a></p><p>I have created a Firebase cloud function for this color pop effect. It uses Tensorflow.js on Node which makes it run much faster than that on the user’s browser. You can check the <a href="https://github.com/blenderskool/color-pop">Color Pop</a> 🌈 project here. I can’t wait to see your ❤️ and contributions to it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a584ddc48a02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/color-pop-effect-using-bodypix-and-tensorflow-js-a584ddc48a02">Color Pop effect using BodyPix and Tensorflow.js</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My look at SvelteJS and how you can start using it]]></title>
            <link>https://medium.com/front-end-weekly/my-look-at-sveltejs-and-how-you-can-start-using-it-aebf7508cea0?source=rss-c73eddb5c7ed------2</link>
            <guid isPermaLink="false">https://medium.com/p/aebf7508cea0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Akash Hamirwasia]]></dc:creator>
            <pubDate>Sun, 29 Sep 2019 15:05:51 GMT</pubDate>
            <atom:updated>2020-09-20T12:48:43.286Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TctFgqaL6zu4VbiSAt-cvg.png" /></figure><p>Naturally, I ignore<em> yet another JS framework </em>type of posts but <strong>Svelte</strong> caught my eye when I saw it making some fuss in the web community. So I gave it a try, and to my dismay, it is better than what I thought! 🧡<br>In this post, I would share some of my thoughts which I had when starting with Svelte and how you can start using it in your web projects.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fupscri.be%2Ff%2F788447%3Fas_embed%3Dtrue&amp;dntp=1&amp;display_name=Upscribe&amp;url=https%3A%2F%2Fupscri.be%2F788447%2F&amp;type=text%2Fhtml&amp;schema=upscri" width="800" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18214d8333adbb5668f31791a3202b60/href">https://medium.com/media/18214d8333adbb5668f31791a3202b60/href</a></iframe><h3>Some background</h3><p>Front-end JavaScript frameworks are used by web developers to build their applications in a more structured and maintainable way. While they have a ton of benefits, the framework itself adds some bulk to your JavaScript bundle, thus increasing the load time of your app by a small margin.</p><p><a href="https://svelte.dev/">Svelte</a> is a JavaScript compiler that takes the source code of the front-end and converts it into native JavaScript code. <strong>This compiled code does not include any code from Svelte itself</strong>, thus generating a more efficient JavaScript bundle that is much smaller in size compared to other popular frameworks. It still uses HTML, CSS, and JavaScript, but with a few specific additions that have led to creators calling it a separate language itself!</p><p>This decrease in size may not seem much for most projects and I would agree on that, but it’s always better to have solutions that tackle a problem differently rather than just reinventing the wheel again and again.</p><h3>Some bits and pieces of Svelte</h3><p>Having used other frameworks, I expect any new framework in 2019 to have the following features.</p><ul><li>Components (including passing props and events)</li><li>Reactivity</li><li>State Management</li><li>Routing</li><li>At the end of the day, an overall improved developer experience 🤘</li></ul><p>Svelte has most of the above-listed features, plus a <strong>really good developer experience</strong>(at least for someone who is just starting). It does not have an official routing library (but unofficial ones do exist and provide basic functionality).</p><h3>Getting started by creating a project</h3><p>You can try Svelte on their <a href="https://svelte.dev/repl">REPL</a> which is a playground where you can directly write your code rather than setting up a project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nIhj5wWLl5_Yjyr7Q6cjlg.png" /><figcaption>Svelte REPL</figcaption></figure><p>All component files in Svelte ends with .svelte extension, and has<strong> three parts associated with it</strong>: JavaScript, Styling for the component, Markup. Following example illustrates basic usage of Svelte</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3456026f497c14746bab1d21aa5572c7/href">https://medium.com/media/3456026f497c14746bab1d21aa5572c7/href</a></iframe><p>If the above code looks confusing, don’t worry, we’ll go through it line by line.<br>export let name = &#39;world&#39; creates a variable. export keyword <strong>marks this as a prop</strong> which can be passed from parent components. ‘world’ is the default value of the prop.<br>let num = 5 creates a <strong>state variable</strong>.<br>function sayHello(){... Creates a function in the component. We’ll use it later. Styling part is self-explanatory, so we’ll skip that.</p><p>&lt;h1&gt;Hello {name}!&lt;/h1&gt; <strong>Interpolation</strong> comes into the picture now. h1 tag has {name} in its content. It gets replaced by the value stored in the name variable we created earlier.<br>&lt;input bind:value={num}&gt; Here we are <strong>binding</strong> the value in the input tag to num, the variable we created earlier. So every time we change the text in the input, it gets stored in num. [Notice how the next line updates in the output when you change the text. This shows reactivity]<br>&lt;p&gt;Double of num: {num * 2}&lt;/p&gt; This also shows interpolation, but we are doing some JavaScript inside the curly braces.<br>&lt;button on:click={sayHello}&gt;Click me!&lt;/button&gt; Here we are handling events. Events follow on:&lt;event-name&gt;={} syntax. Components can also dispatch custom events and they are also handled the same way.</p><p>I won’t be going through concepts like props passing, event dispatching, etc. in detail here cause their <a href="https://svelte.dev/tutorial">interactive tutorial</a> is very good for learning Svelte.</p><h4>Let’s see under the hood 🧐</h4><p>If you see the above code example in my <a href="https://svelte.dev/repl/9af08a5c1c504b3687038358f19bb91a?version=3.12.1">REPL</a>, you can see what our built files look like. Open the <strong>JS output</strong>, to see the JavaScript after compilation(also shown below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uisUpdwfSlDHlDjDSm4GTA.png" /><figcaption>Compiled JavaScript bundle</figcaption></figure><p>At first glance, it might not seem very optimized, and you’re right! This is because the REPL only shows<strong> the compiled ES module of the Svelte components</strong>. It is the job of a bundler to further convert it to commonJS and then minify it to get the production bundle.</p><p>If you see the output more closely, you would see <strong>how short the file itself is</strong>. This is where the compiler shines and gives you a significantly smaller bundle than other frameworks. Let’s now take a look at the <strong>CSS output.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4drryh6zYgNn6RHOV91ig.png" /><figcaption>CSS output</figcaption></figure><p>CSS output(shown above) doesn’t seem too interesting. But wait! What’s that .svelte-bt9zrl? Our App.svelte just has h1 { in the style tags. This is another feature of Svelte! It scopes our styling in component level. This means whatever styles you write in a component, <strong>they get scoped and are applied to only the elements within that component</strong>. This way you won’t have conflicting styles between different components.</p><p>If you want to have global styles(applied to all components), you’d create a separate CSS file and link to the HTML file itself. Ah, the good old way!</p><h3>Building a real project with it</h3><p>After I got myself familiar with how Svelte handles the UI, I decided to give it a shot in trying to develop a <a href="https://github.com/blenderskool/blaze">real project</a> with it. I had a project written in vanilla JavaScript and wanted to see how easy would it be to migrate an existing (relatively simple UI) project to Svelte. I scaffolded the project with the following command.</p><pre>npx degit sveltejs/template my-svelte-project</pre><p>Svelte uses <a href="https://rollupjs.org/">Rollup</a> to build the app. The project structure and the configuration worked out of the box, and I had migrated the existing project in a matter of a few hours.</p><p>The problem came when I wanted to implement Routing. I found out that Svelte does not have an official Routing library (the closest thing to it was <a href="https://sapper.svelte.dev/">Sapper</a>, but it’s more than just routing) and I had to resort to using an unofficial routing library which worked relatively well for my needs.</p><h3>So you’re telling me to switch to Svelte now? 😑</h3><p><strong>Nope</strong>. It may not be ready for large applications, but I think you should <strong>consider it for some side projects</strong> you build in the future, maybe get a feel for it and see if you like it. Some things I liked about Svelte were:</p><ul><li>Easy to grasp syntax.</li><li>The idea of compiling rather than just another traditional framework is intriguing. ✨</li><li>Reactivity is very simple to use in the components.</li><li>Things like Svelte transitions, custom elements, and SSR integration are cherries on the cake.🍰</li><li>Speed isn’t a de-facto way of choosing frameworks, but Rich Harris(creator of Svelte) plays hard to keep Svelte’s speed at top of the list!</li></ul><p>In the end, <strong>my experience with Svelte was positive</strong>. The community is small but growing. I would recommend you to watch this video ‘<a href="https://www.youtube.com/watch?v=AdNJ3fydeao">Rethinking reactivity</a>’ — by Rich Harris, creator of Svelte.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aebf7508cea0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/front-end-weekly/my-look-at-sveltejs-and-how-you-can-start-using-it-aebf7508cea0">My look at SvelteJS and how you can start using it</a> was originally published in <a href="https://medium.com/front-end-weekly">Frontend Weekly</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>