<?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 Sanchit Nevgi on Medium]]></title>
        <description><![CDATA[Stories by Sanchit Nevgi on Medium]]></description>
        <link>https://medium.com/@sanchitgn?source=rss-f87072b2a46f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*XzICXxXa-OR_DTbS9zl99Q.jpeg</url>
            <title>Stories by Sanchit Nevgi on Medium</title>
            <link>https://medium.com/@sanchitgn?source=rss-f87072b2a46f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 14:22:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sanchitgn/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[Developing a React masonry HOC ]]></title>
            <link>https://medium.com/@sanchitgn/developing-a-react-masonry-hoc-f4cf9b7edee0?source=rss-f87072b2a46f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4cf9b7edee0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ui]]></category>
            <category><![CDATA[masonry]]></category>
            <category><![CDATA[higher-order-components]]></category>
            <dc:creator><![CDATA[Sanchit Nevgi]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 13:20:31 GMT</pubDate>
            <atom:updated>2018-02-05T13:20:31.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gPvynUbpsrC0JJvr-bGalg.png" /><figcaption>Taken straight from the demo</figcaption></figure><blockquote>react-mason is zero-config, zero-dependency masonry HOC.</blockquote><h4>What’s a masonry grid?</h4><p>Made popular by Pinterest, a masonry grid displays items stacked compactly (Much like a mason with bricks). Especially useful to display un-structured data (News, photo gallery, posts etc)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7a5_1QYagP6LZgm9aiTSaQ.png" /></figure><h4>Why would I need this?</h4><p>There are plenty of masonry libraries out there no doubt. So how is this any different? Many of the libraries I found has third-party dependencies (<em>I’m looking at you jQuery</em>). The ones that didn’t, needed me to set fixed columns or had some crazy configuration. So I decided to write a generic HOC (Higher Order Component). No columns, no config!</p><h4>Demo</h4><p>Check out <a href="https://sanchitgn.github.io/react-mason/">the live demo</a> and <a href="http://github.com/sanchitgn/react-mason">the repo</a>.</p><h4>Try it out yourself</h4><p>It is ridiculously easy to use, just wrap the items in a Masonry component and you’re good to go!</p><p>npm install react-mason</p><pre>import React, { Component } from &#39;react&#39;;<br>import Masonry from &#39;react-mason&#39;;<br>import Photo from &#39;./Photo&#39;;<br><br>class PhotoAlbum extends Component {<br>  render() {<br>    return (<br>      &lt;Masonry&gt;<br>        {<br>          this.props.photos.map(photo =&gt; &lt;Photo {...photo} /&gt;)<br>        }<br>      &lt;/Masonry&gt;<br>    )<br>  }<br>}</pre><p>That’s all! For more details about how this is made, look <a href="https://github.com/sanchitgn/react-mason/blob/master/src/index.js">behind the scenes</a> (~140 LOC). It is <em>very </em>readable I promise! 🤞</p><h4>What it has going for it 😍</h4><ul><li>Computing child placement is fast with a <em>fairly</em> compact grid.</li><li>Can layout variable width/height children (<em>No fixed columns!</em>).</li><li>Zero config, zero dependencies :)</li></ul><h4>What it doesn’t 🤷</h4><ul><li>The layout may not be optimal (it may leave gaps).</li><li>No ability to add new children without causing a complete re-layout (yet!)</li><li>Zero config :(</li></ul><p>Thank you for reading ❤️.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4cf9b7edee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Porting Kindle Word-Wise to the Browser]]></title>
            <link>https://medium.com/@sanchitgn/porting-kindle-word-wise-to-the-browser-7e21e04d066c?source=rss-f87072b2a46f------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e21e04d066c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[vocabulary]]></category>
            <dc:creator><![CDATA[Sanchit Nevgi]]></dc:creator>
            <pubDate>Wed, 29 Mar 2017 05:16:12 GMT</pubDate>
            <atom:updated>2017-03-29T05:24:23.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WK7rmBuhnE7yRXLcFS4V8w.png" /></figure><p>I keep a list of projects I’d like to take up. This particular one has been on it for quite some time. So what is it? An extension.</p><p>Stop laughing.</p><h3>The Idea</h3><p>A year ago, I’d purchased Kindle. Best decision ever! As you might have guessed, it has this wonderful feature called Word-Wise.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*1nawuM54hgUmv5_tR77Qhw.jpeg" /></figure><p>Their website says:</p><blockquote><strong>“Read more challenging books</strong></blockquote><blockquote>Word Wise makes it easier to enjoy and quickly understand more challenging books. Short and simple definitions automatically appear above difficult words, so you can keep reading with fewer interruptions.”</blockquote><p>Since the past few months I have been <a href="https://medium.com/@sanchitgn/what-ive-learnt-developing-a-modern-progressive-web-app-d3abe69933fa">way too into Javascript</a>. I had been going through the <a href="https://developer.mozilla.org/en/docs/Web/HTML/Element">HTML5 semantic elements</a>, as one does on a Friday night. When I saw this:</p><blockquote>The <strong>HTML </strong><strong>&lt;ruby&gt; element</strong> represents a ruby annotation. Ruby annotations are for showing pronunciation of East Asian characters.</blockquote><p>And something in my head clicked!</p><p>The idea was simple.</p><p>Procure a dictionary → Get difficult words → Traverse the DOM and annotate aforementioned words with the &lt;ruby&gt; tag (which is <a href="http://caniuse.com/#search=ruby">supported by most browsers</a>) to display the definition.</p><p>Let’s begin</p><h4>Look Ma! (Show Me The Code)</h4><p><a href="https://chrome.google.com/webstore/detail/voracious/jimkaakbhabmabeigofmboihfpojdgln">Voracious</a></p><p><a href="https://github.com/sanchitgn/voracious">Checkout the code.</a></p><h3>The Process</h3><p>I <a href="https://github.com/EmailThis/extension-boilerplate">bootstrapped my extension</a>, added Webpack for bundling and had my project set up in under 30 mins. The basic idea was that I would <em>inject </em>a contentscript.js into a page, analyze the text and display the definition.</p><p>Now, I needed a list of tough words. A few searches later, I had a <a href="http://www.freevocabulary.com/">list of 5000 words</a> primarily used for SAT prep. A little cleanup and I had this:</p><pre>{<br>  &quot;abase&quot;: &quot;To lower in position, estimation, or the like&quot;, <br>  &quot;abbess&quot;: &quot;The lady superior of a nunnery&quot;<br>  ...<br>}</pre><p>Nice! But not enough. The list contained words such as “access” and “accept”, not what I would categorize as tough words. Each word needed a difficulty associated with it. That’s where dictionary.com comes in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0Ycj4vWye_FSMrocjejDg.png" /><figcaption>Dictionary.com provides a difficulty level for each word</figcaption></figure><p>So I did what any sane person would do, send a request for each word in my dictionary, parse the HTML response and find that little data-difficulty attribute in the page. All using a <a href="https://github.com/sanchitgn/reader/blob/master/src/scripts/utils/difficulty.js">70-line node script</a> with axios and cheerio.</p><p>I ended up with a refined version of the dictionary.</p><pre>{<br>  &quot;abase&quot;: {<br>    &quot;definition&quot;: &quot;To lower in position, estimation, or the like&quot;,<br>    &quot;difficulty&quot;: 48<br>  },<br>  &quot;abbess&quot;: {<br>    &quot;definition&quot;: &quot;The lady superior of a nunnery.&quot;,<br>    &quot;difficulty&quot;: 42<br>  }<br>}</pre><p>Here comes the interesting part, the crux of the extension.</p><p>I started off writing helper functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaefb5edaa50aa3af655e20d5ab870fc/href">https://medium.com/media/eaefb5edaa50aa3af655e20d5ab870fc/href</a></iframe><p>So far so good. I began writing the logic for DOM traversal.</p><h4>Attempt #1</h4><p>This was the first approach I’d used. Be warned, it is näive and may cause heartburn.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9cbbb693a0dccef3d3fed1c0ab32d8b/href">https://medium.com/media/a9cbbb693a0dccef3d3fed1c0ab32d8b/href</a></iframe><p>It goes like this, I select all the &lt;p&gt; elements in the page, get their inner text, split the words, annotate them and set the innerHTML .</p><p>There are some major flaws in this,</p><ol><li>If &lt;p&gt; or &lt;li&gt; has child nodes they are lost.</li><li>&lt;p&gt; and &lt;li&gt; may not be part of an article.</li></ol><p>Back to the drawing board.</p><h4>Attempt #2</h4><p>Let’s go the brute force way. Why not traverse the entire DOM and annotate the text. In theory, this sounds logical.</p><p>A little background first. A node in a document can be of <a href="https://developer.mozilla.org/en/docs/Web/API/Node/nodeType">several types</a>. The most common ones are Node.ELEMENT_NODE which represents an element such as &lt;div&gt; and Node.TEXT_NODE which is what you’d think it would be.</p><p>Node has this helpful method replaceWith() which I’m going to be honest, took me way too long to find.</p><blockquote>The <strong>ChildNode.replaceWith()</strong> method replaces this ChildNode in the children list of its parent with a set of <a href="https://developer.mozilla.org/en-US/docs/Web/API/Node">Node</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/API/DOMString">DOMString</a> objects. — MDN</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23339e81ba666790e26a35f5a117dff1/href">https://medium.com/media/23339e81ba666790e26a35f5a117dff1/href</a></iframe><p>VanillaJS FTW! Who needs jQuery am I right!</p><h4>Attempt #3</h4><p>Using document.body had some side-effects. The google search page would flicker like crazy (If anyone knows why, let me know, I’m curious). Also, this isn’t very efficient. Many elements that ought to be skipped such as &lt;script&gt; are traversed.</p><p>I decided to use some intelligence while traversing. HTML has an &lt;article&gt; semantic just for this. Although I found, many websites avoid using it. I ended up using these class and tag selectors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d849fbdae58c8ee5ad8c990d958c82a/href">https://medium.com/media/5d849fbdae58c8ee5ad8c990d958c82a/href</a></iframe><h3><a href="http://sanchitgn.github.io/voracious">The Result</a></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/910/1*i5gRgEW_8cyRIfLxoL3LNQ.gif" /></figure><p>This is far from perfect, but it’s a start. Some noticeable bugs are</p><ol><li>Since I use class &amp; element selectors, the extension fails on some websites (Clearly it’s their fault).</li><li>The context of the sentence is not considered, sometimes leading to the wrong definition being displayed.</li><li>Some words are not recognized during parsing. This happens when the word has adjacent punctuation such as . , or ( etc.</li><li>The dictionary is by no means complete. It has roughly 5,000 words. In contrast the Oxford dictionary has 171,476 words<strong>.</strong></li></ol><p>Since this extension is not dependent on browser specific api’s, it can be ported to other Browsers like Firefox, Opera without any changes, something I am actively working on (I’m at position 386 out of 488).</p><p>That’s all folks!</p><p>PS: Love the Chrome extension publishing process.</p><h3>Call To Action</h3><p>If you enjoyed this article, let me know by clicking the 💚.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e21e04d066c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Compare npm packages from the command line]]></title>
            <link>https://medium.com/@sanchitgn/compare-npm-packages-from-the-command-line-f123c3ac0af1?source=rss-f87072b2a46f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f123c3ac0af1</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Sanchit Nevgi]]></dc:creator>
            <pubDate>Wed, 08 Mar 2017 12:16:04 GMT</pubDate>
            <atom:updated>2017-03-08T12:16:04.182Z</atom:updated>
            <content:encoded><![CDATA[<p>There are <a href="https://developers.slashdot.org/story/17/01/14/0222245/nodejss-npm-is-now-the-largest-package-registry-in-the-world">over 350,000 packages</a> on npm. There are more than <a href="http://blog.npmjs.org/post/143451680695/how-many-npm-users-are-there">a billion downloads</a> per week. With so many new packages, it becomes difficult to select the right package for you projects.</p><p>Express vs Connect vs Koa ‎ (ﾉಥ益ಥ）ﾉ ┻━┻</p><p>Tools like <a href="https://npmcompare.com/">npmcompare.com</a> and <a href="https://npms.io/">npms.io</a> make choosing easier.</p><p>Enter npm-compare. <a href="https://www.npmjs.com/package/npm-compare">Compare npm packages</a> right from your terminal. Powered by the npms.io api.</p><p>Start using it right away by</p><pre>$ npm install --global npm-compare</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*na9lc6lAtEVxmuKWJ_7Dvw.gif" /></figure><p>Although this shouldn’t be the only criteria for selecting a package. I hope this helps you make an informed decision.</p><p>Have a great day :)</p><p>PS: If you are interested, you can check out the <a href="https://gist.github.com/sanchitgn/197576a38433bef42ab82a6ec5934f26">75-line code here</a> or on my <a href="https://github.com/sanchitgn/npm-compare">GitHub repository</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f123c3ac0af1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I’ve learnt developing a modern progressive web app]]></title>
            <link>https://medium.com/@sanchitgn/what-ive-learnt-developing-a-modern-progressive-web-app-d3abe69933fa?source=rss-f87072b2a46f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3abe69933fa</guid>
            <category><![CDATA[progressive-web-app]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Sanchit Nevgi]]></dc:creator>
            <pubDate>Fri, 30 Dec 2016 13:24:08 GMT</pubDate>
            <atom:updated>2016-12-30T13:24:08.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgGPgxUb-HJqiEDbdNkUnA.jpeg" /></figure><p>I read about a lot of people who take up side projects as a challenge. Most recently about <a href="https://medium.com/u/c79346ea7c9a">Mark Zuckerberg</a>’s <a href="https://www.facebook.com/notes/mark-zuckerberg/building-jarvis/10154361492931634/">Building Jarvis</a>. I thought I’d take one up as an experiment. There has been a lot of buzz going around progressive web apps or PWA being the next big thing in web. So I took a look at it and YOU WON’T BELIEVE what happened next…well you can take a guess.</p><p>Shut up and show me <a href="https://github.com/sanchitgn/remember">the code</a>!. Take a look at the demo <a href="http://remember-53b67.firebaseapp.com/">here.</a></p><p>Web development is moving at a crazy speed, like a Lamborghini on steroids. <a href="https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.4b1u2y1vt">Javascript fatigue</a> is real people. So I thought, how difficult would it be to write a modern offline-first web-app. After a lot of deliberation and thought, I landed on a progressive todo-app (I bet you’re really surprised)</p><p><strong>Full disclosure:</strong> I am not even close to an experienced developer. I’m one of those “Oh f**k — check StackOverflow” type. I had just enough experience in React to barely know what’s going on. So don’t go pulling your hair out if things are not up to your standards. In order to comprehend a basic understanding of Javascript-land is needed. If you don’t but feel rebellious, carry on.</p><p>With the enthusiasm of a 5 year old on sugar rush, I created the project with create-react-app I yarned the dependencies up. The cogs in my brain began churning at 10rpm (I’m pretty slow).</p><p>I already had a mental model of what I had to do</p><ul><li>Create a mobile-friendly todo app</li><li>Cache todos locally</li><li><a href="https://developers.google.com/web/progressive-web-apps/">Make it a PWA</a> by adding offline capabilities</li><li>Deploy application</li><li>Add authentication</li><li>Store todos in the cloud</li><li>Add analytics, push notifications</li><li>Write blog post, bask in glory</li><li>Thank the president for the medal of honour</li></ul><p>I wanted to use what all the cool kids were using. A <strong>lot </strong>of thought went into this. I finally landed on React, Redux, Webpack 2, ES6+7 (with all the generator goodies). I did not use a UI framework and went the flex way.</p><p>I set a deadline to do it on a weekend (Boy, was I naive). The “making the todo app” part was simple enough, having done countless tutorials. Sprinkle some actions and a dash of reducers and there we had it. MAN I’M AWESOME. And here comes our first lesson.</p><h4>Lesson #1: Never judge a project by how easy it is to start.</h4><pre><strong>actions/index.js</strong></pre><pre>export const ADD_TODO = &#39;ADD_TODO&#39;<br>export const MARK_TODO = &#39;MARK_TODO&#39;<br>export const EDIT_TODO = &#39;EDIT_TODO&#39;</pre><pre>export const addTodo = text =&gt; ({type: ADD_TODO, text})<br>export const markTodo = (id, completed) =&gt; ({type: MARK_TODO, id, completed})<br>export const editTodo = (id, text) =&gt; ({type: EDIT_TODO, id, text})</pre><pre><strong>reducers/index.js</strong></pre><pre>const todos = (state = [], action) =&gt; {<br>  switch (action.type) {<br>    case ADD_TODO:<br>      const todo = makeTodo(action.text)<br>      return [ ...state, todo ]<br>    case MARK_TODO:<br>      return state.map(todo =&gt;<br>        todo.id === action.id ? { ...todo, completed: action.completed }<br>          : todo<br>      )<br>    case EDIT_TODO:<br>      return state.map(todo =&gt;<br>        todo.id === action.id ? { ...todo, text: action.text }<br>          : todo<br>      )<br>  }<br>}</pre><p>I wired up a basic UI, mimicking material design as much as I could. Shout out to Chrome developer tools, you da bomb. If you aren’t using it already, I highly recommend that you do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*tC8R9TVIGOI2hSKe59a33Q.png" /></figure><p>On to the next one…</p><p>We have a todo app, but it isn’t very helpful. The todos vanish on page refresh. We would need some way to cache todos and retrieve them on page reload.</p><p><a href="https://developers.google.com/web/fundamentals/instant-and-offline/web-storage/offline-for-pwa">A little birdie told me</a> that IndexedDB was the way to go. localforage is a handy wrapper around IndexedDB and has api’s similar to localStorage. Using it was a piece of cake.</p><pre><strong>util/storageUtil.js</strong></pre><pre>const configStorage = () =&gt; {<br>  localforage.config({<br>    ...<br>  })<br>}<br>configStorage()</pre><pre>const getTodos = () =&gt; localforage.getItem(TODOS)</pre><pre>const saveTodos = todos =&gt; localforage.setItem(TODOS, todos)</pre><pre>export { getTodos, saveTodos }</pre><p>Uh ohhhhh, our first roadblock. The <a href="http://redux.js.org/docs/basics/Reducers.html">redux docs</a> say that reducers should be pure functions, and database access is not pure as much as I try to convince myself. A little <em>overflowing </em>(Thats what I call going on StackOverflow) later and I was left with two options redux-thunk and redux-saga. Both are very strong libraries. <a href="https://www.youtube.com/watch?v=xDuwrtwYHu8">The Saga pattern</a> seemed to be all the craze, so I went with that. Awesome! I checked out <a href="https://redux-saga.github.io/redux-saga/">their docs</a> to get started and…</p><p>Uh ohhhhh, I had no idea what async/await or generators were. At first, the docs were like a Shakespearean play to me. I had no f**king clue what was going on.</p><p>After some blog posts¹ and head-banging, I landed on something that worked. If you’d ask me how, I couldn’t tell you.</p><pre><strong>middleware/saga.js</strong></pre><pre>function* cacheTodos() {<br>  try {<br>    const todos = yield select(state =&gt; state.todos)<br>    saveTodos(todos)<br>  } catch(e) {<br>    yield e<br>  }<br>}</pre><pre>function* getCachedTodos() {<br>  try {<br>    const todos = yield getTodos()<br>    yield put(receiveCachedTodos(todos))<br>  } catch(e) {<br>    yield e<br>  }<br>}</pre><pre>function* todoStorageSaga() {<br>  yield [<br>    takeEvery(FETCH_CACHED_TODOS, getCachedTodos),<br>    takeEvery([ADD_TODO, EDIT_TODO, CLEAR_TODOS, MARK_TODO], cacheTodos)<br>  ]<br>}</pre><p>And wiring it up with the redux store</p><pre><strong>index.js</strong></pre><pre>const sagaMiddleware = createSagaMiddleware()</pre><pre>const store = createStore(rootReducer,   applyMiddleware(sagaMiddleware))<br>sagaMiddleware.run(todoStorageSaga)</pre><p>Those few lines took me hours.</p><p>Whew! Now comes the interesting part (If you’re a nerd like me). So why make an app PWA anyway. If you don’t know what a progressive web app is, here’s a run down from <a href="https://ionicframework.com/docs/v2/resources/progressive-web-apps/">the good people at Ionic</a></p><blockquote>Progressive — Work for every user, regardless of browser choice, because they are built with progressive enhancement as a core tenet.</blockquote><blockquote>Responsive — Fit any form factor, desktop, mobile, tablet</blockquote><blockquote>Connectivity independent — Enhanced with service workers to work offline or on low quality networks.</blockquote><blockquote>App-like — Use the app-shell model to provide app-style navigation and interactions.</blockquote><blockquote>Installable — Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.</blockquote><p>To make an app “progressive”, you need at the very least:</p><ul><li>A service worker — contains caching logic</li><li>A manifest.json — contains your apps name, icon.</li></ul><p>I followed <a href="https://developers.google.com/web/fundamentals/getting-started/codelabs/your-first-pwapp/">the tutorial</a> from Google and contrary to what I assumed, It wasn’t all that difficult. The guys are Google are so nice that they even provided a sw-precache tool, which let’s you lie on your butt and drink coffee while the tool does everything for you.</p><pre><strong>manifest.json</strong></pre><pre>{<br>  &quot;short_name&quot;: &quot;Remember&quot;,<br>  &quot;name&quot;: &quot;The simple Todo app&quot;,<br>  &quot;description&quot;: &quot;A Todo app using progressive technologies&quot;,<br>  &quot;theme_color&quot;: &quot;#009688&quot;,<br>  &quot;lang&quot;: &quot;en-US&quot;,<br>  &quot;dir&quot;: &quot;ltr&quot;,<br>  &quot;icons&quot;: [<br>    {<br>      &quot;src&quot;: &quot;favicon.png&quot;,<br>      &quot;type&quot;: &quot;image/png&quot;,<br>      &quot;sizes&quot;: &quot;192x192&quot;<br>    }<br>  ],<br>  &quot;start_url&quot;: &quot;index.html?launcher=true&quot;,<br>  &quot;display&quot;: &quot;standalone&quot;,<br>  &quot;orientation&quot;: &quot;portrait&quot;<br>}</pre><pre><strong>package.json</strong></pre><pre>&quot;scripts&quot;: {<br>  &quot;build-offline&quot;: &quot;react-scripts build &amp;&amp; sw-precache --root=&#39;build/&#39; static-file-globs=&#39;build/**/!(*map*)&#39;&quot;<br>}</pre><p>THAT’S IT!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*qTu-zC7LKqdlAEMt5DIdSA.gif" /></figure><h4><strong>Lesson #2: Just because something looks difficult, doesn’t mean it is.</strong></h4><p>Moving on.</p><p>It’s a good practice to deploy as early as possible if you’d rather not spend hours trying to figure out why the f**k npm build just won’t work.</p><p>I have been a fan of <a href="https://firebase.google.com/">Firebase</a> for a while now for its ease of use, and when they introduced hosting, I’ve been dying to try it out. Looks like this is our chance.</p><pre>$ yarn global add firebase-tools<br>$ firebase login<br>$ firebase init<br>$ firebase deploy</pre><p>SERIOUSLY, THAT’S IT! Man, technology is awesome! We got ourselves an app hosted at <a href="http://remember-53b67.firebaseapp.com/"><em>remember-53b67.firebaseapp.com</em></a></p><p>We have a deployed offline todo app, Woohoo! But wait, there’s a problem………the app sucks! There’s no way to edit a todo, you have to tap a todo to complete it, there are no animations and it just looks dull. Time to roll up my sleeves and summon my inner designer.</p><p>I decided adding coloured background to each todo item. This is where my newfound knowledge of generators came in handy. I added color-string, a handy library to manipulate colour strings.</p><pre><strong>util/colorUtil.js</strong></pre><pre>const constrain = (start, value, end) =&gt; Math.max(start, Math.min(value, end))</pre><pre>function *getColor() {<br>  const start = 40, jump = 8<br>  let i=0<br>  while(true) {<br>    yield colorString.to.hex([0, constrain(start, start + i++*jump, 180), 0])<br>  }<br>}</pre><pre><strong>containers/TodoContainer.js</strong></pre><pre>const colors = getColor()</pre><pre>&lt;TodoItem ... bgColor={colors.next().value} /&gt;</pre><p>This may not be the best way to do it, but hey, my brain runs at 10rpm, what do I know.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*t-f2NBmmzysLmdehPM0Qqw.png" /></figure><p><strong>TL;DR: Added HammerJS and react-motion</strong></p><p>Ladies and gentlemen, please fasten your seat-belts as we prepare for take-off</p><p>We have built this as a native app, so we need to handle touch events. HammerJS is a popular library that abstracts this and provides api’s such as tap, pinch, swipe. react-hammerjs is a wrapper around it that lets you add it as a React component.</p><p>The first thing we need it a way to edit todos on double-tap and save it on blur or enter. Easy-peasy</p><pre><strong>TodoItem.js</strong></pre><pre>editTodo = () =&gt; {<br>  this.setState({editing: false})<br>  this.props.onEdit(this.props.id, this.state.editText)<br>}<br>handleDoubleTap = () =&gt; {<br>  this.setState({editing: true})<br>}<br>handleBlur = () =&gt; {<br>  this.editTodo()<br>}<br>handleKeyDown = e =&gt; {<br>  if(e.which === 13) {<br>    this.editTodo()<br>  }<br>}</pre><pre>...</pre><pre>&lt;Hammer onDoubleTap={this.handleDoubleTap}&gt;<br>  {/* Actual todo */}<br>&lt;/Hammer&gt;</pre><pre><strong>TodoContainer.js</strong></pre><pre>&lt;TodoItem ... onEdit={editTodo}/&gt; // redux-dispatch passed as prop</pre><pre><strong>reducers/index.js</strong></pre><pre>case EDIT_TODO:<br>      return state.map(todo =&gt;<br>        todo.id === action.id ? { ...todo, text: action.text }<br>          : todo<br>      )</pre><pre><strong>actions/index.js</strong></pre><pre>export const EDIT_TODO = &#39;EDIT_TODO&#39;<br>export const editTodo = (id, text) =&gt; ({type: EDIT_TODO, id, text})</pre><p>P.S: This may seem over-whelming at first to the un-initiated, but trust me it’s easy once you understand it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Gd2mI5AtYYMGHQjTY4qt3Q.gif" /></figure><p><a href="https://medium.com/u/701b0000d771">Cheng Lou</a>’s react-motion is amazing for adding animation, although it takes some time to wrap your head around it. I’d recommend going through <a href="https://github.com/chenglou/react-motion">their docs</a> and issues (I basically picked up the code from one of the demos). The code has been truncated for brevity, please don’t sue me.</p><pre><strong>TodoItem.js</strong></pre><pre>constructor(props) {<br>  this.state = {isPressed: false, lastX: null, deltaX: 0, opacity: 1}<br>}<br>handleTouchStart = e =&gt; {<br>  this.setState({lastX: e.touches[0].pageX, isPressed: true})<br>}<br>handleTouchMove = e =&gt; {<br>  if(this.state.isPressed)<br>    e.preventDefault()<br>  let deltaX = e.touches[0].pageX - this.state.lastX<br>  this.setState({deltaX, opacity: (240-deltaX)/240})<br>  if(deltaX &gt; 240) {<br>    this.props.markTodo(this.props.id, true)<br>  }<br>}<br>handleTouchEnd = () =&gt; {<br>  this.setState({isPressed: false, lastX: null, deltaX: 0, opacity: 1})<br>}<br>render() {<br>  let style = isPressed ? {x: deltaX, opacity} : {x: spring(0), opacity: spring(1)}<br>...<br>  &lt;Motion style={style}&gt;<br>    {({x, opacity}) =&gt; {<br>      return &lt;div style={{<br>        backgroundColor: bgColor,<br>        opacity,<br>        transform: `translate3d(${x}px, 0, 0)`,<br>        WebkitTransform: `translate3d(${x}px, 0, 0)`<br>      }} onTouchStart={this.handleTouchStart} onTouchMove={this.handleTouchMove} onTouchEnd={this.handleTouchEnd}&gt;<br>      {/* Todo Item */}<br>    &lt;/div&gt;<br>  }}<br>&lt;/Motion&gt;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/270/1*Xp6krIqeFQzAbNnjGkEUZA.gif" /></figure><p>So far, we have a deployed an offline todo app, with some animations. Not bad, but far from over. Shit is about to get real. All in all, I’m pretty happy with myself. I know, I know, there are some ninja coders out there who could this blind-folded, balanced on top a horse while juggling fireballs (I would love to see that). In the next part, I’ll add cloud storage and authentication.</p><p>And finally,</p><h4><strong>Lesson #3: Even the simplest of apps takes tremendous effort if you want to do it right.</strong></h4><h3>¹References:</h3><h4>ES6 Generators: <a href="https://medium.com/javascript-scene/the-hidden-power-of-es6-generators-observable-async-flow-control-cfa4c7f31435#.t4mlhsg1z">[1]</a> <a href="https://davidwalsh.name/es6-generators">[2]</a></h4><h4>Progressive Web Apps: <a href="https://developers.google.com/web/progressive-web-apps/">[1]</a> <a href="https://medium.com/@addyosmani/progressive-web-apps-with-react-js-part-i-introduction-50679aef2b12#.x9e6nqawi">[2]</a> <a href="https://chodounsky.net/2016/12/23/progressive-web-applications/">[3]</a></h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3abe69933fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>