<?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 Vikram Thyagarajan on Medium]]></title>
        <description><![CDATA[Stories by Vikram Thyagarajan on Medium]]></description>
        <link>https://medium.com/@vikramthyagarajan?source=rss-9b55f7bd8406------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*e2wTsJH1KN79tJuYdW0dpw.jpeg</url>
            <title>Stories by Vikram Thyagarajan on Medium</title>
            <link>https://medium.com/@vikramthyagarajan?source=rss-9b55f7bd8406------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 16:05:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vikramthyagarajan/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to build a Notion-like text editor in React and TipTap]]></title>
            <link>https://vikramthyagarajan.medium.com/how-to-build-a-notion-like-text-editor-in-react-and-tiptap-7f394c36ed9d?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f394c36ed9d</guid>
            <category><![CDATA[ux-design]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[creator-tools]]></category>
            <category><![CDATA[text-editing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Mon, 07 Aug 2023 08:58:38 GMT</pubDate>
            <atom:updated>2023-08-07T08:58:38.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQVOYqb4uMIRCjR_8-FHHg.png" /><figcaption>The final output</figcaption></figure><p>One of the best experiences you can give your users is the ability to write unbounded. A place for them to hold their thoughts in reserve while they think through important things in their head. We don’t want to steal their words, but just store them in a place for keepsakes. A vault that will hold their words until they need them in their lives.</p><p>Unfortunately, this is not the easiest to do in modern frameworks. Text editing brings along with it a lot of issues that need to be tackled starting with a good text editing framework that is customizable, configurable, but also infinitely extensible. It needs to have a clear and crisp API that allows us to mangle the user&#39;s cursor, words, UI, and keyboard events in such a way that we can give them the best writing experience without getting in their way. To take this text editor for a test drive, head on to <a href="https://advaita-writer.vercel.app/playground">this link</a>.</p><h3>The framework</h3><p><a href="https://tiptap.dev/">Tiptap</a> is a content editing framework that is built on top of a stable API called <a href="https://prosemirror.net/">ProseMirror</a>. When used in conjunction, it gives us a way to easily extend the capabilities of ProseMirror using its plugin system which gives us a good API to work with. It also provides us with a simple set of plugins out of the box that can be found <a href="https://tiptap.dev/extensions">here</a>. We will be using these extensions along with building some of our own in order to come up with the best long-form journal writing experience for users. Let’s get started.</p><h3>Schemas and basic plugins</h3><p>A schema is a description of the document that the user is trying to write. In most text editing formats on the web, the main format is HTML. It is extensible, configurable, lightweight, and easily transformable. We need to describe the HTML format of the document that the user is trying to write. In our case, we need to allow for these HTML tags-</p><h4>Nodes (block nodes that take up a paragraph on the document)</h4><ul><li><a href="https://tiptap.dev/api/nodes/blockquote">Blockquote</a> (&lt;blockquote&gt;)</li><li><a href="https://tiptap.dev/api/nodes/bullet-list">BulletList</a> (&lt;ul&gt;)</li><li><a href="https://tiptap.dev/api/nodes/code-block">CodeBlock</a> (&lt;pre&gt;&lt;code&gt;)</li><li><a href="https://tiptap.dev/api/nodes/document">Document</a> &lt;body&gt;</li><li><a href="https://tiptap.dev/api/nodes/hard-break">HardBreak</a> &lt;br&gt;</li><li><a href="https://tiptap.dev/api/nodes/heading">Heading</a> &lt;h1...h6&gt;</li><li><a href="https://tiptap.dev/api/nodes/horizontal-rule">HorizontalRule</a> &lt;hr&gt;</li><li><a href="https://tiptap.dev/api/nodes/list-item">ListItem</a> &lt;li&gt;</li><li><a href="https://tiptap.dev/api/nodes/ordered-list">OrderedList</a> &lt;ol&gt;</li><li><a href="https://tiptap.dev/api/nodes/paragraph">Paragraph</a> &lt;p&gt;</li><li><a href="https://tiptap.dev/api/nodes/text">Text</a></li></ul><h4>Marks (inline nodes that alter styles on the text in each node)</h4><ul><li><a href="https://tiptap.dev/api/marks/bold">Bold</a></li><li><a href="https://tiptap.dev/api/marks/code">Code</a></li><li><a href="https://tiptap.dev/api/marks/italic">Italic</a></li><li><a href="https://tiptap.dev/api/marks/underline">Underline</a></li><li><a href="https://tiptap.dev/api/marks/link">Link</a></li><li><a href="https://tiptap.dev/api/marks/strike">Strike</a></li></ul><h4>Extensions (extra features for better UX)</h4><ul><li><a href="https://tiptap.dev/api/extensions/dropcursor">Dropcursor</a></li><li><a href="https://tiptap.dev/api/extensions/gapcursor">Gapcursor</a></li><li><a href="https://tiptap.dev/api/extensions/history">History</a></li></ul><p>We get this schema out of the box with the StarterKit and a few other extensions. The next extensions we need to add are Menu Nodes that can help the users manipulate these inline and block nodes. The first we will add is the Bubble Menu, which allows users to add marks (bold, italics, underline, etc) to their text nodes when the user selects some text.</p><h3>Bubble Menu</h3><p>We need to add an extension from TipTap called the <a href="https://tiptap.dev/api/extensions/bubble-menu">Bubble Menu extension</a> which will add a tooltip whenever the user makes an inline text selection. This is available via the BubbleMenu as BubbleMenuReact component in the @tiptap/react library. We pass in the editor element, a container reference with a DOM element in which the tooltip will be contained.</p><pre>export const BubbleMenu = ({ editor, containerRef }: BubbleMenuProps) =&gt; {<br>  const [selectionType, setSelectionType] = useState&lt;SelectionMenuType&gt;(null);<br>  useEffect(() =&gt; {<br>    if (selectionType !== &quot;link&quot;) setSelectionType(null);<br>  }, []);<br>  if (!editor || !containerRef.current) return null;<br>  return (<br>    &lt;BubbleMenuReact<br>      pluginKey=&quot;bubbleMenu&quot;<br>      editor={editor}<br>      className=&quot;bubble-menu&quot;<br>      tippyOptions={{<br>        appendTo: containerRef.current,<br>      }}<br>    &gt;<br>      &lt;SelectionMenu<br>        editor={editor}<br>        selectionType={selectionType}<br>        setSelectionType={setSelectionType}<br>      /&gt;<br>    &lt;/BubbleMenuReact&gt;<br>  );<br>};</pre><p>We also need to add a Selection Menu that allows the user to paste a link embed when the user clicks on the Link mark in the Bubble Menu.</p><pre>export interface BubbleMenuProps {<br>  editor: Editor;<br>  containerRef: RefObject&lt;HTMLDivElement&gt;;<br>}<br><br>export type SelectionMenuType = &quot;link&quot; | null;<br><br>const SelectionMenu = ({<br>  editor,<br>  selectionType,<br>  setSelectionType,<br>}: {<br>  editor: Editor;<br>  selectionType: SelectionMenuType;<br>  setSelectionType: (type: SelectionMenuType) =&gt; void;<br>}) =&gt; {<br>  switch (selectionType) {<br>    case null:<br>      return (<br>        &lt;&gt;<br>          &lt;button<br>            type=&quot;button&quot;<br>            data-test-id=&quot;mark-bold&quot;<br>            className={clsx({<br>              active: editor.isActive(&quot;bold&quot;),<br>            })}<br>            onClick={() =&gt; editor.chain().toggleBold().run()}<br>          &gt;<br>            &lt;BoldIcon /&gt;<br>          &lt;/button&gt;<br>          &lt;button<br>            type=&quot;button&quot;<br>            data-test-id=&quot;mark-italic&quot;<br>            className={clsx({<br>              active: editor.isActive(&quot;italic&quot;),<br>            })}<br>            onClick={() =&gt; editor.chain().toggleItalic().run()}<br>          &gt;<br>            &lt;ItalicIcon /&gt;<br>          &lt;/button&gt;<br>          &lt;button<br>            type=&quot;button&quot;<br>            data-test-id=&quot;mark-underline&quot;<br>            className={clsx({<br>              active: editor.isActive(&quot;underline&quot;),<br>            })}<br>            onClick={() =&gt; editor.chain().toggleUnderline().run()}<br>          &gt;<br>            &lt;UnderlineIcon /&gt;<br>          &lt;/button&gt;<br>          &lt;button<br>            type=&quot;button&quot;<br>            data-test-id=&quot;mark-strike&quot;<br>            className={clsx({<br>              active: editor.isActive(&quot;strike&quot;),<br>            })}<br>            onClick={() =&gt; editor.chain().toggleStrike().run()}<br>          &gt;<br>            &lt;StrikeIcon /&gt;<br>          &lt;/button&gt;<br>          &lt;button<br>            type=&quot;button&quot;<br>            data-test-id=&quot;mark-link&quot;<br>            className={clsx({<br>              active: editor.isActive(&quot;link&quot;),<br>            })}<br>            onClick={() =&gt; {<br>              setSelectionType(&quot;link&quot;);<br>            }}<br>          &gt;<br>            &lt;LinkIcon /&gt;<br>          &lt;/button&gt;<br>        &lt;/&gt;<br>      );<br>    case &quot;link&quot;:<br>      return (<br>        &lt;div className=&quot;insert-link-box&quot;&gt;<br>          &lt;input<br>            data-test-id=&quot;insert-link-value&quot;<br>            autoFocus<br>            type=&quot;text&quot;<br>            placeholder=&quot;Insert link address&quot;<br>            onKeyDown={(event) =&gt; {<br>              if (event.key === &quot;Enter&quot;) {<br>                editor<br>                  .chain()<br>                  .focus()<br>                  .setLink({<br>                    href: (event.target as HTMLInputElement).value,<br>                    target: &quot;_blank&quot;,<br>                  })<br>                  .run();<br>                setSelectionType(null);<br>              }<br>            }}<br>          /&gt;<br>        &lt;/div&gt;<br>      );<br>  }<br>};</pre><p>This element shows the Bold, Italics, Underline, and Strike marks, and if Link is selected, shows an &lt;input&gt; element that lets the user paste a link embed and highlights it in the text element. When all is said and done, this is how the experience looks like for a user</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cNWpidqKyFSoJKU0GYxTPw.gif" /><figcaption>The Bubble Menu for links in action</figcaption></figure><h3>Commands Menu</h3><p>It’s time to move on to Node Creation for our lovely users. The ideal way for a user to create new types of nodes in their documents would be to not take them out of the flow of writing. We want to open up a floating tooltip that shows up when the user types the / key. We give them a list of options to choose from and they select the node they would like to create. An important feature we want to give them is to be able to use this whole menu from just the keyboard.</p><p>Unfortunately, for making this kind of a plugin, we need to use some advanced features of TipTap, called CustomNodeViews. This allows us to write a React Component and have that render our CommandMenu. We will use a ProseMirror extension called Suggestion that comes out of the box with TipTap in order to achieve this</p><pre>const CommandsPlugin = Extension.create({<br>  name: &quot;insertMenu&quot;,<br>  addProseMirrorPlugins() {<br>    return [<br>      Suggestion&lt;CommandProps&gt;({<br>        editor: this.editor,<br>        char: &quot;/&quot;,<br>        command: ({ editor, range, props }) =&gt; {<br>          props.command({ editor, range, props });<br>        },<br>        items: ({ query }) =&gt; {<br>          return (<br>            [<br>              {<br>                title: &quot;Heading&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-heading1&quot;,<br>                },<br>                command: ({ editor }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .setNode(&quot;heading&quot;, { level: 1 })<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Subheading&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-heading2&quot;,<br>                },<br>                command: ({ editor }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .setNode(&quot;heading&quot;, { level: 2 })<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Small Subheading&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-heading3&quot;,<br>                },<br>                command: ({ editor }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .setNode(&quot;heading&quot;, { level: 3 })<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Quote&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-quote&quot;,<br>                },<br>                command: ({ editor, range }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .setBlockquote()<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Bullet List&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-bullet-list&quot;,<br>                },<br>                command: ({ editor, range }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .toggleBulletList()<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Numbered List&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-ordered-list&quot;,<br>                },<br>                command: ({ editor, range }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .toggleOrderedList()<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Code Block&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-code&quot;,<br>                },<br>                command: ({ editor, range }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .setCodeBlock()<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Callout&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-callout&quot;,<br>                },<br>                command: ({ editor, range }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .setCallout()<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Image&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-image&quot;,<br>                },<br>                command: ({ editor, range }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .insertContentAt(from, { type: &quot;imagePlaceholder&quot; })<br>                    .run();<br>                },<br>              },<br>              {<br>                title: &quot;Video&quot;,<br>                attrs: {<br>                  &quot;data-test-id&quot;: &quot;insert-video&quot;,<br>                },<br>                command: ({ editor, range }) =&gt; {<br>                  const selection = editor.view.state.selection;<br>                  const from = selection.$from.posAtIndex(0);<br>                  const to = selection.$from.posAtIndex(1);<br>                  editor<br>                    .chain()<br>                    .focus()<br>                    .deleteRange({ from, to })<br>                    .insertContentAt(from, { type: &quot;videoPlaceholder&quot; })<br>                    .run();<br>                },<br>              },<br>            ] as CommandProps[]<br>          )<br>            .filter((item) =&gt; {<br>              return item.title.toLowerCase().startsWith(query.toLowerCase());<br>            })<br>            .slice(0, 10);<br>        },<br>        startOfLine: true,<br>        allow: ({ state, range, editor }) =&gt; {<br>          const node = state.selection.$from.node();<br>          if (!node) return false;<br>          return node.textBetween(0, 1) === &quot;/&quot;;<br>        },<br>        render: () =&gt; {<br>          let component: ReactRenderer&lt;CommandsView, any&gt;, popup: Instance&lt;any&gt;;<br>          return {<br>            onStart: (props) =&gt; {<br>              component = new ReactRenderer(CommandsView, {<br>                props,<br>                editor: props.editor,<br>              });<br>              popup = tippy(props.editor.options.element, {<br>                getReferenceClientRect:<br>                  props.clientRect as GetReferenceClientRect,<br>                content: component.element,<br>                showOnCreate: true,<br>                interactive: true,<br>                trigger: &quot;manual&quot;,<br>                placement: &quot;bottom-start&quot;,<br>              });<br>            },<br>            onUpdate: (props) =&gt; {<br>              component.updateProps(props);<br>              popup.setProps({<br>                getReferenceClientRect: props.clientRect,<br>              });<br>            },<br>            onKeyDown: ({ event }) =&gt; {<br>              if (event.key === &quot;Escape&quot;) {<br>                popup.hide();<br>                return true;<br>              }<br>              if (component.ref)<br>                return component.ref.onKeyDown(event as KeyboardEvent);<br>              else return true;<br>            },<br>            onExit: () =&gt; {<br>              component.destroy();<br>              popup.destroy();<br>            },<br>          };<br>        },<br>      }),<br>    ];<br>  },<br>});</pre><p>The important functions to pay attention to are the items and render functions. The items function takes a query string as a parameter and returns an array of possible node types that will be shown to the user. The render function lets us render these items to the user however we want to. In our case, it shows a Tippy tooltip and renders our React Component through the ReactRenderer component that @tiptap/core provides. We also pass in some events like onKeyDown and destroy so our components can handle them as they see fit</p><p>This is what our React Component looks like</p><pre>class CommandsView extends Component&lt;SuggestionProps&gt; {<br>  state = {<br>    selectedIndex: null,<br>  };<br><br>  componentDidUpdate(oldProps: SuggestionProps) {<br>    if (this.props.items !== oldProps.items) {<br>      this.setState({<br>        selectedIndex: 0,<br>      });<br>    }<br>  }<br><br>  onKeyDown(event: KeyboardEvent) {<br>    if (event.key === &quot;ArrowUp&quot;) {<br>      this.upHandler();<br>      return true;<br>    }<br><br>    if (event.key === &quot;ArrowDown&quot;) {<br>      this.downHandler();<br>      return true;<br>    }<br><br>    if (event.key === &quot;Enter&quot;) {<br>      this.enterHandler();<br>      return true;<br>    }<br><br>    return false;<br>  }<br><br>  upHandler() {<br>    this.setState({<br>      selectedIndex:<br>        ((this.state.selectedIndex || 0) + this.props.items.length - 1) %<br>        this.props.items.length,<br>    });<br>  }<br><br>  downHandler() {<br>    this.setState({<br>      selectedIndex:<br>        this.state.selectedIndex === null<br>          ? 0<br>          : ((this.state.selectedIndex || 0) + 1) % this.props.items.length,<br>    });<br>  }<br><br>  enterHandler() {<br>    this.selectItem(this.state.selectedIndex);<br>  }<br><br>  selectItem(index: number | null) {<br>    const item = this.props.items[index || 0];<br><br>    if (item) {<br>      this.props.command(item);<br>    }<br>  }<br><br>  render() {<br>    const { items } = this.props;<br>    return (<br>      &lt;div className=&quot;insert-menu&quot;&gt;<br>        {items.map((item, index) =&gt; {<br>          return (<br>            &lt;button<br>              type=&quot;button&quot;<br>              className={`${<br>                index === this.state.selectedIndex ? &quot;active&quot; : &quot;&quot;<br>              }`}<br>              {...item.attrs}<br>              key={index}<br>              onClick={() =&gt; this.selectItem(index)}<br>            &gt;<br>              {item.element || item.title}<br>            &lt;/button&gt;<br>          );<br>        })}<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><p>It holds the currently selected item in its state and updates the state whenever a KeyDown event is received by it. We also add an active class for the currently selected node to give feedback on the user. When the user hits the Enter key, we add the currently selected node to the document and allow the user to continue writing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xwoysZuePUHUEvJU3qeuWg.gif" /><figcaption>The CommandMenu in action</figcaption></figure><p>An important thing to understand while creating and changing nodes is how to use the ProseMirror API to achieve this. TipTap gives us easy and chainable command functions that can be used to manipulate the Editor schema and document. You can find a list of these commands <a href="https://tiptap.dev/api/commands#nodes--marks">here</a>. Mostly, we just need the editor prop that is available to all plugins in order to run these commands</p><h3>Change Menu</h3><p>The final menu element we are going to build is the ChangeMenu. This will help the user convert certain nodes to different types of nodes. So we can convert a paragraph node to a quote, and into a list item without losing the content inside these nodes. This is the final menu element we need, but it is far more complicated than the ones we’ve made before because it means we are making the whole extension from basic TipTap and ProseMirror APIs, so sit tight and grab yourself a warm cup of tea as we break these down</p><h4>Part 1: Showing the Change Menu View</h4><p>We want to show a change node icon on the left of every block node. And this time, we won’t be using the React Renderer, but doing this through vanilla javascript. The reason for this is that we want deeper access to the ProseMirror API, and we want more control over the tooltip we show and how it behaves</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YxXIZAp3_efg4uAG1LBJJA.png" /><figcaption>The change node icon to the top left of every block node</figcaption></figure><p>In order for us to show the tooltip at the correct location, we need to understand how TipTap’s TextSelection works. We can explain this through our implementation of the shouldShow function, which describes on every tick whether our menu tooltip should show</p><pre>  public shouldShow: Exclude&lt;ChangeMenuPluginProps[&quot;shouldShow&quot;], null&gt; = ({<br>    view,<br>    state,<br>  }) =&gt; {<br>    const { selection } = state;<br>    const { $anchor, empty } = selection;<br>    const disabledContents = [<br>      &quot;imageNode&quot;,<br>      &quot;imagePlaceholder&quot;,<br>      &quot;videoNode&quot;,<br>      &quot;videoPlaceholder&quot;,<br>    ];<br>    let isDisabled = false;<br>    if ($anchor &amp;&amp; $anchor.node(1)) {<br>      const node = $anchor.node(1);<br>      const contents = node.content ? node.content?.toJSON() || [] : [];<br>      isDisabled = contents.find((c: { type: string }) =&gt;<br>        disabledContents.includes(c.type)<br>      );<br>    }<br>    const isRootDepth = $anchor.depth === 1;<br>    const isEmptyTextBlock =<br>      $anchor.parent.isTextblock &amp;&amp;<br>      !$anchor.parent.type.spec.code &amp;&amp;<br>      !$anchor.parent.textContent;<br><br>    if (<br>      !view.hasFocus() ||<br>      isDisabled ||<br>      !this.editor.isEditable<br>    ) {<br>      return false;<br>    }<br><br>    return true;<br>  };</pre><p>The current text selection is stored in the editor state as state.selection . Within this selection, we have 2 nodes that describe the range of selection. The $anchor position is the part of the selection that does not move when we extend the cursor. It is the starting position of our selection, while the $from position is the part that changes. From here, we need to start filtering whether this menu should be visible</p><p>Once we get the $anchor position, we check its root node’s contents. We need to check the root node because the actual text selection is on the leaf node. In order to know what contents are present in this node, we must select the node at depth 1 and loop through its contents</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*Uzg8d3SF4b3D8EPietL9NA.png" /><figcaption>The hierarchy for a text selection in an ordered list</figcaption></figure><p>We then calculate the isDisabled value by looping through the contents and setting isDisabled to true for Video and Image nodes. This is because Image and Video nodes cannot be changed to other nodes because we simply have no way to transform images and videos into paragraphs and vice versa.</p><p>Now that we have understood this, we can look at the code for the whole ChangeMenuView</p><pre>export class ChangeMenuView {<br>  public editor: Editor;<br><br>  public element: HTMLElement;<br><br>  public view: EditorView;<br><br>  public preventHide = false;<br><br>  public tippy: Instance | undefined;<br><br>  public tippyOptions?: Partial&lt;Props&gt;;<br><br>  public shouldShow: Exclude&lt;ChangeMenuPluginProps[&quot;shouldShow&quot;], null&gt; = ({<br>    view,<br>    state,<br>  }) =&gt; {<br>    const { selection } = state;<br>    const { $anchor, $from, empty } = selection;<br>    const disabledContents = [<br>      &quot;imageNode&quot;,<br>      &quot;imagePlaceholder&quot;,<br>      &quot;videoNode&quot;,<br>      &quot;videoPlaceholder&quot;,<br>    ];<br>    let isDisabled = false;<br>    if ($anchor &amp;&amp; $anchor.node(1)) {<br>      const node = $anchor.node(1);<br>      const contents = node.content ? node.content?.toJSON() || [] : [];<br>      isDisabled = contents.find((c: { type: string }) =&gt;<br>        disabledContents.includes(c.type)<br>      );<br>    }<br>    const isRootDepth = $anchor.depth === 1;<br>    const isEmptyTextBlock =<br>      $anchor.parent.isTextblock &amp;&amp;<br>      !$anchor.parent.type.spec.code &amp;&amp;<br>      !$anchor.parent.textContent;<br><br>    if (<br>      !view.hasFocus() ||<br>      isDisabled ||<br>      // !empty ||<br>      // !isRootDepth ||<br>      // !isEmptyTextBlock ||<br>      !this.editor.isEditable<br>    ) {<br>      return false;<br>    }<br><br>    return true;<br>  };<br><br>  constructor({<br>    editor,<br>    element,<br>    view,<br>    tippyOptions = {},<br>    shouldShow,<br>  }: ChangeMenuViewProps) {<br>    this.editor = editor;<br>    this.element = element;<br>    this.view = view;<br><br>    if (shouldShow) {<br>      this.shouldShow = shouldShow;<br>    }<br><br>    this.element.addEventListener(&quot;mousedown&quot;, this.mousedownHandler, {<br>      capture: true,<br>    });<br>    this.editor.on(&quot;focus&quot;, this.focusHandler);<br>    this.editor.on(&quot;blur&quot;, this.blurHandler);<br>    this.tippyOptions = tippyOptions;<br>    // Detaches menu content from its current parent<br>    this.element.remove();<br>    this.element.style.visibility = &quot;visible&quot;;<br>  }<br><br>  mousedownHandler = () =&gt; {<br>    this.preventHide = true;<br>  };<br><br>  focusHandler = () =&gt; {<br>    // we use `setTimeout` to make sure `selection` is already updated<br>    setTimeout(() =&gt; this.update(this.editor.view));<br>  };<br><br>  blurHandler = ({ event }: { event: FocusEvent }) =&gt; {<br>    if (this.preventHide) {<br>      this.preventHide = false;<br><br>      return;<br>    }<br><br>    if (<br>      event?.relatedTarget &amp;&amp;<br>      this.element.parentNode?.contains(event.relatedTarget as Node)<br>    ) {<br>      return;<br>    }<br><br>    this.hide();<br>  };<br><br>  tippyBlurHandler = (event: FocusEvent) =&gt; {<br>    this.blurHandler({ event });<br>  };<br><br>  createTooltip() {<br>    const { element: editorElement } = this.editor.options;<br>    const editorIsAttached = !!editorElement.parentElement;<br><br>    if (this.tippy || !editorIsAttached) {<br>      return;<br>    }<br><br>    this.tippy = tippy(editorElement, {<br>      duration: 0,<br>      getReferenceClientRect: null,<br>      content: this.element,<br>      interactive: true,<br>      trigger: &quot;manual&quot;,<br>      placement: &quot;right-start&quot;,<br>      ...this.tippyOptions,<br>    });<br><br>    // maybe we have to hide tippy on its own blur event as well<br>    if (this.tippy.popper.firstChild) {<br>      (this.tippy.popper.firstChild as HTMLElement).addEventListener(<br>        &quot;blur&quot;,<br>        this.tippyBlurHandler<br>      );<br>    }<br>  }<br><br>  update(view: EditorView, oldState?: EditorState) {<br>    const { state } = view;<br>    const { doc, selection } = state;<br>    const isSame =<br>      oldState &amp;&amp; oldState.doc.eq(doc) &amp;&amp; oldState.selection.eq(selection);<br><br>    if (isSame) {<br>      return;<br>    }<br><br>    this.createTooltip();<br><br>    const shouldShow = this.shouldShow?.({<br>      editor: this.editor,<br>      view,<br>      state,<br>      oldState,<br>    });<br><br>    if (!shouldShow) {<br>      this.hide();<br><br>      return;<br>    }<br><br>    this.tippy?.setProps({<br>      getReferenceClientRect:<br>        this.tippyOptions?.getReferenceClientRect ||<br>        (() =&gt; {<br>          const from = selection.$from.posAtIndex(0);<br>          const boundaries = posToDOMRect(view, 1, 1);<br>          const nodeRect = posToDOMRect(view, from, from);<br>          return {<br>            ...nodeRect,<br>            left: boundaries.left,<br>            right: boundaries.right,<br>          };<br>        }),<br>    });<br><br>    this.show();<br>  }<br><br>  show() {<br>    this.tippy?.show();<br>  }<br><br>  hide() {<br>    this.tippy?.hide();<br>  }<br><br>  destroy() {<br>    if (this.tippy?.popper.firstChild) {<br>      (this.tippy.popper.firstChild as HTMLElement).removeEventListener(<br>        &quot;blur&quot;,<br>        this.tippyBlurHandler<br>      );<br>    }<br>    this.tippy?.destroy();<br>    this.element.removeEventListener(&quot;mousedown&quot;, this.mousedownHandler, {<br>      capture: true,<br>    });<br>    this.editor.off(&quot;focus&quot;, this.focusHandler);<br>    this.editor.off(&quot;blur&quot;, this.blurHandler);<br>  }<br>}</pre><p>The main function to understand in this view is the update function that runs whenever the editor receives focus. We create a tooltip, check whether it should show, and then show the tooltip in the correct coordinates. We do some extra math to calculate the boundary Rect so that our tooltip never overlaps with text that the user has written. So our left and right values are always out of bounds of the actual text content.</p><h4>Part 2: Creating an extension for the ChangeMenu</h4><p>Next, we hook our vanilla ChangeMenu to the TipTap plugin system so our tooltip can show up properly in the view when required</p><pre>const ChangeMenuPlugin = (options: ChangeMenuPluginProps) =&gt; {<br>  return new Plugin({<br>    key:<br>      typeof options.pluginKey === &quot;string&quot;<br>        ? new PluginKey(options.pluginKey)<br>        : options.pluginKey,<br>    view: (view) =&gt; new ChangeMenuView({ view, ...options }),<br>  });<br>};<br><br>export const ChangeMenuReact = Extension.create({<br>  name: &quot;changeMenu&quot;,<br>  addOptions() {<br>    return {<br>      element: null,<br>      tippyOptions: {},<br>      pluginKey: &quot;changeMenu&quot;,<br>      shouldShow: null,<br>    };<br>  },<br>  addProseMirrorPlugins() {<br>    return [<br>      ChangeMenuPlugin({<br>        pluginKey: this.options.pluginKey,<br>        editor: this.editor,<br>        element: this.options.element,<br>        tippyOptions: this.options.tippyOptions,<br>        shouldShow: this.options.shouldShow,<br>      }),<br>    ];<br>  },<br>});<br><br>export interface ChangeMenuProps {<br>  containerRef: RefObject&lt;HTMLDivElement&gt;;<br>  className?: string;<br>  editor: Editor;<br>  tippyOptions?: Partial&lt;Props&gt;;<br>  shouldShow?:<br>    | ((props: {<br>        editor: Editor;<br>        view: EditorView;<br>        state: EditorState;<br>        oldState?: EditorState;<br>      }) =&gt; boolean)<br>    | null;<br>}<br><br>export type MenuItemProps = {<br>  title: string;<br>  subtitle?: string;<br>  attrs: any;<br>  command: ({<br>    editor,<br>    range,<br>  }: {<br>    editor: Editor;<br>    range: { from: number; to: number };<br>  }) =&gt; void;<br>}[];</pre><p>This is pretty standard syntax for writing a plugin with TipTap. We define it as a ProseMirror plugin so we have access to the editor state and other commands that helps us use the ProseMirror API. We also define some types and interfaces that describe our components</p><h4>Part 3: Showing the different nodes on click of ChangeMenu</h4><p>We want to now register this plugin in a React component that we can drop into our JSX and have it show the tooltip. The ChangeMenu itself handles the showing and hiding of the tooltip, all that is remaining is handling the click of the icon, showing the nodes, and the click command to change the node</p><pre>export const ChangeMenu = (props: PropsWithChildren&lt;ChangeMenuProps&gt;) =&gt; {<br>  const [element, setElement] = useState&lt;HTMLDivElement | null&gt;(null);<br>  const [showList, setShowList] = useState(false);<br><br>  useEffect(() =&gt; {<br>    if (!element) {<br>      return;<br>    }<br><br>    if (props.editor.isDestroyed) {<br>      return;<br>    }<br><br>    const pluginKey = &quot;changeMenu&quot;;<br>    const { editor, tippyOptions = {}, shouldShow = null } = props;<br><br>    const plugin = ChangeMenuPlugin({<br>      editor,<br>      element,<br>      pluginKey,<br>      shouldShow,<br>      tippyOptions,<br>    });<br><br>    editor.registerPlugin(plugin);<br>    return () =&gt; editor.unregisterPlugin(pluginKey);<br>  }, [props.editor, element]);<br><br>  const menus: MenuItemProps = [<br>    {<br>      title: &quot;Paragraph&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-paragraph&quot;,<br>      },<br>      command: ({ editor, range }) =&gt; {<br>        editor<br>          .chain()<br>          .focus()<br>          .clearNodes()<br>          .toggleNode(&quot;paragraph&quot;, &quot;paragraph&quot;, {})<br>          .run();<br>      },<br>    },<br>    {<br>      title: &quot;Heading&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-heading1&quot;,<br>      },<br>      command: ({ editor, range }) =&gt; {<br>        editor.chain().focus().setNode(&quot;heading&quot;, { level: 1 }).run();<br>      },<br>    },<br>    {<br>      title: &quot;Subheading&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-heading2&quot;,<br>      },<br>      command: ({ editor }) =&gt; {<br>        editor.chain().focus().setNode(&quot;heading&quot;, { level: 2 }).run();<br>      },<br>    },<br>    {<br>      title: &quot;Small Subheading&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-heading3&quot;,<br>      },<br>      command: ({ editor }) =&gt; {<br>        editor.chain().focus().setNode(&quot;heading&quot;, { level: 3 }).run();<br>      },<br>    },<br>    {<br>      title: &quot;Quote&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-quote&quot;,<br>      },<br>      command: ({ editor, range }) =&gt; {<br>        editor.chain().focus().clearNodes().setBlockquote().run();<br>      },<br>    },<br>    {<br>      title: &quot;Bullet List&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-bullet-list&quot;,<br>      },<br>      command: ({ editor, range }) =&gt; {<br>        editor.chain().focus().clearNodes().toggleBulletList().run();<br>      },<br>    },<br>    {<br>      title: &quot;Numbered List&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-ordered-list&quot;,<br>      },<br>      command: ({ editor, range }) =&gt; {<br>        editor.chain().focus().toggleOrderedList().run();<br>      },<br>    },<br>    {<br>      title: &quot;Code Block&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-code&quot;,<br>      },<br>      command: ({ editor, range }) =&gt; {<br>        editor.chain().focus().setCodeBlock().run();<br>      },<br>    },<br>    {<br>      title: &quot;Callout&quot;,<br>      attrs: {<br>        &quot;data-test-id&quot;: &quot;set-callout&quot;,<br>      },<br>      command: ({ editor, range }) =&gt; {<br>        editor.chain().focus().setCallout().run();<br>      },<br>    },<br>  ];<br><br>  return (<br>    &lt;div<br>      ref={setElement}<br>      className={props.className}<br>      data-test-id=&quot;change-block&quot;<br>      style={{ visibility: &quot;hidden&quot; }}<br>    &gt;<br>      &lt;ChangeIcon onClick={() =&gt; setShowList(!showList)} /&gt;<br>      {showList ? (<br>        &lt;div className=&quot;block-menu&quot;&gt;<br>          {menus.map(({ attrs, title, subtitle, command }) =&gt; {<br>            return (<br>              &lt;div<br>                key={title}<br>                className=&quot;menu-item&quot;<br>                {...attrs}<br>                onClick={() =&gt; {<br>                  setShowList(false);<br>                  const { selection } = props.editor.state;<br>                  const $anchor = selection.$anchor;<br>                  const range = {<br>                    from: $anchor.posAtIndex(0, 1),<br>                    to: $anchor.posAtIndex(1, 1),<br>                  };<br>                  command({ editor: props.editor, range });<br>                }}<br>              &gt;<br>                {title}<br>              &lt;/div&gt;<br>            );<br>          })}<br>        &lt;/div&gt;<br>      ) : null}<br>    &lt;/div&gt;<br>  );<br>};</pre><p>In this code, we take a DOM element as part of our props, pass it on to a ref, and register our plugin against that ref. When we show the list of nodes, we run a click command that is described for each node type and execute it when it is clicked. We also add some CSS classes so we can style these so they look good while the user is using them</p><p>This is what that looks when correctly hooked up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*223aTv2WEZW8Tc78eY0J-A.gif" /><figcaption>The ChangeMenu in action</figcaption></figure><h3>Conclusion</h3><p>In this blog post, we just covered some of the basics of building your own text editor, but a lot more has been left out, most importantly images and video nodes, and how we can further take TipTap and ProseMirror to build more complicated workflows that can help users with long-form writing.</p><p>I’ll take a few more blog posts and dive deeper into these concepts, so stay tuned for more content on this. Until then, keep writing, write letters to your friends, and spread beauty around the world. I’ll see you next time 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f394c36ed9d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Figma-like Infinite Canvas in React]]></title>
            <link>https://medium.com/better-programming/how-to-create-a-figma-like-infinite-canvas-in-react-a2b0365b2a7?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2b0365b2a7</guid>
            <category><![CDATA[computer-graphics]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Wed, 23 Nov 2022 05:52:15 GMT</pubDate>
            <atom:updated>2022-12-06T11:15:39.260Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create infinite experiences for the user</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XqIQld-OZZA-_HpC" /><figcaption>The webpage is your canvas. What will you make?</figcaption></figure><p>I’d recently written about <a href="https://medium.com/better-programming/how-to-create-a-figma-like-infinite-canvas-in-webgl-8be94f65674f">how to build an infinite canvas in WebGL</a>, but as I started building more of my ideas on an infinite canvas, I realised how simple HTML is for prototyping. So I thought I’d merge both and build an infinite canvas in React. This allows me to leverage all the benefits that the browser gives that would have to be rewritten for WebGL: Drag and Drop, Text, iFrames etc.</p><p>To those who have not gone through the other post, I would recommend that you go through at least the Foundation section although going through all of it would help you understand the code that I have used here. In the previous post I mentioned how the logic could be implemented with any framework, and I meant it. And I will show how that implementation could look when brought into React.</p><p>Note: I have made a Code Sandbox so you can view the whole code and play with it <a href="https://codesandbox.io/s/infinite-canvas-react-nhfbb0?file=/src/index.tsx">here</a></p><h4>Immediate Mode Rendering</h4><p>Before we get into the implementation, let me introduce you to a concept in Computer Graphics called Immediate Mode Rendering. This will be needed for the performance benefits it brings.</p><blockquote>In immediate mode, the scene (complete object model of the rendering primitives) is retained in the memory space of the client, instead of the graphics library. This implies that in an immediate mode application the lists of graphical objects to be rendered are kept by the client and are not saved by the graphics library API.</blockquote><p>What this means in React-land is that we are not depending on React to render the whole application. React usually keeps the whole tree and re-renders parts it when the state changes. But can you imagine how that would work for an infinite canvas? React keeping track of every single component in infinity and seeing and running hooks for each of them and placing them? It would be incredibly inefficient to say the least.</p><p>Instead, we will control and tell React what to render. We will keep a 60fps loop and tell React which components to render and where to render them. We will hide any components that are outside our canvas so React has to do just enough rendering to display elements that are inside. It is not even aware of the elements outside the canvas.</p><p>How do we do this in React? We write a custom hook that runs a loop on every RequestAnimationFrame</p><pre>import CanvasStore from &quot;modules/state/CanvasStore&quot;;<br>import { useEffect, useRef, useState } from &quot;react&quot;;<br><br>class RenderLoop {<br>  private lastFrameTime: number = 0;<br>  private lastRequestId: number | null = null;<br>  constructor(private fps: number = 0, private draw: () =&gt; void) {}<br><br>  initialize(fps: number) {<br>    this.fps = fps;<br>  }<br><br>  start() {<br>    this.lastFrameTime = performance.now();<br>    this.loop();<br>  }<br><br>  stop() {<br>    if (this.lastRequestId) cancelAnimationFrame(this.lastRequestId);<br>    this.lastRequestId = null;<br>  }<br><br>  private get fpsInterval() {<br>    return 1000 / this.fps;<br>  }<br><br>  private loop() {<br>    this.lastRequestId = requestAnimationFrame(() =&gt; this.loop());<br>    const now = performance.now();<br>    const elapsed = now - this.lastFrameTime;<br>    if (elapsed &gt; this.fpsInterval) {<br>      this.lastFrameTime = now - (elapsed % this.fpsInterval);<br>      this.draw();<br>    }<br>  }<br>}<br><br>let renderLoop: RenderLoop;<br>export function getRenderLoop(fps = 15, draw: () =&gt; void) {<br>  if (!renderLoop) return new RenderLoop(fps, draw);<br>  else return renderLoop;<br>}<br><br>export const useRenderLoop = (fps: number = 15) =&gt; {<br>  const [frame, setFrame] = useState(&quot;0&quot;);<br>  const loop = useRef&lt;RenderLoop&gt;(<br>    getRenderLoop(fps, () =&gt; {<br>      if (CanvasStore.shouldRender) {<br>        setFrame(`${performance.now()}`);<br>        CanvasStore.shouldRender = false;<br>      }<br>    })<br>  );<br><br>  useEffect(() =&gt; {<br>    CanvasStore.shouldRender = true;<br>    loop.current.start();<br><br>    return () =&gt; loop.current.stop();<br>  }, []);<br>  return frame;<br>};<br><br>export default useRenderLoop;</pre><p>The way this works is that when the app starts, we start a RenderLoop that keeps calling requestAnimationFrame, and depending on the fps , triggers the draw function, which sets a frame string based on the current time. Whenever this value changes, state is changed and so our root component will re render every fps frames a second.</p><h4>Implementation</h4><p>Now that we’ve covered the way we will be using React in the previous section and the foundations of projection in the previous <a href="https://medium.com/better-programming/how-to-create-a-figma-like-infinite-canvas-in-webgl-8be94f65674f">blog post</a>, we can dive into the implementation. We can keep our expected output the same as we did the last time, which is to create 9 large blocks to test the following</p><ul><li>Zooming in and out of the canvas and seeing more blocks</li><li>Moving the camera around and seeing different blocks</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I8aLs5sR2_BaACI7pTCvg.png" /><figcaption>Expected output of our program. It is a grid of many colors with texts on each block</figcaption></figure><p>Let us start with how we place the most foundational elements. We need a component that can place any element with global coordinates on the canvas.</p><p>It takes the screen that is visible (maintained by our CanvasStore, covered later), and positions it locally with respect to our screen. So, given our screen + global coordinates, this component converts it to local coordinates and places them on the screen.</p><pre>import CanvasStore from &quot;modules/state/CanvasStore&quot;;<br>import { PropsWithChildren } from &quot;react&quot;;<br>import { inBounds } from &quot;./math-utils&quot;;<br><br>export interface CanvasPosition {<br>  top: number;<br>  left: number;<br>  width: number;<br>  height: number;<br>}<br><br>export const Position = ({<br>  left,<br>  top,<br>  width,<br>  height,<br>  children,<br>}: PropsWithChildren&lt;CanvasPosition&gt;) =&gt; {<br>  const screen = CanvasStore.screen;<br>  if (<br>    inBounds(<br>      { left, top, height, width },<br>      {<br>        left: screen.x,<br>        top: screen.y,<br>        width: screen.width,<br>        height: screen.height,<br>      }<br>    )<br>  ) {<br>    return (<br>      &lt;div<br>        className=&quot;absolute inline-block&quot;<br>        style={{<br>          left: `${left - screen.x}px`,<br>          top: `${top - screen.y}px`,<br>        }}<br>      &gt;<br>        {children}<br>      &lt;/div&gt;<br>    );<br>  } else return null;<br>};</pre><p>We are yet to implement the inBounds function. This checks whether the rectangle with its global coordinates is visible in the canvas. The overlap logic is explained in detail in <a href="https://stackoverflow.com/a/306332">this stack overflow answer</a>.</p><pre>// math-utils.ts<br>export const radians = (angle: number) =&gt; {<br>  return angle * (Math.PI / 180);<br>};<br><br>interface Rect {<br>  left: number;<br>  top: number;<br>  width: number;<br>  height: number;<br>}<br><br>export const inBounds = (rect1: Rect, rect2: Rect) =&gt; {<br>  if (<br>    rect1.left &lt; rect2.left + rect2.width &amp;&amp;<br>    rect1.left + rect1.width &gt; rect2.left &amp;&amp;<br>    rect1.top &lt; rect2.top + rect2.height &amp;&amp;<br>    rect1.top + rect1.height &gt; rect2.top<br>  )<br>    return true;<br>  else return false;<br>};</pre><p>Now that we know how to place elements on our canvas, we can build our InfiniteCanvas component and place 9 large blocks with text elements inside of them</p><pre>import { RECT_H, RECT_W } from &quot;modules/core/constants&quot;;<br>import { CanvasPosition, Position } from &quot;modules/core/foundation&quot;;<br>import CanvasStore from &quot;modules/state/CanvasStore&quot;;<br>import { memo } from &quot;react&quot;;<br><br>interface TextBlockProps extends CanvasPosition {<br>  text: string;<br>  color: string;<br>  width: number;<br>  height: number;<br>}<br><br>const TextBlock = ({<br>  text,<br>  color,<br>  left,<br>  top,<br>  width,<br>  height,<br>}: TextBlockProps) =&gt; {<br>  return (<br>    &lt;Position left={left} top={top} width={width} height={height}&gt;<br>      &lt;div<br>        className=&quot;flex items-center justify-center&quot;<br>        style={{<br>          width: `${width}px`,<br>          height: `${height}px`,<br>          background: color,<br>        }}<br>      &gt;<br>        {text}<br>      &lt;/div&gt;<br>    &lt;/Position&gt;<br>  );<br>};<br><br>const InfiniteCanvas = ({ frame }: { frame: string }) =&gt; {<br>  const texts = [<br>    &quot;Infinite&quot;,<br>    &quot;Canvases&quot;,<br>    &quot;Are&quot;,<br>    &quot;Easy&quot;,<br>    &quot;When&quot;,<br>    &quot;You&quot;,<br>    &quot;Know&quot;,<br>    &quot;The&quot;,<br>    &quot;Fundamentals&quot;,<br>  ];<br><br>  const colors = [<br>    &quot;#f1f7ed&quot;,<br>    &quot;#61c9a8&quot;,<br>    &quot;#7ca982&quot;,<br>    &quot;#e0eec6&quot;,<br>    &quot;#c2a83e&quot;,<br>    &quot;#ff99c8&quot;,<br>    &quot;#fcf6bd&quot;,<br>    &quot;#9c92a3&quot;,<br>    &quot;#c6b9cd&quot;,<br>  ];<br>  const rectW = RECT_W;<br>  const rectH = RECT_H;<br>  const scale = CanvasStore.scale;<br><br>  return (<br>    &lt;div<br>      className=&quot;w-full h-full&quot;<br>      style={{<br>        transform: `scale(${(scale.x, scale.y)})`,<br>        transformOrigin: &quot;top left&quot;,<br>      }}<br>    &gt;<br>      {texts.map((text, index) =&gt; (<br>        &lt;TextBlock<br>          key={index}<br>          text={text}<br>          color={colors[index]}<br>          left={(index % 3) * rectW}<br>          top={Math.floor(index / 3) * rectH}<br>          width={rectW}<br>          height={rectH}<br>        /&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default memo(InfiniteCanvas);</pre><p>Now we should incorporate this into our UI by building our CanvasRoot and adding it to our ReactDOM:</p><pre>import CanvasStore from &quot;modules/state/CanvasStore&quot;;<br>import { PointerEvent, useEffect, useRef, WheelEvent } from &quot;react&quot;;<br>import useSize from &quot;@react-hook/size&quot;;<br>import InfiniteCanvas from &quot;./InfiniteCanvas&quot;;<br>import useRenderLoop from &quot;modules/core/RenderLoop&quot;;<br><br>const wheelListener = (e: WheelEvent) =&gt; {<br>  const friction = 1;<br>  const event = e as WheelEvent;<br>  const deltaX = event.deltaX * friction;<br>  const deltaY = event.deltaY * friction;<br>  if (!event.ctrlKey) {<br>    CanvasStore.moveCamera(deltaX, deltaY);<br>  } else {<br>    CanvasStore.zoomCamera(deltaX, deltaY);<br>  }<br>};<br><br>const pointerListener = (event: PointerEvent) =&gt; {<br>  CanvasStore.movePointer(event.clientX, event.clientY);<br>};<br><br>const CanvasRoot = () =&gt; {<br>  const canvas = useRef&lt;HTMLDivElement&gt;(null);<br>  const [width, height] = useSize(canvas);<br>  useEffect(() =&gt; {<br>    if (width === 0 || height === 0) return;<br>    CanvasStore.initialize(width, height);<br>  }, [width, height]);<br>  const frame = useRenderLoop(60);<br>  return (<br>    &lt;div className=&quot;w-full h-full&quot;&gt;<br>      &lt;div<br>        className=&quot;w-full h-full relative overflow-hidden overscroll-none&quot;<br>        ref={canvas}<br>        onWheel={wheelListener}<br>        onPointerMove={pointerListener}<br>      &gt;<br>        &lt;InfiniteCanvas frame={frame}&gt;&lt;/InfiniteCanvas&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default CanvasRoot;</pre><p>We initialize the CanvasStore and set up the RenderLoop and simply call our InfiniteCanvas here.</p><p>We also need to pass in the width and height of our canvas container to the CanvasStore which we do through a hook that we have imported. Now the only part remaining is the CanvasStore, which looks like this</p><pre>import {<br>  cameraToScreenCoordinates,<br>  scaleWithAnchorPoint,<br>} from &quot;../core/camera-utils&quot;;<br>import { CAMERA_ANGLE, RECT_H, RECT_W } from &quot;../core/constants&quot;;<br>import { radians } from &quot;../core/math-utils&quot;;<br><br>export interface CanvasState {<br>  shouldRender: boolean;<br>  pixelRatio: number; // our resolution for dip calculations<br>  container: {<br>    //holds information related to our screen container<br>    width: number;<br>    height: number;<br>  };<br>  pointer: {<br>    x: number;<br>    y: number;<br>  };<br>  camera: {<br>    //holds camera state<br>    x: number;<br>    y: number;<br>    z: number;<br>  };<br>}<br>const getInitialCanvasState = (): CanvasState =&gt; {<br>  return {<br>    shouldRender: true,<br>    pixelRatio: window.devicePixelRatio || 1,<br>    container: {<br>      width: 0,<br>      height: 0,<br>    },<br>    pointer: {<br>      x: 0,<br>      y: 0,<br>    },<br>    camera: {<br>      x: 0,<br>      y: 0,<br>      z: 0,<br>    },<br>  };<br>};<br><br>let canvasData = getInitialCanvasState();<br><br>export default class CanvasStore {<br>  private static get data() {<br>    if (!canvasData)<br>      canvasData = {<br>        shouldRender: true,<br>        pixelRatio: window.devicePixelRatio || 1,<br>        container: {<br>          width: 0,<br>          height: 0,<br>        },<br>        pointer: {<br>          x: 0,<br>          y: 0,<br>        },<br>        camera: {<br>          x: 0,<br>          y: 0,<br>          z: 0,<br>        },<br>      };<br>    return canvasData;<br>  }<br><br>  static initialize(width: number, height: number) {<br>    const containerWidth = width;<br>    const containerHeight = height;<br>    canvasData = getInitialCanvasState();<br>    canvasData.pixelRatio = window.devicePixelRatio || 1;<br>    canvasData.container.width = containerWidth;<br>    canvasData.container.height = containerHeight;<br>    canvasData.camera.x = 1.5 * RECT_W;<br>    canvasData.camera.y = 1.5 * RECT_H;<br>    canvasData.camera.z = containerWidth / (2 * Math.tan(CAMERA_ANGLE));<br>  }<br>  public static get screen() {<br>    const { x, y, z } = this.camera;<br>    const aspect = this.aspect;<br>    const angle = CAMERA_ANGLE;<br>    return cameraToScreenCoordinates(x, y, z, angle, aspect);<br>  }<br>  public static get camera() {<br>    return this.data.camera;<br>  }<br>  public static get scale() {<br>    const { width: w, height: h } = CanvasStore.screen;<br>    const { width: cw, height: ch } = CanvasStore.container;<br>    return { x: cw / w, y: ch / h };<br>  }<br>  public static get shouldRender() {<br>    return canvasData.shouldRender;<br>  }<br>  public static set shouldRender(value: boolean) {<br>    canvasData.shouldRender = value;<br>  }<br><br>  private static get container() {<br>    return canvasData.container;<br>  }<br><br>  private static get pointer() {<br>    return canvasData.pointer;<br>  }<br><br>  private static get aspect() {<br>    return canvasData.container.width / canvasData.container.height;<br>  }<br><br>  private static isCameraInBounds(<br>    cameraX: number,<br>    cameraY: number,<br>    cameraZ: number<br>  ) {<br>    return true;<br>  }<br><br>  public static moveCamera(mx: number, my: number) {<br>    const scrollFactor = 1.5;<br>    const deltaX = mx * scrollFactor,<br>      deltaY = my * scrollFactor;<br>    const { x, y, z } = this.camera;<br>    if (this.isCameraInBounds(x + deltaX, y + deltaY, z)) {<br>      this.data.camera.x += deltaX;<br>      this.data.camera.y += deltaY;<br>      // move pointer by the same amount<br>      this.shouldRender = true;<br>      this.movePointer(deltaY, deltaY);<br>    }<br>  }<br><br>  public static zoomCamera(deltaX: number, deltaY: number) {<br>    // Normal zoom is quite slow, we want to scale the amount quite a bit<br>    const zoomScaleFactor = 10;<br>    const deltaAmount = zoomScaleFactor * Math.max(deltaY);<br>    const { x: oldX, y: oldY, z: oldZ } = this.camera;<br>    const oldScale = { ...this.scale };<br><br>    const { width: containerWidth, height: containerHeight } = this.container;<br>    const { width, height } = cameraToScreenCoordinates(<br>      oldX,<br>      oldY,<br>      oldZ + deltaAmount,<br>      CAMERA_ANGLE,<br>      this.aspect<br>    );<br>    const newScaleX = containerWidth / width;<br>    const newScaleY = containerHeight / height;<br>    const { x: newX, y: newY } = scaleWithAnchorPoint(<br>      this.pointer.x,<br>      this.pointer.y,<br>      oldX,<br>      oldY,<br>      oldScale.x,<br>      oldScale.y,<br>      newScaleX,<br>      newScaleY<br>    );<br>    const newZ = oldZ + deltaAmount;<br>    this.shouldRender = true;<br>    if (this.isCameraInBounds(oldX, oldY, newZ)) {<br>      this.data.camera = {<br>        x: newX,<br>        y: newY,<br>        z: newZ,<br>      };<br>    }<br>  }<br><br>  // pointer position from top left of the screen<br>  public static movePointer(deltaX: number, deltaY: number) {<br>    const scale = this.scale;<br>    const { x: left, y: top } = this.screen;<br>    this.data.pointer.x = left + deltaX / scale.x;<br>    this.data.pointer.y = top + deltaY / scale.y;<br>  }<br>}</pre><p>We have covered the logic behind this CanvasStore in our previous post, so if you’re still confused I urge you to go through that post for more clarity. The only additional part is the idea of a shouldRender boolean.</p><p>We don’t want to render the whole tree at 60fps if nothing has changed. So we set shouldRender only when something new has occurred in the UI. This is an optimization that should make our code more performant</p><p>This is what our output looks once we put it all together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*5kHAXOLchokhrbLekvpfFQ.gif" /><figcaption>An infinite canvas with scrolling and pinch zooming</figcaption></figure><p>I hope you learned and are playing around with more infinite canvas experiences in many tools and frameworks. I believe they are one of the most powerful experiences you can give to a user, and it’s a concept that inspires me a lot. All the best in your journey and keep building beautiful things :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2b0365b2a7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-create-a-figma-like-infinite-canvas-in-react-a2b0365b2a7">How to Create a Figma-like Infinite Canvas in React</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create a Figma-like Infinite Canvas in WebGL]]></title>
            <link>https://medium.com/better-programming/how-to-create-a-figma-like-infinite-canvas-in-webgl-8be94f65674f?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be94f65674f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[figma]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Thu, 03 Nov 2022 10:19:24 GMT</pubDate>
            <atom:updated>2022-11-17T09:16:41.330Z</atom:updated>
            <content:encoded><![CDATA[<h4>A primer on how to do a simple 2D camera projection to simulate an infinite canvas</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*y8aMr8e00dRhoOhY" /><figcaption>Photo by <a href="https://unsplash.com/@theshubhamdhage?utm_source=medium&amp;utm_medium=referral">Shubham Dhage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>An infinite canvas is one of the most beautiful experiences you can give to users. One of the benefits of the internet is that we can create experiences that are impossible to attain in the real world. You can build 3D models in Blender as far and as wide as you like without any space constraints of the real world.</p><p>Infinite canvases are not a new invention, however. 3D tools have had them for a long time, and so have game engines and other creator tools. Our challenge, if we choose to accept it, is to merge the ideas that we need from these pre-existing tools and build our own simplified version of this.</p><h3>Foundations</h3><p>In order to do that, we need to first understand what 3D projection is. The idea behind an infinite canvas is that there is a world (where all objects are placed) and there is a camera (which is just a projection of the world). What the user sees is what the camera projects. And the user can move around the camera however they see fit. This way, the world can exist in seemingly infinite space and you could go to the negative and positive x-y axes till infinity. If you need to, you can constrain the camera to only show one region, but you could also allow unbounded exploration in your canvas if you like.</p><p>The way this is done for 3D projection is fascinating, but it might be overkill for us to implement projection matrices. Since we are modeling a 2D world in our Figma-like canvas, our math looks a lot simpler with just a few geometric concepts that we have to be kept in mind.</p><figure><img alt="A diagram showing the way a camera projects a region of the infinite canvas" src="https://cdn-images-1.medium.com/max/1024/1*59IngIJ4xqwC629qD89APA.png" /><figcaption>The camera’s projection of a region on the canvas</figcaption></figure><p>In our case, our camera is a point in the z axis and it is always pointed towards our x-y plane. We can control how much zoom is allowed by constraining the camera to only some z values. Our canvas can stretch to Infinity on the x and the y axes.</p><p>First, we need to find our initial projection. That means we need to find out where to place our camera initially. We only want to project enough of the canvas that can be painted on the browser. No point drawing more of the canvas when it will not be seen by the user. So we will be working with the aspect ratio of our browser screen.</p><p>In order to come up with our equations, let us try to paint a region of the canvas. We will start off with projecting the canvas from (0,0) to (screen width, screen height) in the x-y plane. Let’s try to figure out where to place our camera so we can see this region. The x and y coordinates of the camera are simple. We will place them in the middle of the projection, looking right down. So the x and y coordinate are (screen width / 2, screen height / 2).</p><p>In order to place the z coordinate of our camera, we need to set a constant, which will remain the same irrespective of the zoom or where the camera is positioned. That constant is the camera angle. We will keep it for 30 degrees, but we can experiment with different values of this as well.</p><p>Once we know our angle, it becomes possible for us to find the height of the camera. But before we do that, let us revise some simple geometrical concepts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_V2itBQ3Mn7U3Eiio4_a3w.png" /><figcaption>Diagram to calculate the height of the camera</figcaption></figure><pre>tan θ is also called as <strong>law of tangent</strong>. The tangent formula for a right-angled triangle can be defined as the ratio of the opposite side of a triangle to the adjacent side.</pre><pre>Tan(θ) = (ScreenWidth / 2) / z<br>z = ScreenWidth / (2 * Tan(θ))</pre><p>Once we have this formula, we can place the camera. And anytime we move the camera, we can figure out the width of the projection rectangle that is visible using the formula above. Once you figure out the width, we can derive the height the aspect ratio of our browser screen. The reason we want to keep the same aspect ratio is that we don’t want to paint more than what the user can see.</p><h3>Implementation</h3><p>Now that we’ve learnt the main concepts behind the 2D projections for an Infinite Canvas, we can get down to the implementation stage. Before we get into the state management and logic, let us set up expectations of what we are building. We want to test out a few things-</p><ul><li>We should be to zoom in and out of a canvas and see more of the canvas</li><li>We should be able to move the camera left and right and see different parts of the canvas</li></ul><p>In order to test these things, this is the simplest Proof of Concept that we can make that will test all our conditions-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2I8aLs5sR2_BaACI7pTCvg.png" /><figcaption>Expected output of our program. It is a grid of many colors with texts on each block</figcaption></figure><p>The idea is that we draw a bunch of blocks of different colors and different text in the middle of each block. We set the camera near the middle of the canvas initially, and then when we zoom and scroll, we can see our infinite canvas in action.</p><p>I will be using Pixi.js as our WebGL library to do the drawing, but the exact framework for drawing does not matter. The state management and the logic can be understood and implemented in any library and language. Once the foundations are laid, it can be used everywhere.</p><pre>import { Application, Container, Graphics, Text } from &quot;pixi.js&quot;;<br>// Listener that will host our zoom and strafe camera actions<br>const wheelListener = (e: Event) =&gt; {<br>  e.preventDefault();<br>  e.stopPropagation();<br>};<br>// Listener to keep track of our pointer. Used for accurate zoom<br>const pointerListener = (event: PointerEvent) =&gt; {<br>  CanvasStore.movePointer(event.offsetX, event.offsetY);<br>};<br>class App {<br>  // Draws blocks with texts in the middle of them<br>  private drawCanvas() {<br>    const container = new Container();<br>    const colors = [<br>      0xf1f7ed, 0x61c9a8, 0x7ca982, 0xe0eec6, 0xc2a83e, 0xff99c8, 0xfcf6bd,<br>      0x9c92a3, 0xc6b9cd,<br>    ];<br>    const texts = [<br>      &quot;Infinite&quot;,<br>      &quot;Canvases&quot;,<br>      &quot;Are&quot;,<br>      &quot;Easy&quot;,<br>      &quot;When&quot;,<br>      &quot;You&quot;,<br>      &quot;Know&quot;,<br>      &quot;The&quot;,<br>      &quot;Fundamentals&quot;,<br>    ];<br>    const rectW = 500;<br>    const rectH = 500;<br>    for (let i = 0; i &lt; 9; i++) {<br>      const block = new Container();<br>      const randomColor = colors[i];<br>      const bg = new Graphics();<br>      const leftOffset = (i % 3) * rectW;<br>      const topOffset = Math.floor(i / 3) * rectH;<br>      bg.beginFill(randomColor);<br>      bg.drawRect(leftOffset, topOffset, rectW, rectH);<br>      bg.endFill();<br>      block.addChild(bg);<br>      const textElement = new Text(texts[i], {<br>        fontSize: 10,<br>        fill: 0x000000,<br>        fontWeight: &quot;700&quot;,<br>        wordWrap: false,<br>      });<br>      textElement.anchor.set(0.5);<br>      textElement.position.set(leftOffset + block.width / 2, topOffset + block.height / 2);<br>      block.addChild(textElement);<br>      container.addChild(block);<br>    }<br>    return container;<br>  }<br>  attach(root: HTMLElement) {<br>    const app = new Application({<br>      width: document.body.clientWidth,<br>      height: document.body.clientHeight,<br>      backgroundColor: 0xffffff,<br>      resolution: 2,<br>      antialias: true,<br>      autoDensity: true,<br>    });<br>    root.appendChild(app.view);<br>    const canvas = this.drawCanvas();<br>    app.stage.addChild(canvas);<br>    root.addEventListener(&quot;mousewheel&quot;, wheelListener, { passive: false });<br>    root.addEventListener(&quot;pointermove&quot;, pointerListener, {<br>      passive: true,<br>    });<br>  }<br>  detach(root: HTMLElement) {<br>    root.removeEventListener(&quot;mousewheel&quot;, wheelListener);<br>    root.removeEventListener(&quot;pointermove&quot;, pointerListener);<br>  }<br>}<br>// Loading and Unloading logic for our app<br>let _app: App | null;<br>window.onload = () =&gt; {<br>  _app = new App();<br>  _app.attach(document.body);<br>};<br>window.onbeforeunload = () =&gt; {<br>  if (_app) _app.detach(document.body);<br>};</pre><figure><img alt="A screenshot showing 2 zoomed in blocks with some text on them" src="https://cdn-images-1.medium.com/max/1024/1*NpWKrhXDL63MrfOpmzmgqg.png" /><figcaption>What our output looks like currently without projection and scroll/zoom</figcaption></figure><h4>State Management</h4><p>We have now drawn our canvas, but we are not able to appreciate it in all its glory. We can neither scroll nor zoom in. This is because we have not set up our camera, so let’s start with that. For now, we’ll keep a singleton called CanvasStore which holds our logic and camera state. We can move all this to better structures depending on the scale and needs of our application, but that is not required for this Proof of Concept.</p><pre>interface CanvasState {<br>  pixelRatio: number; // our resolution for dip calculations<br>  container: {   //holds information related to our screen container<br>    width: number;<br>    height: number;<br>  };<br>  camera: {  //holds camera state<br>    x: number;<br>    y: number;<br>    z: number;<br>  };<br>}<br>export const getInitialCanvasState = (): CanvasState =&gt; {<br>  return {<br>    pixelRatio: window.devicePixelRatio || 1,<br>    container: {<br>      width: 0,<br>      height: 0,<br>    },<br>    camera: {<br>      x: 0,<br>      y: 0,<br>      z: 0,<br>    },<br>  };<br>};<br>const radians = (angle: number) =&gt; {<br>  return angle * (Math.PI / 180);<br>};<br>export const CAMERA_ANGLE = radians(30);<br>export const RECT_W = 500;<br>export const RECT_H = 500;<br>export default class CanvasStore {<br>  private static get data() {<br>    if (!canvasData) canvasData = {<br>    pixelRatio: window.devicePixelRatio || 1,<br>    pixelsPerFrame: 1,<br>    container: {<br>      width: 0,<br>      height: 0,<br>    },<br>    pointer: {<br>      x: 0,<br>      y: 0,<br>    },<br>    canvas: {<br>      width: 0,<br>      height: 0,<br>    },<br>    camera: {<br>      x: 0,<br>      y: 0,<br>      z: 0,<br>    },<br>  };<br>    return canvasData;<br>  }<br>static initialize(width: number, height: number) {<br>    const containerWidth = width;<br>    const containerHeight = height;<br>    canvasData = getInitialCanvasState();<br>    canvasData.pixelRatio = window.devicePixelRatio || 1;<br>    canvasData.container.width = containerWidth;<br>    canvasData.container.height = containerHeight;<br>    canvasData.camera.x = 1.5 * RECT_W;<br>    canvasData.camera.y = 1.5 * RECT_H;<br>    canvasData.camera.z = containerWidth / (2 * Math.tan(CAMERA_ANGLE));<br>  }<br>public static get screen() {<br>    const { x, y, z } = this.camera;<br>    const aspect = this.aspect;<br>    const angle = radians(30);<br>    return cameraToScreenCoordinates(x, y, z, angle, aspect);<br>  }<br>public static get camera() {<br>    return this.data.camera;<br>  }<br>public static get scale() {<br>    const { width: w, height: h } = CanvasStore.screen;<br>    const { width: cw, height: ch } = CanvasStore.container;<br>    return { x: cw / w, y: ch / h };<br>  }</pre><p>One of the important concept in the code block above is the initialize method, which sets the up the following values-</p><ul><li>Store our pixelRatio for a density independent pixel calculations if needed</li><li>Stores the height and width of our canvas element on the browser (currently our whole document body, but can be of any size)</li><li>Calculates and sets our initial camera position. It is in the middle of our 9 blocks. Each block has a dimension of RECT_W x RECT_H. And we have laid out the formula for the height of the camera at the start of this post</li></ul><p>The other important concept is this function cameraToScreenCoordinates, which we have not covered yet. The way this function works is that it takes the camera coordinates, the camera angle, the container aspect ratio, and returns to us the part of the Infinite Canvas that is visible to the user. So we can just display the rectangle specified by the return value of this function and the user will see what the camera sees.</p><pre>export const cameraToScreenCoordinates = (<br>  x: number,<br>  y: number,<br>  z: number,<br>  cameraAngle: number,<br>  screenAspect: number<br>) =&gt; {<br>  const width = 2 * z * Math.tan(CAMERA_ANGLE);<br>  const height = width / screenAspect;<br>  const screenX = x - width / 2;<br>  const screenY = y - height / 2;<br>return { x: screenX, y: screenY, width, height };<br>};</pre><h4>Integrating the Camera Projection</h4><p>Now that we’ve setup our logic and state, we need to wire it to our display code so that we see and draw only the camera projection that is to be shown to the user. The way we do this is that we have to rewrite our attach<strong><em> </em></strong>function that we had used above. It now looks like this:</p><pre>attach(root: HTMLElement) {<br>    CanvasStore.initialize(<br>      document.body.clientWidth,<br>      document.body.clientHeight<br>    );<br>    const app = new Application({<br>      width: document.body.clientWidth,<br>      height: document.body.clientHeight,<br>      backgroundColor: 0xffffff,<br>      resolution: 2,<br>      antialias: true,<br>      autoDensity: true,<br>    });<br>    root.appendChild(app.view);<br>    const canvas = this.drawCanvas();<br>    app.stage.addChild(canvas);<br>    app.ticker.add(() =&gt; {<br>      const { x, y } = CanvasStore.screen;<br>      const scale = CanvasStore.scale;<br>      canvas.position.set(-scale.x * x, -scale.y * y);<br>      canvas.scale.set(scale.x, scale.y);<br>    });<br>    root.addEventListener(&quot;mousewheel&quot;, wheelListener, { passive: false });<br>    root.addEventListener(&quot;pointermove&quot;, pointerListener, {<br>      passive: true,<br>    });<br>  }</pre><p>We have initialized our store at the start of the application, and every frame, we are repositioning our application to move the region mentioned by CanvasStore.screen<strong><em> </em></strong>to (0,0) and (screen width, screen height).</p><p>So now, based on the scale and position, only the camera projection is visible to the user. We can also add a Mask to this to only draw the portion based on the screen size, but that is left as an exercise to the user.</p><h4>Implementing Scroll and Zoom with Anchor Point</h4><p>Now that we’ve set up our display and our state, we can dive into the most important and fun portion of this tutorial — making things move. The whole benefit of the Infinite Canvas is getting to mess around and move around everywhere. Let’s have a look at the scroll function that we will put in our CanvasStore:</p><pre>public static moveCamera(mx: number, my: number) {<br>    const scrollFactor = 1.5;<br>    const deltaX = mx * scrollFactor;<br>    const deltaY = my * scrollFactor;<br>    const { x, y, z } = this.camera;<br>    this.data.camera.x += deltaX;<br>    this.data.camera.y += deltaY;<br>    // move pointer by the same amount<br>    this.movePointer(deltaY, deltaY);<br>  }<br>public static movePointer(deltaX: number, deltaY: number) {<br>    const scale = this.scale;<br>    const { x: left, y: top } = this.screen;<br>    this.data.pointer.x = left + deltaX / scale.x;<br>    this.data.pointer.y = top + deltaY / scale.y;<br>  }</pre><p>The logic in this is quite straightforward, we are moving the camera and the pointer based on the amount that was scrolled. We also have a scrollFactor so we can speed up or slow down the scroll behaviour. Why are we maintaining the pointer position? Well we will understand that when we get to implementing the next part — Scroll with Anchor Point. The best way to describe this behaviour is to show it</p><figure><img alt="An animated image showing a target zoom into the text element" src="https://cdn-images-1.medium.com/max/600/1*oRSw2JCxpZUbCbSMQ0xtkw.gif" /><figcaption>Targeted zoom towards the pointer position (at the text element)</figcaption></figure><p>In the zoom above, you can see that we detect the user’s pointer position and make sure to zoom into the place that their pointer rests on. The way we do this is we change the scale but also scroll the canvas a little bit so that the pointer still points to the same pixel it did before. Now that we’ve understood how that behaviour works, we can dive into the logic:</p><pre>const scaleWithAnchorPoint = (<br>  anchorPointX: number,<br>  anchorPointY: number,<br>  cameraX1: number,<br>  cameraY1: number,<br>  scaleX1: number,<br>  scaleY1: number,<br>  scaleX2: number,<br>  scaleY2: number<br>) =&gt; {<br>  const cameraX2 =<br>    (anchorPointX * (scaleX2 - scaleX1) + scaleX1 * cameraX1) / scaleX2;<br>  const cameraY2 =<br>    (anchorPointY * (scaleY2 - scaleY1) + scaleY1 * cameraY1) / scaleY2;<br>return { x: cameraX2, y: cameraY2 };<br>};<br>public static zoomCamera(deltaX: number, deltaY: number) {<br>    // Normal zoom is quite slow, we want to scale the amount quite a bit<br>    const zoomScaleFactor = 10;<br>    const deltaAmount = zoomScaleFactor * Math.max(deltaY);<br>    const { x: oldX, y: oldY, z: oldZ } = this.camera;<br>    const oldScale = { ...this.scale };<br>const { width: containerWidth, height: containerHeight } = this.container;<br>    const { width, height } = cameraToScreenCoordinates(<br>      oldX,<br>      oldY,<br>      oldZ + deltaAmount,<br>      this.cameraAngle,<br>      this.aspect<br>    );<br>    const newScaleX = containerWidth / width;<br>    const newScaleY = containerHeight / height;<br>    const { x: newX, y: newY } = scaleWithAnchorPoint(<br>      this.pointer.x,<br>      this.pointer.y,<br>      oldX,<br>      oldY,<br>      oldScale.x,<br>      oldScale.y,<br>      newScaleX,<br>      newScaleY<br>    );<br>    const newZ = oldZ + deltaAmount;<br>    this.data.camera = {<br>      x: newX,<br>      y: newY,<br>      z: newZ,<br>    };<br>  }</pre><p>We can now integrate this into our scroll wheel handler that we defined above:</p><pre>const wheelListener = (e: Event) =&gt; {<br>  e.preventDefault();<br>  e.stopPropagation();<br>  const friction = 1;<br>  const event = e as WheelEvent;<br>  const deltaX = event.deltaX * friction;<br>  const deltaY = event.deltaY * friction;<br>  if (!event.ctrlKey) {<br>    CanvasStore.moveCamera(deltaX, deltaY);<br>  } else {<br>    CanvasStore.zoomCamera(deltaX, deltaY);<br>  }<br>};</pre><p>With that done, we can finally look at the output of our infinite canvas. We start with the camera in the middle of the 5th block, we scroll, zoom out and zoom in a few times onto the text to show how it works together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*aPUJhRWwD09cXe_f_xkYfA.gif" /></figure><h3>Conclusion</h3><p>This was a primer on how to do a simple 2D camera projection to simulate an infinite canvas. The only thing remaining is placing things in the infinite canvas and this camera system should theoretically be able to hold and show any amount of content depending on the use case. I have always been fascinated by creator tools that have Canvas interfaces, and I am very curious to see what others come up.</p><p>If you liked this tutorial and want to see more of this, do like, share and comment, and maybe I’ll do some more complicated in-depth projects. Go forth, and build things.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be94f65674f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-create-a-figma-like-infinite-canvas-in-webgl-8be94f65674f">How to Create a Figma-like Infinite Canvas in WebGL</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Implement Pinch to Zoom on the Browser in Angular]]></title>
            <link>https://levelup.gitconnected.com/how-to-implement-pinch-to-zoom-on-the-browser-in-angular-6ad56ce54df4?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ad56ce54df4</guid>
            <category><![CDATA[experience-design]]></category>
            <category><![CDATA[interaction-design]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[user-experience]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Thu, 06 May 2021 00:25:17 GMT</pubDate>
            <atom:updated>2021-05-09T16:18:46.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XyXUJS21kjv7zU0y" /><figcaption>Photo by <a href="https://unsplash.com/@sigmund?utm_source=medium&amp;utm_medium=referral">Sigmund</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>At <a href="https://invideo.io/">Invideo</a>, we’re always looking to give our customers the best user experience to empower them to make their best videos. A key aspect of this is their workflow around the timeline</p><p>For video editors, the timeline is the most integral aspect of the tool that they use. Users intuitively pinch the touchpad or trackpad that they work on to see if the timeline zoom works. It is such an intrinsic part of their creation workflow, that muscle memory kicks in</p><p>However, pinch to zoom on desktop browsers lacks cohesive support. This interaction is not part of any spec, which makes it very difficult to implement. However, there are workarounds so you can get a good enough pinch zoom experience for all</p><h3>The Problem</h3><p>The trackpad as a concept is a very weird one when it comes to browsers and its implementation</p><pre>&quot;Are trackpad events mouse events? Are they touch events? Are they somewhere in between&quot;</pre><pre>- Buddha, post enlightenment, getting utterly confused by javascript</pre><p>Since there is no new event that can completely categorise the trackpad events, the browsers have found workarounds. 2 finger movements have been mapped to the scroll event. Some OS’s for example captures a 3 finger touch and sends the right click event to the browser</p><p>How does this relate to Pinch to Zoom? Well, some browsers have employed workarounds with respect to the pinch interaction as well. The first one is to send the mousewheel event with the ctrlKey value set to true. The default behaviour for this is to zoom the whole screen, but by calling preventDefault we can override this. Reference links to understand this at the bottom</p><p>The browser support seems to be as following:</p><ul><li>Chrome: ✅ since Chrome M35</li><li>Firefox: ✅ since Firefox 55</li><li>Edge: ✅ <a href="https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/7134034/">Unless you are using a “precision-touchpad”</a></li><li>Safari does not follow this convention, but has another workaround</li></ul><p>Safari instead handles this using a proprietary GestureEvent that is triggered with a scale value that is triggered when a pinch is performed by the user. More information <a href="https://developer.mozilla.org/en-US/docs/Web/API/GestureEvent">here</a></p><h3>Implementation in Angular</h3><p>Now that we’ve understood the basics and even a little bit of the history of this support, let’s dive into some code. How we’ve utilized this at Invideo is to implement a stepped zoom functionality on our video timeline. It kind of looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NVLG-1H6sJXssUwN75OoDg.png" /><figcaption><a href="https://en.wikipedia.org/wiki/Jhoom_Barabar_Jhoom">Zoom Barabar Zoom</a></figcaption></figure><p>Our timeline is dynamic and javascript based, so a directive would be best to implement our pinch zoom logic. An implementation would kind of look like this.</p><pre>import { Directive, HostListener, Input, OnInit, Output } from &#39;@angular/core&#39;;<br>import { Subject } from &#39;rxjs&#39;;<br>import { clamp } from &#39;lodash&#39;;</pre><pre>@Directive({<br>  selector: &#39;[appPinchZoom]&#39;,<br>})<br>export class PinchZoomDirective implements OnInit {<br>  <a href="http://twitter.com/Input">@Input</a>() scaleFactor: number = 0.08;<br>  <a href="http://twitter.com/Input">@Input</a>() zoomThreshold: number = 9;<br>  <a href="http://twitter.com/Input">@Input</a>() initialZoom: number = 5;<br>  <a href="http://twitter.com/Input">@Input</a>() debounceTime: number = 100; // in ms<br>  scale: number;<br>  <a href="http://twitter.com/Output">@Output</a>() onPinch$: Subject&lt;number&gt; = new Subject&lt;number&gt;();</pre><pre>  constructor() {<br>    <br>  }</pre><pre>  ngOnInit(): void {<br>    this.scale = this.initialZoom;<br>  }</pre><pre>  @HostListener(&#39;wheel&#39;, [&#39;$event&#39;])<br>  onWheel($event: WheelEvent) {<br>    if (!$event.ctrlKey) return;<br>    $event.preventDefault();<br>    let scale = this.scale - $event.deltaY * this.scaleFactor;<br>    scale = clamp(scale, 1, this.zoomThreshold);</pre><pre>    this.calculatePinch(scale);<br>  }</pre><pre>  calculatePinch(scale: number) {<br>    this.scale = scale;<br>    this.onPinch$.next(this.scale));<br>  }<br>}</pre><p>This directive calculates pinch logic, calculates when the scale has gone up a step and sends in an output event onPinch. The main code of this is in the onWheel function, which takes the mousewheel event, listens to the ctrlKey value and based on a scaleFactor that controls sensitivity.</p><p>Using this is as simple as just calling this directive in a component and setting the sensitivity factor</p><pre>// timeline.component.html<br>&lt;div<br>  class=&quot;timeline&quot;<br>  #timeline<br>  appPinchZoom<br>  (onPinch$)=&quot;onPinch($event)&quot;<br>  [scaleFactor]=&quot;0.02&quot;<br>  [zoomThreshold]=&quot;9&quot;<br>  [initialZoom]=&quot;5&quot;<br>&gt;<br>  &lt;!-- timeline internals go here --&gt;</pre><pre>&lt;/div&gt;</pre><pre>// timeline.component.ts<br><a href="http://twitter.com/Component">@Component</a>({<br>  selector: &#39;app-timeline-v2&#39;,<br>  templateUrl: &#39;./timeline-v2.component.html&#39;,<br>  styleUrls: [&#39;./timeline-v2.component.scss&#39;],<br>})<br>export class TimelineComponent{<br>  constructor(private timelineService: TimelineService) {}<br>  onPinch(level: number) {<br>    this.timelineService.updateZoom(level);<br>  }<br>}</pre><p>An astute observer would see that we have only implemented this functionality for the Chrome , Firefox and Edge, which has implemented the ctrlKey fix. So what do we do for Safari? Thank you, I thought you’d never ask even though I’ve been dying to tell.</p><pre>  @HostListener(&#39;gesturestart&#39;, [&#39;$event&#39;])<br>  @HostListener(&#39;gesturechange&#39;, [&#39;$event&#39;])<br>  @HostListener(&#39;gestureend&#39;, [&#39;$event&#39;])<br>  onGesture($event: any) {<br>    $event.preventDefault();<br>    let pinchAmount = $event.scale - 1;<br>    let scale = this.scale + pinchAmount * this.scaleFactor;<br>    scale = clamp(scale, 1, this.zoomThreshold + this.thresholdBuffer);</pre><pre>    this.calculatePinch(scale);<br>  }</pre><p>And you’re good to go. It’s time to boast about this by writing a blog post 😉</p><h4>Possible improvements</h4><p>This article covers the basics of implementing the pinch zoom for browsers, but not much about the best way to use this. What is going on inside our onPinch function, how do we render our elements on the timeline so that it is not janky? How can we optimise performance? Stay tuned on the next episode of “Vikram Groks The Internet”, coming soon to a Medium publication near you</p><h4>References</h4><ul><li><a href="https://github.com/w3c/uievents/issues/31">[Proposal] Add &quot;Zoom&quot; event · Issue #31 · w3c/uievents</a></li><li><a href="https://github.com/w3c/pointerevents/issues/206">Extend pointer events to support raw trackpad data · Issue #206 · w3c/pointerevents</a></li><li><a href="https://bugzilla.mozilla.org/show_bug.cgi?id=1052253">1052253 - OS X: Pinch to zoom gesture should map to mousewheel with the control key, like Chrome</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/GestureEvent">GestureEvent - Web APIs | MDN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ad56ce54df4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-implement-pinch-to-zoom-on-the-browser-in-angular-6ad56ce54df4">How to Implement Pinch to Zoom on the Browser in Angular</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Realistic Paper Tearing Animation using React Spring]]></title>
            <link>https://medium.com/weekly-webtips/creating-a-realistic-paper-tearing-animation-using-react-spring-8387f25dff1b?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/8387f25dff1b</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-spring]]></category>
            <category><![CDATA[user-experience]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Thu, 16 Jul 2020 12:25:19 GMT</pubDate>
            <atom:updated>2020-08-18T14:05:44.974Z</atom:updated>
            <content:encoded><![CDATA[<h4>Lactose-free buttery animations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ep4NUnUtNn_0F2aSAm9EtA.gif" /><figcaption>Wax on, Wax off</figcaption></figure><p>Long gone are the days where you just wrap your components in ReactTransitionGroups and hope to dear life that your animations chain one after another to get that sweet buttery animation. But now we have the better butter, a buff butter that never buffers (your daily tongue twister from a lovely mister). I am, of course, talking about <a href="https://www.react-spring.io/">React Spring</a>. It’s an animation library that emulates spring physics into our app so the animations appear smoother.</p><p>I’ve been working on a productivity app, and one thing I’ve wanted to emulate is my use of Post-it notes to keep track of things to do throughout the day. And if I want an app to recreate the experience of writing and maintaining those notes, then I need to emulate the material that makes those notes - Paper</p><h3>Setting up the Butter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*oulWJPD_FjHD1rs6ifzkWQ.png" /><figcaption>Pay attention to the textures</figcaption></figure><p>Let’s set up the foundations for our app. We’re going to need to recreate a wooden board, and then stick our bits of paper on that board. Along with their colors being consistent with the real world, we’d also want them to <strong>feel </strong>like real-world objects.</p><p>We’re going to use some lovely textures from the wonderful folks at <a href="https://www.transparenttextures.com/">TransparentTextures</a> to accomplish this. This is what our Home component looks like</p><pre>export default function Home() {<br>    return (<br>        &lt;div className={list}&gt;<br>            &lt;div className={listHeader}&gt;Today&lt;/div&gt;<br>            &lt;TodoList /&gt;<br>        &lt;/div&gt;<br>    )<br>}</pre><p>Here is our TodoList</p><pre>import Todo from &#39;./Todo&#39;<br>import { todolist } from &#39;./TodoList.module.scss&#39;</pre><pre>export default function TodoList (props) {<br>  <br>let todos = [{&quot;id&quot;:&quot;2bd7cbc716&quot;, &quot;name&quot;:&quot;Research and design a date picker&quot;,&quot;isChecked&quot;:false},<br>    {&quot;id&quot;:&quot;efc6e1edc4&quot;,&quot;name&quot;:&quot;Create the Add Todo view&quot;,&quot;isChecked&quot;:false},<br>    {&quot;id&quot;:&quot;72bed57be0&quot;,&quot;name&quot;:&quot;Animate the Check Todo action&quot;,&quot;isChecked&quot;:false},<br>    {&quot;id&quot;:&quot;0be851c06b&quot;,&quot;name&quot;:&quot;Make the Todo call&quot;,&quot;isChecked&quot;:false},<br>    {&quot;id&quot;:&quot;72634b2dcf&quot;,&quot;name&quot;:&quot;Do things&quot;,&quot;isChecked&quot;:false}]</pre><pre>return (<br>    &lt;div className={todolist}&gt;<br>      {todos.map(action =&gt; {<br>        return &lt;Todo key={action.id} action={action}&gt;&lt;/Todo&gt;<br>      })}<br>    &lt;/div&gt;<br>  )<br>}</pre><p>And finally, our Todo</p><pre>import { todo, todoWrapper, name, isChecked } from &#39;./TodoList.module.scss&#39;<br>import cn from &#39;classnames/bind&#39;</pre><pre>import SwipeTodo from &#39;../SwipeableItem/SwipeTodo&#39;;</pre><pre>let cx = cn.bind({todo, isChecked});</pre><pre>export default function Todo({key, action}) {</pre><pre>return (<br>    &lt;div className={todoWrapper}&gt;<br>      &lt;SwipeTodo action={action}&gt;<br>          &lt;div className={cx({todo: true, isChecked: action.isChecked})}&gt;<br>            &lt;div className={name}&gt;{action.name}&lt;/div&gt;<br>          &lt;/div&gt;<br>      &lt;/SwipeTodo&gt;<br>    &lt;/div&gt;<br>  )<br>}</pre><p>Don’t worry about the SwipeTodo or the { } brackets around the className. I’m using CSS Modules, but how I declare my CSS still looks the same-</p><pre>.list {<br>  padding: 5px 0px;<br>  height: 100%;<br>  overflow: auto;<br>  background: $primary;<br>  background-image: url(https://medium.com/&quot;%3Ca%20href=%22/service/https://www.transparenttextures.com/patterns/wood-pattern.png%22%3Ehttps://www.transparenttextures.com/patterns/wood-pattern.png%3C/a%3E&quot;);<br>  border-radius: 5px;<br>}</pre><pre>.listHeader {<br>  color: $black;<br>  font-family: marker;<br>  text-align: center;<br>  font-size: 30px;<br>}</pre><pre>.focusFooter {<br>  display: flex;<br>  justify-content: flex-end;<br>  margin-top: 10px;<br>  margin-right: 20px;<br>  margin-bottom: 20px;<br>}</pre><pre>.todolist {<br>  display: block;<br>  margin: 10px 20px;<br>  border-radius: 5px;<br>  border: 0;<br>  box-shadow: 0px 3px 2px -1px rgba(0,0,0,0.2),<br>    0px 2px 2px 0px rgba(0,0,0,0.04)<br>    ;</pre><pre>display: flex;<br>  flex-flow: row wrap;<br>  box-shadow: none;<br>  justify-content: space-evenly;<br>  margin: 5px 20px;</pre><pre>}</pre><pre>.todoWrapper {<br>  width: 150px;<br>  max-width: 150px;<br>  height: 150px;<br>  margin: 5px;<br>  flex-basis: 45%;<br>  font-family: Permanent Marker, Arial, Helvetica, sans-serif;<br>  user-select: none;<br>  position: relative;<br>}</pre><pre>.todo {<br>  width: 150px;<br>  height: 150px;<br>  border-radius: 2px;<br>  justify-content: center;<br>  font-family: Permanent Marker, Arial, Helvetica, sans-serif;<br>  background: adjust-hue($secondary, 5%);<br>  background-image: url(https://medium.com/&quot;%3Ca%20href=%22/service/https://www.transparenttextures.com/patterns/wood-pattern.png%22%3Ehttps://www.transparenttextures.com/patterns/%3C/a%3Eembossed-paper.png&quot;);<br>  border: none;<br>  box-shadow: 0px 3px 2px -1px rgba(0,0,0,0.2),<br>    0px 2px 2px 0px rgba(0,0,0,0.04) ;</pre><pre>  position: absolute;<br>  left: 0;<br>}</pre><pre>.name {<br>  font-size: 18px;<br>  text-align: center;<br>  color: black;<br>}</pre><p>The font we use here is the <a href="https://fonts.google.com/specimen/Permanent+Marker">Permanent Marker</a></p><h3>Churning the Butter</h3><p><em>In case I’m getting too heavy-handed with the butter analogies do let me know, I’ll make a note of it in my diary.</em></p><p>In order to understand how our SwipeTodo component works, we need to understand how a paper actually tears from wood. The paper can be broken down into two major parts</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/436/1*G8i_cXsNJ3oVOoJUTkycvg.png" /></figure><ul><li>At the start, the front side of the paper is shown</li><li>As it is torn away, the backsides shows and increase in width, while we see less of the front of the paper</li><li>As more is peeled away, the backside moves to the right, so it seems like the front side is “turning itself” into the backside of the paper</li></ul><p>Now that we understand the working of a real paper peel, let’s see how we can implement it in code. Firstly, we want to style the back paper different from the front. We do that by choosing a lighter color and a smooth texture (this is where our use of textures pays off) to differentiate it. And we give it a higher z-index and a box-shadow to make it look like it&#39;s over the front of the paper</p><pre>.swiper {<br>  position: absolute;<br>  right: 0;<br>  height: 100%;<br>  overflow: hidden;<br>  width: 100%;<br>}</pre><pre>.backPaper {<br>  height: 100%;<br>  position: absolute;<br>  left: 0;<br>  width: 10px;<br>  background: $secondary-lighter;<br>  z-index: 5;<br>  box-shadow: 4px 5px 15px -2px rgba(0,0,0,0.4);<br>}</pre><pre>.frontPaper {<br>  width: 150px;<br>  height: 150px;<br>  position: absolute; <br>}</pre><p>Another way to understand the positioning in this is that we are aligning the parent (.swiper) to the right of its parent (.todoWrapper), which we will be moving towards the right. So swiper makes sure our paper moves to the right, so .backPaper and .frontPaper only need to control their width and position with respect to .swiper.</p><p>Now let’s get into the code of SwipeTodo, and how we use React Spring to implement this motion so its smooth and buttery (I’m obsessed with that word aren’t I)</p><pre>import { useSpring, animated, interpolate } from &#39;react-spring&#39;;<br>import { useDrag } from &#39;react-use-gesture&#39;;<br>import { backPaper, frontPaper, swiper } from &#39;../TodoList/TodoList.module.scss&#39;;</pre><pre>export default function SwipeTodo({action, children}) {<br>  const [{x, y}, set] = useSpring(() =&gt; ({x: 0, y: 0}));<br>  const bindSwipe = useDrag(({down, movement: [mx, my], velocity}) =&gt; {<br>    let realisticX = mx * (1 + velocity);<br>    let realisticY = my;</pre><pre>if (!down) {<br>      // either torn or back based on current position<br>      realisticX = realisticX &gt; 150? window.innerWidth: 0;<br>    }</pre><pre>set({x: realisticX, y: realisticY});<br>  });</pre><pre>return (<br>    &lt;animated.div key={action.id} {...bindSwipe()} className={swiper} style={{overflow: &#39;hidden&#39;, width: &#39;100%&#39;, right: interpolate([x], (x) =&gt; `-${x}px`)}}&gt;<br>      &lt;animated.div className={backPaper} style={{width: interpolate([x], x=&gt; `${x}px`)}}&gt;&lt;/animated.div&gt;<br>      &lt;animated.div className={frontPaper} style={{left: interpolate([x], x =&gt; `-${x}px`)}}&gt;<br>        {children}<br>      &lt;/animated.div&gt;<br>    &lt;/animated.div&gt;</pre><pre>)<br>}</pre><p>Okay, that might be a lot of new code to understand in one go, so lets go through it line by line. Let’s go through the logic of calculating the x and y</p><pre>  const [{x, y}, set] = useSpring(() =&gt; ({x: 0, y: 0}));<br>  const bindSwipe = useDrag(({down, movement: [mx, my], velocity}) =&gt; {<br>    let realisticX = mx * (1 + velocity);<br>    let realisticY = my;</pre><pre>if (!down) {<br>      // either peels away or snaps back based on it&#39;s x value<br>      realisticX = realisticX &gt; 150? window.innerWidth: 0;<br>    }</pre><pre>set({x: realisticX, y: realisticY});<br>  });</pre><ul><li>useSpring here just generates a new spring so our animations are smooth. Think of it this way - if our x and y change from 0 to a 100, we want it to slowly tick up to it, not in one go. Also the set function allows us to manually set the x and y values that the spring will act on</li><li>useDrag is a function that we use to track the “drag” gesture of the user. It gives us the x-y coordinates, velocity of the swipe and when it ends</li><li>We use realisticX to set the value of x (y we will ignore). We want the velocity to have an impact on the x, so the paper moves faster if flicked</li><li>We also use a threshold when the user lets go of the paper. If they let go after 150px (it’s width) then we set the x to the ends of the window</li></ul><pre>&lt;animated.div key={action.id} {...bindSwipe()} className={swiper} style={{overflow: &#39;hidden&#39;, width: &#39;100%&#39;, right: interpolate([x], (x) =&gt; `-${x}px`)}}&gt;<br>      &lt;animated.div className={backPaper} style={{width: interpolate([x], x=&gt; `${x}px`)}}&gt;&lt;/animated.div&gt;<br>      &lt;animated.div className={frontPaper} style={{left: interpolate([x], x =&gt; `-${x}px`)}}&gt;<br>        {children}<br>      &lt;/animated.div&gt;<br>    &lt;/animated.div&gt;</pre><ul><li>animated.div is just a helper element that can read our changing x and y values and update the dom accordingly</li><li>We use the interpolate helper to read the x value and update the “right”, “left” and “width” values for our elements</li></ul><p>Voila! It’s time to enjoy some of that lactose-free goodness</p><h3>Spread the Butter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*mgfJ8XRcDL4g1vZ2INbjaQ.gif" /><figcaption>You can almost hear this gif. It sounds like Hollaback Girl by Gwen Stefani</figcaption></figure><p>Yes, before you ask, I had to show another gif of that animation. For science reasons.</p><p>Some might say my deep dive into paper physics might be overkill. And they might be right. My family is dying and I‘m missing a few limbs due to an unrelated black market paper acquisition deal. But it’s all worth it</p><h4>Where do we go from here</h4><p>To be honest there are a few improvements that can be made-</p><ul><li>Instead of the whole paper sticking to the board, we can have just the top half stick, like a post-it note. Though that is a little more complicated, involving triangles instead of rectangles for the peel off</li><li>We ignored the y-axis during this implementation. We could incorporate a tearing off motion that works on both the axes</li></ul><p>Both these improvements are a little complicated, and I might make a follow-up blog post if I see interest in this pique up. In the meantime, I need to try to get back my organs from the black market. They will accept views on Medium as a currency, won’t they?</p><p><strong>Note: No cows were harmed in the making of this butter</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8387f25dff1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/creating-a-realistic-paper-tearing-animation-using-react-spring-8387f25dff1b">Creating a Realistic Paper Tearing Animation using React Spring</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Strategies to split code in your React App]]></title>
            <link>https://medium.com/founding-ithaka/strategies-to-split-code-in-your-react-app-2c3c86953748?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c3c86953748</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Wed, 25 Apr 2018 05:37:18 GMT</pubDate>
            <atom:updated>2018-04-25T05:37:18.391Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3sqDZ38_eu0eQnfZqmzCXw.png" /><figcaption>Not the kind of split I’m talking about</figcaption></figure><p>We’re going to continue looking at different ways to bring down app size. If you haven’t, do check out the introductory blog post on how to code split your app through React Router over <a href="https://medium.com/founding-ithaka/code-splitting-with-create-react-app-10ea9541cb01">here</a>. It explains the fundamentals and internals of what we’re going to delve deeper into in this post.</p><p>We’ve already covered splitting code by pages or routes, which can be a great starting point. But sometimes it might prove inadequate for large apps with their ever increasing bundle sizes. And so here we’ll be looking at more detailed strategies to counter this.</p><h4>Pros and Cons</h4><p>Before we go further however, we must look at the drawbacks of this approach. There are a few disadvantages to code splitting as well, and there definitely is a thing as too much splitting.</p><p>For one, common plugins or code has to be bundled with each code split. For example, if a component uses Lodash, Moment and React Bootstrap, then all these packages need to be bundled in the component’s split in order for it to work.</p><p>Secondly, this does increase the number of requests that the browser makes to fetch content. In a slow connection, if not managed properly, it might be possible that the user still sees nothing but a bunch of loaders everywhere.</p><p>On the other hand, we would like the benefits that splitting provides, which is primarily to bring down our App’s bundle size. We can lazy load most elements like images which is great, but for most apps the greatest bulk is in the components. So we’d ideally like to lazy load some of these as well.</p><p>And in most cases, the pros outweigh the cons, however it is important you weigh each with your app to strike the right balance</p><h4>Splitting your Components</h4><p>We’re going to be looking at splitting code through this great library called <a href="https://github.com/jamiebuilds/react-loadable">React Loadable</a></p><p>In order to use this, we first need to get a loading component ready. Since our code split is going to be fetched asynchronously via promises, we need to show something on the UI while the promise resolves.</p><pre>import React from “react”;</pre><pre>export default class Loader extends React.Component {<br>  getSpinnerContent = () =&gt; {<br>    if (this.props.pastDelay) {<br>      return (<br>        &lt;div className=&quot;spinner-inner&quot;&gt;<br>          &lt;i className=&quot;fa fa-circle-o-notch fa-2x fa-spin&quot;&gt;&lt;/i&gt;<br>        &lt;/div&gt;<br>      )<br>    }<br>    else if (this.props.error) {<br>      return (<br>        &lt;div className=&quot;spinner-inner&quot;&gt;<br>          &lt;i className=&quot;fa fa-times fa-2x error&quot;&gt;&lt;/i&gt;<br>          &lt;div className=&quot;spinner-text&quot;&gt;Failed to load due to {this.props.error.message}&lt;/div&gt;<br>        &lt;/div&gt;<br>      )<br>    }<br>    else return null;<br>  }</pre><pre>  render() {<br>    return (<br>      &lt;div className={&quot;data-loader &quot; + (this.props.fullscreen? &quot;fullscreen&quot;: &quot;&quot;)}&gt;<br>        &lt;div className=&quot;spinner &quot;&gt;<br>          {this.getSpinnerContent()}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>    )<br>  }<br>}</pre><p>This component handles a few extra cases like requiring taking the full width of its container, or allowing for a static height and width instead. Also, an appropriate error message is printed to the UI if one does occur.</p><h4>Using React Loadable</h4><p>After creating the loading component, it can be used with React Loadable to start wrapping the components in our app.</p><pre>import Loadable from ‘react-loadable’;<br>import Loader from ‘./loader’;<br><br>const WrappedComponent = Loadable({<br>  loader: () =&gt; import(&#39;./ComponentToDisplayOnLoad&#39;),<br>  loading: Loader,<br>});</pre><pre>const App = () =&gt; (<br>  &lt;WrappedComponent/&gt;<br>);</pre><p>There is a way this can be further optimized though. In the above code, ComponentToDisplayOnLoad is fetched immediately when the app is rendered. This might be good in some scenarios, but for elements like Tabs, or Modals, wouldn’t it be better if we fetched the component only when the tab is clicked or content is visible?</p><h4>Loading components on demand</h4><p>Let’s take an example of Tabs and how we can utilize it to further optimize rendering and speed in our app. Lets assume, for simplicity, we use <a href="https://react-bootstrap.github.io/">React Bootstrap</a> to render our tabs in this example</p><pre>import Loadable from ‘react-loadable’;<br>import Loader from ‘./loader’;<br><br>const WrappedComponent1 = Loadable({<br>  loader: () =&gt; import(&#39;./Component1&#39;),<br>  loading: Loader,<br>})<br>const WrappedComponent2 = Loadable({<br>  loader: () =&gt; import(&#39;./Component2&#39;),<br>  loading: Loader,<br>})</pre><pre>&lt;Tabs defaultActiveKey={1}&gt;<br>  &lt;Tab eventKey={1}&gt;<br>    &lt;WrappedComponent1 /&gt;<br>  &lt;/Tab&gt;<br>  &lt;Tab eventKey={2} mountOnEnter&gt;<br>    &lt;WrappedComponent2 /&gt;<br>  &lt;/Tab&gt;<br>&lt;/Tabs&gt;</pre><p>Here, Component1 would be fetched at the start of the app, whereas Component2 would only be fetched when the second tab is clicked via the mountOnEnter prop that React Bootstrap provides.</p><p>We can even use this strategy while displaying alerts or modals (without external dependencies), and defer rendering until this.props.buttonClicked is true.</p><h4>Optimal split points</h4><p>Now that we’ve looked at how to go about splitting code into components and loading them asynchronously, lets look at where we should be using this-</p><ul><li>In general: Any component that is bulky or uses many sub components should be split into its own bundle. If in doubt, break down the component into its own splits. Make sure you don’t over do it though and have the browser do umpteen requests for every small component in the app</li><li>Tabs, Modals, Alerts, Carousels, Paginations etc: Basically any component that can load content on demand and based on visibility should be split into its own bundle, and should defer fetching until it is visible in the UI</li><li>Process flows: Things like checkout flows or booking flows, which show different steps and continue based on button clicks should be split per step. We wouldn’t want to load step 10 when the user is just viewing step 2 of the flow now, would we?</li><li>Widgets: These are simple to split as they are already self contained components with minimal code coupling, and splitting them can make the app much more lightweight</li></ul><p>Got some additional suggestions on other ways to code split components in apps? Drop down a comment below :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c3c86953748" width="1" height="1" alt=""><hr><p><a href="https://medium.com/founding-ithaka/strategies-to-split-code-in-your-react-app-2c3c86953748">Strategies to split code in your React App</a> was originally published in <a href="https://medium.com/founding-ithaka">Founding Ithaka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing push notifications with Create React App]]></title>
            <link>https://medium.com/founding-ithaka/implementing-push-notifications-with-create-react-app-bf35cd25d870?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf35cd25d870</guid>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <category><![CDATA[service-worker]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 17:26:14 GMT</pubDate>
            <atom:updated>2018-04-16T17:26:14.076Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the benefits of CRA and React is the speed/performance it provides. One of the greatest ways it does so is using Service Workers to cache all static files when deployed in production. This means that every subsequent request to the app resolves much quicker and makes the app seem much smoother.</p><p>However at times we want more from our apps. We want to be able to do things like send push notifications to further engage and bring back our users. However there is no out of the box support for extending the default service worker that CRA provides. Here we’ll go over some ways we can do so ourselves. Be warned that each of these ways requires one to eject (yarn eject) from the default CRA configuration.</p><h4>Step 1: Understanding the default CRA service worker</h4><p>Create React App uses <a href="https://github.com/GoogleChromeLabs/sw-precache">sw-precache</a> internally in its build process to generate the cacheable resources and save it to the app cache. It detects all the static resources and generates their hashes and stores them in the generate service-worker.js file.</p><p>It then ensures that each of these files are served cache-first. This way the most important part of our app — the shell — shows up immediately.</p><p>An important part of its functionality is also keeping the cache up to date with the latest files. How it does this is quite simple. Each subsequent build of our CRA app creates a new set of file with new hashes. Along with this a new service-worker.js file is created with these new files with the new hashes of the files</p><p>The browser then checks periodically if a new service worker is available with a different content hash. Since a new one is available, it is fetched and downloaded, along with the new files. We can link to when the “new content is available” event in the registerServiceWorker.js file</p><h4>Step 2: Set up the custom service worker</h4><p>Create a file called custom-service-worker.js which details what should happen when the push notification is clicked or actioned in any way. In this part we just log the actions done and if the notification is clicked, we take them to the index page and remove the notification. Here we assume notifications are sent in this format -</p><pre>{<br>  data: {<br>    primaryKey: String, // any unique identifier<br>    body: {<br>      // body of the notification<br>    }<br>  }<br>}</pre><p>Code -</p><pre>self.addEventListener(‘notificationclose’, function (e) {<br>  var notification = e.notification;<br>  var data = notification.data || {};<br>  var primaryKey = data.primaryKey;</pre><pre>  console.debug(‘Closed notification: ‘ + primaryKey);<br>});</pre><pre>self.addEventListener(‘notificationclick’, function(e) {<br>  var notification = e.notification;<br>  var data = notification.data || {};<br>  var primaryKey = data.primaryKey;<br>  var action = e.action;</pre><pre>  console.debug(‘Clicked notification: ‘ + primaryKey);<br>  if (action === ‘close’) {<br>    console.debug(‘Notification clicked and closed’, primaryKey);<br>    notification.close();<br>  } <br>  else {<br>    console.debug(‘Notification actioned’, primaryKey);<br>    clients.openWindow(&#39;/&#39;);<br>    notification.close();<br>  }<br>});</pre><h4>Step 3: Add it to the CRA build process</h4><p>The sw-precache plugin allows for a set of options to customize the service worker. The one that we will use is the importScripts option, which accepts an array of scripts which will be linked in the generated service worker.</p><p>To make this change, find the related config in webpack.config.prod.js file in the config folder. There in the SWPrecacheWebpackPlugin options, add the option, linking to wherever your file resides.</p><pre>importScripts: [publicUrl + ‘/custom-service-worker.js’]</pre><p>However, this presents a problem: Our service worker cannot be debugged in a dev environment. The sw-precache plugin is only used in production (understandably, because caching could present problems during development)</p><p>In order to have only our custom service worker run in development, we have to make a few changes to registerServiceWorker.js</p><p>In the default register function, we change the</p><pre>if (process.env.NODE_ENV === ‘production’ &amp;&amp; ‘serviceWorker’ in navigator) {<br> return new Promise((resolve, reject) =&gt; {<br> window.addEventListener(‘load’, () =&gt; {<br> const swUrl = ‘/service-worker.js’;<br> // Rest of the code follows</pre><p>to</p><pre>if (‘serviceWorker’ in navigator) {<br>  return new Promise((resolve, reject) =&gt; {<br>  window.addEventListener(‘load’, () =&gt; {<br>  const swUrl = process.env.NODE_ENV === ‘production’? ‘/service-worker.js’: ‘/custom-service-worker.js’;<br>     // Rest of the code follows</pre><p>This makes sure our service worker is loaded in dev mode as well</p><h4>Step 4: Implement the push functionality</h4><p>The actual push functionality is a little too large to fit into this tutorial. Continuing with <a href="https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications#push_api">this link</a> should help with its implementation. Just remember any code related to the service worker should go to custom-service-worker.js</p><h3>Drawbacks</h3><p>This approach does have a few major drawbacks-</p><ul><li>Any updates to custom-service-worker.js does not cause a new build of service-worker.js. This is because none of the hashes in the generated file change and the importScripts are not appended to the file directly(they are only linked). So the content hash of `service-worker.js` remains the same, so the browser does not update its service worker</li><li>custom-service-worker.js is not part of the build process, so none of the linting and transpiling goodness is available for it</li></ul><h3>Wrapping up</h3><p>Create React App holds sensible defaults for most new age apps, but some requirements for Progressive Web Apps require customizations. There is a ton more that can be done with Service Workers, and in a future blog post, I can cover how to get over the drawbacks that this process present.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf35cd25d870" width="1" height="1" alt=""><hr><p><a href="https://medium.com/founding-ithaka/implementing-push-notifications-with-create-react-app-bf35cd25d870">Implementing push notifications with Create React App</a> was originally published in <a href="https://medium.com/founding-ithaka">Founding Ithaka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code splitting with Create React App]]></title>
            <link>https://medium.com/founding-ithaka/code-splitting-with-create-react-app-10ea9541cb01?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/10ea9541cb01</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Fri, 06 Apr 2018 17:41:08 GMT</pubDate>
            <atom:updated>2018-04-06T17:41:08.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*odiEMb5ba8pLMjNkwJ2VJA.jpeg" /></figure><p>One of the main benefits of React, Componentization and Webpack is that content can be loaded on demand when required. However it can be hard to figure out when and how to split code into different chunks for loading.</p><p>In this tutorial we’ll look at one of the easiest ways to do it - <strong>by the pages in the app</strong>. Let’s take an example of an app with Redux to manage app state and React Router for page navigation and routing. Now in this case, before we load any components we need to initialize app state and the Redux Store. The reason being that we cannot render anything until we know what to render. And this is mostly defined by the app state stored in redux.</p><p>So we’d like to break down this redux logic into its own chunk and load it at the start. Then, based on the route the page is on, we can download the different components that are to be shown and render them. For this we’d like each component that is being rendered in the route to be in its own chunk</p><h3>Breaking redux into its own chunk</h3><p>This is actually very simple. By default CRA puts all code into a single main.js chunk. So this already contains our redux logic. The only issue is that it contains ALL our code. We’ll look into breaking the components into separate chunks in the next section.</p><p>For now one important thing to touch upon is that your index.js (entry file which renders the <strong>ReactDOM</strong>) should contain very few imports and dependencies. Make sure you only include and import the lodash and rxjs (for example) operators required. This goes a long way in bringing down our app size.</p><p>We will also look into loading our reducers asynchronously in the next tutorial. This is so only the most important reducers are loaded in the start, and we further cut down our size of main.js</p><h3>Breaking each page into its own chunk</h3><p>Webpack provides code splitting in a couple of different ways. Here we will at Dynamic Imports, which is an approach that ties well with React Router.</p><p>What we require for our chunks is so all dependencies in are included in the chunk for the component. The drawbacks of this approach is that dependencies could be loaded multiple times. So loads might be imported in our page, as well as main.js but the code for each import would be present in both bundles.</p><p>However at the moment, since we’re importing each lodash operator as required, we can ignore it for the time being. Dynamic importing is done in Webpack by</p><pre>import(/* webpackChunkName: “App” */ ‘./App.js’))<br>.then(() =&gt; {console.log(‘imported’);}<br>.catch((err) =&gt; {console.error(‘error during import’, err);}</pre><p>Instead of our usual import App from &#39;./App.js&#39;. This tells webpack to break all code referenced in app.js to be bundled into its own file. And this code will only be fetched when it is called.</p><p><strong>NOTE</strong>: The dynamic import syntax returns a promise instead of synchronously returning the component as it needs to fetch and load the component from the new file</p><h3><strong>Tying dynamic imports with React Router</strong></h3><p>Now you must wondering how this works in the context of React Router. The dynamic import returns a promise whereas our usual code for loading a component to a route is by passing the component (loaded synchronously) to the Route.Component prop.</p><p>Well, React Router does not provide direct support to pass a component via promises, so we’d have to do a few workarounds. Let’s break it down in steps to better explain it-</p><h4>Creating a wrapper component</h4><p>The Route component requires a component to render at all times, so we will be providing a wrapped component. This component will render a dummy DOM (a loading text) until the promise to fetch the new page resolves</p><pre>const asyncComponent = getComponent =&gt; {<br>  class AsyncComponent extends React.Component {<br>    static Component = null;<br>    state = { Component: AsyncComponent.Component };</pre><pre>    componentWillMount() {<br>      if (!this.state.Component) {<br>        getComponent().then(({ default: Component }) =&gt; {<br>          AsyncComponent.Component = Component;<br>          this.setState({ Component });<br>        });<br>      }<br>    }</pre><pre>    render() {<br>      const { Component } = this.state;<br>      if (Component) {<br>        return &lt;Component {...this.props} /&gt;;<br>      }<br>      return &lt;div&gt;Loading…&lt;/div&gt;;<br>    }<br>  };</pre><pre>  return &lt;AsyncComponent /&gt;<br>};</pre><h4>Connecting the Wrapper component to the Router</h4><p>The Route component accepts a render function which can return a component that is to be shown. We will use this to render the wrapper component.</p><pre>ReactDOM.render(<br> &lt;Provider store={Store}&gt;<br>  &lt;BrowserRouter&gt;<br>   &lt;div&gt;<br>    &lt;Route path=&quot;/&quot; render={(props) =&gt; asyncComponent(() =&gt; {<br>     return import(/* webpackChunkName: &quot;App&quot; */ &#39;./App.js&#39;)<br>    })}&gt;<br>   &lt;/div&gt;<br>  &lt;/BrowserRouter<br> &lt;/Provider&gt;, <br> document.getElementById(&#39;root&#39;)</pre><p>Here the asyncComponent function will return the wrapper component which will be shown. This wrapped component shows a loading div until the dynamic import is resolved.</p><h3>Building and testing it out</h3><p>Our app is now split successfully and once we run our build process, it should show the 2 different built files-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qlhTbYE5xY9F2B3InILehA.png" /><figcaption>The files created after running npm or yarn build</figcaption></figure><p>Also on viewing of the network tab, it shows the loading of main.js and app.js at different times. As our app has more pages, the functioning and loading times of this page would remain unaffected.</p><h3>Using a custom solution</h3><p><a href="https://github.com/jamiebuilds/react-loadable">React Loadable</a> is an out of the box solution for code splitting that does everything that is explained in the post and some additional features like Server Side Rendering. A small snippet for the same can be found in the <a href="https://reacttraining.com/react-router/web/guides/code-splitting">official docs</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10ea9541cb01" width="1" height="1" alt=""><hr><p><a href="https://medium.com/founding-ithaka/code-splitting-with-create-react-app-10ea9541cb01">Code splitting with Create React App</a> was originally published in <a href="https://medium.com/founding-ithaka">Founding Ithaka</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Dotfile Framework in Node.js]]></title>
            <link>https://vikramthyagarajan.medium.com/a-dotfile-framework-in-node-js-ef48532e9d4e?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef48532e9d4e</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[configuration-management]]></category>
            <category><![CDATA[dotfiles]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Thu, 21 Apr 2016 16:21:24 GMT</pubDate>
            <atom:updated>2016-04-21T16:21:24.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqJIxOiCAw6iIbMc9EOrrg.png" /></figure><h3>Introduction</h3><p>Configuration is a natural evolution of my development cycle. Initially I make software to fit a purpose, and slowly find ways to reuse it outside its sandbox. Invariably as the software evolves, it becomes configurable and extensible.</p><p>Dotfiles are a way to keep track of tweaks that you make to your application, to enhance your workflow and productivity. And if you’re like me, you’re looking to maintain these in a way that seems intuitive and simple. We should learn from a field that has solved this problem so well that it is almost second nature: Web Development</p><h3>The sane way to maintain configurations</h3><p>So how do I go about storing these? Should I just copy all of them and dump them in Version Control? Should I add in a file that contains all the commands I want to run? Should I break them up into multiple files? What about installation, should I manually do it outside the dotfiles repo? Where do I start?</p><p>In web development, the only sane way to deal with server configuration is to keep a logical separation between two components: the code that describes the server (usually in JSON files) and the code that runs the server. This is web development 101. So how do we use this theory to maintain our dotfiles?</p><h3>The drawbacks of current dotfile managers</h3><p>Bash is a good scripting language, but maintaining configurations with it is unintuitive and messy.</p><pre>ln -s ~/.vimrc ~/programs/dotfiles/vim/config </pre><p>is more complex to understand than</p><pre>{ <br>  “symlink”: {<br>    “source”: “~/.vimrc”,<br>    “target”: “~/programs/dotfiles/vim/config”<br>  }<br>} </pre><p>The closest dotfile tool that I came across that understands this is DotBot(<a href="https://github.com/anishathalye/dotbot">https://github.com/anishathalye/dotbot</a>). However, it fails in my other requirement -</p><h3>Dotfiles are not just about configuration</h3><p>A Dotfile is the state of an application. Your application went through an evolution. It was installed, initialized, run and tweaked (massively). In order to get to the current state of the application, all of these actions must be done. So your dotfiles should describe this state accurately.</p><p>I would like to think of them as a set of modules. And each module has a lifecycle. It installs, initializes and configures itself, which is what I call bootstrapping. This way I get fine grained control over modules, and can bootstrap a specific module instead of all at once. Also, if I have many modules and configs, I can choose which ones to bootstrap. Dependency management becomes a breeze.</p><h3>Implementation</h3><p>My dotfile framework treats applications as modules. Each module has a lifecycle associated with it, and describes the way it was installed, initialized and configured. All of this is stored in Version Control so that I can get my whole dev environment set up by just running one bootstrap script. The framework is written in Node as it has first class support for JSON, and makes it simple to manage lifecycle events, but can be written in any language. You can check out the code at <a href="https://github.com/vikramthyagarajan/dotfiles">https://github.com/vikramthyagarajan/dotfiles</a>, and fork it for maintaining your dotfile configuration</p><h3>Conventions</h3><p>The framework makes it easy to maintain your dotfiles without much configuration for basic use cases. As I’ve mentioned before, each application has its own folder. Within this folder, these conventions are followed if no config options are given (this means that you have not included a module.json file in the folder) -</p><ul><li>An install.sh file which has the code that runs the app installation</li><li>An initialize.sh file which has the initialization code and runs after install.sh</li><li>A config folder, whose contents will be symlinked to the $HOME directory</li><li>A configure.sh file which runs after the symlinking, and can be used to run code post symlinking</li></ul><p><strong>Note: None of these files are compulsory. You can include just the files you want based on your requirement</strong></p><h3>Configuration</h3><p>All configuration is maintained in the module.json file within each application folder. An example configuration is -</p><pre>{ <br>  &quot;install&quot;: &quot;sudo apt-get install vim&quot;, <br>  &quot;initialize&quot;: &quot;mv ~/.vimrc ~/backup&quot;, <br>  &quot;configure&quot;: &quot;configure.sh&quot;, <br>  &quot;config&quot;: { <br>    &quot;global&quot;: { <br>      &quot;path&quot;: &quot;$HOME/.config&quot;<br>     }, <br>     &quot;nvim&quot;: {<br>       &quot;path&quot;: &quot;$HOME/.config/vim&quot;<br>     } <br>  } <br>}</pre><p>The README has further explanations into each option and their options</p><h3>Usage</h3><p>After setting up your dotfiles in your required format, your dotfiles can be kept in Version Control. In order to run them, you can run these commands to set it up -</p><ul><li>bootstrap: Will set up the whole application, including install, init and configure it</li><li>configure: Will only symlink your config folders and run the configure script</li></ul><pre>npm start bootstrap //will bootstrap all modules <br>npm start bootstrap vim //will bootstrap the vim module <br>npm start configure //will configure all modules <br>npm start configure vim //will configure the vim module</pre><h3>The Way Ahead</h3><p>At the moment, this framework seems to satisfy my requirements in a dotfile management system. However, on the roadmap I do intend to make it easier to use by making a tool that can automate the hardest part — the starting configuration. The tool would take all your required files, move them to the config folder, symlink them and take all the commands you require in one go. Still thinking about this though, would love your comments on whether this would be helpful to start your dotfile management process</p><p>Do let me know what you think about the framework. And of course, issues and pull requests are more than welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef48532e9d4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Beginner’s Journey into Improv]]></title>
            <link>https://vikramthyagarajan.medium.com/a-beginner-s-journey-into-improv-c6964f09a60c?source=rss-9b55f7bd8406------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6964f09a60c</guid>
            <category><![CDATA[comedy]]></category>
            <category><![CDATA[journey]]></category>
            <category><![CDATA[improv]]></category>
            <dc:creator><![CDATA[Vikram Thyagarajan]]></dc:creator>
            <pubDate>Fri, 08 Apr 2016 15:23:21 GMT</pubDate>
            <atom:updated>2016-04-08T15:23:21.457Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1R_ZFKzdE9g7eGt6Sv9jw.png" /><figcaption>Image taken from <a href="https://www.flickr.com/photos/batmoo/3735638680">https://www.flickr.com/photos/batmoo/3735638680</a></figcaption></figure><p>I recently joined a Level 1 Workshop on Improv. I‘ve completed 8 sessions, and have a showcase coming up soon. Suffice it to say that I’m incredibly nervous and excited; which is probably the best mixture of emotions.</p><p>I just thought I’d share how my journey’s been thus far, in case others are looking to learn about Level 1 and what it’s like.</p><h3>Why Improv</h3><p>I have always wanted to try out Improv, for many reasons-</p><ul><li>I am a huge comedy nerd and I love SNL. Most if not all of the comedic greats spoke very highly of Improv and how it shaped their career and their life.</li><li>Improvisation has always been fun for me. It’s the reason I compose new music when I sit with my guitar; I never liked learning songs just for the sake of performance.</li><li>My comedy style has always tended towards Improv. I am terrible at jokes; I tend to forget stories easily and I always muck up the delivery. But I’ve always felt I’ve been my funniest on the spot; when there’s context around and I can find the funny in it. So Improv helps me find my sense of comedy, understand it, and nurture it.</li></ul><p>These reasons coupled with the fact that I wanted to try something new clinched the deal. I was gonna learn Improv one way or another.</p><h3>Challenges</h3><p>It was difficult for me to understand Improv at first. Mostly because there’s not as much to learn, as there is to unlearn. We all arrive with a lot of social conditioning that has been inflicted on us as part of everyday life. And letting go of these rules is hard. But let go you must.</p><h4>1) <strong>There is no I in Improv</strong></h4><p>Yeah, you read that right. In order to be a good improviser, you must forget yourself. You must shed your Ego and your desires. You must start thinking of yourself as the scene, the characters, the relationships.</p><p>This concept was very hard to wrap my head around. I wanted so much to be funny and get laughs on the spot. So I stopped paying attention to the scene and started thinking of how I could make the scene funny and win laughs. And invariably, since the control was out of my hands, I used to bomb. This is what they call in Improv “not listening”.</p><p>I knew it as it was happening, but I wasn’t able to help it. I simply wasn’t able to think of the scene without thinking of myself and how I could make it funny. I had to keep reminding myself to let it go every time I consciously realized I was doing it.</p><h4>2) You must learn to handle the pressure</h4><p>The pressure is omnipresent in Improv. You will feel pressure when you have to</p><ul><li>Come up with something on the spot</li><li>React in moments while multiple improvisers depend on you</li><li>Step out of your comfort zone</li><li>Remember many patterns — Names, Relationships, Objectives, Environments</li><li>Listen</li><li>Perform on stage</li><li>Be funny (an internal pressure for beginner students who haven’t managed to let go of their Ego)</li></ul><p>This is probably the hardest of all the challenges and one that I’m always working toward getting over. I am still figuring it out, but experience and practice helps in understanding how to overcome it. However, the one thing that seems most important in handling the pressure is Team Work.</p><h4>3) Team work is everything</h4><p>This is probably the most fundamental concept in Improv. Without a team, you cannot do Improv. This ties in to the first point about there being no self. Once you get this right, pressure becomes simple to handle, because when you work as a team, the pressure gets shared among its individuals. And in order to work with a group, you must learn to communicate.</p><h4>4) Communication takes many forms</h4><p>Communication is two way. In order for something to be communicated effectively, both the speaker and the listener must work together. You cannot just say something and walk away. You must make sure the message is conveyed and understood. So listening is very important in Improv, and in life.</p><p>However, the thing that baffled me the is the sheer number of forms of communication. When you’re listening properly, you understand so much about another person. You understand when he’s in discomfort, when he’s uneasy, when he’s excited and rearing to go. When you learn to effectively communicate, you can wing it in every situation with the other person.</p><p>You can know when your teammate is struggling and help him. He will know when you’re struggling and take over. You can understand where you should let him lead, and where you should take the lead.</p><blockquote>With communication, you can “harmonize” effectively.</blockquote><p>The details of each type of communication and their uses is pretty vast. Maybe I’ll include them in a different article.</p><h4>5) The only time that matters is now</h4><p>There are many things going on in an Improv scene. Your date is acting like a fish. You are in a restaurant where every waiter is a penguin, trying to low-key eat her.</p><p>In order to be able to react to all that’s happening around you, you must have razor sharp focus. I think the only way to understand and incorporate this is by conditioning yourself to it. Which means experiencing and doing a lot of Improv.</p><h3>Conclusion</h3><p>I think my journey with Improv will be a life long one. I will be detailing the process. So do subscribe and stay tuned for more of the same. I highly recommend Improv to everyone. Go to your nearest comedy theatre, or find a troupe in your city; they will have workshops you can attend. Keep learning and improvising.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6964f09a60c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>