<?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 Konstantine Kutalia on Medium]]></title>
        <description><![CDATA[Stories by Konstantine Kutalia on Medium]]></description>
        <link>https://medium.com/@kutalia?source=rss-70394d2b289d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dHwcMtl766dEh3m2myrBFQ.png</url>
            <title>Stories by Konstantine Kutalia on Medium</title>
            <link>https://medium.com/@kutalia?source=rss-70394d2b289d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:24:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kutalia/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[You don’t know “useEffect”]]></title>
            <link>https://kutalia.medium.com/you-dont-know-useeffect-3cd9d741f33d?source=rss-70394d2b289d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3cd9d741f33d</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[browser-paint]]></category>
            <category><![CDATA[useeffect]]></category>
            <category><![CDATA[react-lifecycle]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Konstantine Kutalia]]></dc:creator>
            <pubDate>Thu, 28 Dec 2023 18:31:36 GMT</pubDate>
            <atom:updated>2023-12-28T18:37:11.690Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/225/0*MrS3sShjfGFvv8Wu" /><figcaption>Every React JS developer’s dream</figcaption></figure><p>There have been circulating many misconceptions about React JS hooks, particularly <strong>useEffect</strong>. Part of the problem is <a href="https://reactjs.org/docs">official React docs</a> (now deprecated) which in many cases oversimplified matters to the point you asked yourself: “Why on earth React team doesn’t tell us <strong>how React actually works?!</strong>”. This caused massive confusion in the community, especially in junior/middle developers segment. When I conducted interviews for a company I could witness candidates over and over again not having a solid grasp on basic React component lifecycle concepts. Thanks gosh React team addressed the issue by releasing <a href="https://react.dev/">new docs</a>. I started creating this post while the docs were still missing a lot, now I’ll try to make the topic even more accessible to save your time reading dozens of unfullfilling docs pages and contradictory StackOverflow answers. Let’s start:</p><h3>useEffect is not same as (componentDidMount + componentWillUnmount + componentDidUpdate)</h3><p>Yes, we’ve been lied. It’s a simple association, yet untrue on so many levels.</p><p>To understand differences between class component lifecycle methods and functional component hooks one must know the meaning and sequence of events in React JS and browsers like <strong>DOM mutation, paint</strong>, <strong>element render</strong>, <strong>re-render</strong>, <strong>mount</strong>, <strong>unmount</strong>, <strong>clean-up</strong> and etc.</p><h4>Etimology 🤓📖</h4><p>While there is an official <a href="https://developer.mozilla.org/en-US/docs/Web/Performance/How_browsers_work">MDN</a> and <a href="https://react.dev/learn/render-and-commit">React</a> “glossary” for controversial phrases, many people still confuse terms like <em>DOM paint</em> with <em>element render</em>. I will try to interpret them simply, yet accurately:</p><ol><li><strong>Render </strong>— if we want to differentiate <em>render</em> and <em>paint </em>then the term can be used to describe calculation process made by React JS in your memory which doesn’t result in any visualization just yet. It only prepares your element for painting by running code from your components, filtering what to show and whatnots using React’s <em>reconcillation algorithm </em>which is another fancy name for diffing browser’s DOM and virtual DOM.</li><li><strong>Mount </strong>— on this stage your components in a <em>virtual DOM </em>are actualized and inserted into a <em>real</em> <em>DOM </em>tree <em>for the first time</em> (which still takes time for browser engines to <em>paint </em>using native system calls like hardware acceleration, loading remote CSS assets, calculating styles and etc.). Future re-renders might cause certain <em>children</em> of a component to <em>unmount</em>, <em>mount</em> or <em>update</em>.</li><li><strong>Paint</strong> — the final stage of the <em>browser rendering process</em> resulting in the actual visualization of your elements. For some people mounting is analogous to painting for the first time, although as defined above and as we will see it later, from a pure technological viewpoint <em>componentDidMount is fired before the actual first paint</em>. By contrast, although it usually does, in specific scenarios <em>useEffect code is not even guaranteed to only fire after paint </em>(more on that later).</li><li><strong>Re-render </strong>— sometimes called <strong>update</strong>. Usually caused by <em>state</em> or <em>props </em>change, but can also be triggered by subscribing to the <strong>context</strong> API. Also can be bypassed by <strong>memo</strong>ization. As the name implies, it causes the element to render again.</li><li><strong>Unmount</strong> — The antipode of mounting. the process of removing nodes rendered by your component from the DOM tree.</li></ol><p>Here’s the proof that useEffect clean up runs after componentWillUnmount (see the console):</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Fgallant-bush-9gciig&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fu43ntk&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F9gciig%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ac3e5c0f0ea6eaf9170a35af984502b/href">https://medium.com/media/2ac3e5c0f0ea6eaf9170a35af984502b/href</a></iframe><p>The simple explanation is that useEffect cleanup does not “live” in the same place as it’s React class sibling method.</p><p>Confusing, right?</p><p>Here’s a readable infographic showing what’s actually going on with the hook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DaHetXJod8CR8rSzJp9o5w.png" /><figcaption>Simplified React component lifecycle and involving useEffect hook</figcaption></figure><p>As it looks like, both useEffect and useLayoutEffect cleanup functions always run before the next effect is executed (from the same hook).</p><p>It’s a different game when running actual effects:</p><p>useEffect is deferred, not blocking the “browser painting thread” (given that most browser engines handle the process with a single thread). Thus, if you update/read DOM inside useEffect, you might get caught in a process of a browser painting content from the latest React component render, resulting in a flicker/incorrect read respectively.</p><p>This is where useLayoutEffect comes in, which simply blocks the thread and executes before a browser has any chance to paint. If you mutate DOM there, browser engine will give priority to your values over the scheduled DOM mutations from the last render (<em>segment 3 on the photo</em>).</p><p>As of the <em>useEffect not being guaranteed to only fire after paint,</em> here’s the corner case:</p><pre>import React, { useEffect, useRef } from &#39;react&#39;;<br><br>function ExampleComponent() {<br>  const containerRef = useRef(null);<br><br>  useEffect(() =&gt; {<br>    const prePaintTask = () =&gt; {<br>      // Execute some code before the browser paints the DOM<br>      performPrePaintTask();<br><br>      // Once the pre-paint task is complete, you can force an immediate re-render<br>      // to ensure that the updated UI is painted without any delay<br>      // Use requestAnimationFrame to schedule the re-render<br>      window.requestAnimationFrame(() =&gt; {<br>        // Update state or trigger other UI-related actions<br>      });<br>    };<br><br>    // Schedule the pre-paint task using requestAnimationFrame<br>    window.requestAnimationFrame(prePaintTask);<br>  }, []);<br><br>  return (<br>    &lt;div ref={containerRef}&gt;<br>      {/* Render your component&#39;s UI */}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ExampleComponent;</pre><p>This happens because according to <a href="https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame">MND </a><strong>window.requestAnimationFrame()</strong><em> requests the browser to call a user-supplied callback function before the next repaint.</em></p><p>Hope this article gave you a clearer view of the React hooks, the component lifecycle and the browser painting mechanism.</p><p>While some of the techniques discussed here are more advanced, I recommend following general React guidelines and <a href="https://www.patterns.dev/">proven programming patterns</a>. From my experience, oftentimes you don’t really benefit from the amount of control React gives with it’s API. And if your project desperately needs it, you might be doing something wrong.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3cd9d741f33d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the hell is “this” in JavaScript?]]></title>
            <link>https://kutalia.medium.com/what-the-hell-is-this-in-javascript-35bd428f8293?source=rss-70394d2b289d------2</link>
            <guid isPermaLink="false">https://medium.com/p/35bd428f8293</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[objectorientedprogramming]]></category>
            <dc:creator><![CDATA[Konstantine Kutalia]]></dc:creator>
            <pubDate>Wed, 09 Nov 2022 18:16:20 GMT</pubDate>
            <atom:updated>2022-11-09T18:17:55.608Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*Q1u6NXmX-H-HWURouR4FRg.png" /><figcaption>The other Jackie Chan meme</figcaption></figure><p><strong>this</strong> is Javascript‘s one of the most confusing concepts.</p><p>From my experience, the confusion mostly comes from the assotiation of <em>this </em>to <em>classes</em>.</p><p>In fact, classes and <em>this</em> work fundamentally different compared to the so-called object-oriented languages such as Java, C++, C#, etc.</p><p>Javascript-ში this განისაზღვრება რამდენიმე ფაქტორის მიხედვით: ვიძახებთ თუ არა ფუნქციაში, რა ტიპის ფუნქციაში, რა კონტექსტში (scope), რომელ გარემოში და ა.შ.</p><p>In Javascript, <em>this</em> is defined according to several factors: whether we call it in a function, in what type of function, in what context (scope), in which environment, etc.</p><p>Let’s consider the usual functions created with the <strong>function</strong> keyword. By remembering the<strong> following 4 rules</strong>, we will always be able to easily find the value of <em>this</em>:</p><ol><li>If the function is called using the <strong>new</strong> keyword, then a new location is allocated in memory, the specified function is called, in which <em>this </em>points to this new block of memory;</li><li>If the function is invoked via <strong>call</strong>, <strong>apply</strong>, or <strong>bind </strong>(the latter still relies on <em>apply</em>), then <em>this </em>is determined by the corresponding argument passed to these helper functions;</li><li>If the function is called on an <strong>object </strong>(as a method, ie <em>obj.foo</em> style), then <em>this</em> points to this object;</li><li>If <strong>none of the above</strong> conditions are met, then the value of <em>this</em> will be a <strong>global object</strong> (in strict mode — <em>undefined</em>).</li></ol><p>It should be noted that the given rules are listed <strong>hierarchically</strong>, that is, when several rules are used concurrently, priority will be given to the top rule.</p><p>For example, if the call the so-called <strong>hardbound </strong>function (derived by <em>bind</em>) with <em>new</em>, <em>this </em>will still target a new object.</p><pre>let testObj = {<br>    foo: &#39;this is a test object&#39;,<br>};</pre><pre>function test() {<br>    return this;<br>}</pre><pre>console.log( new ( test.bind( testObj ) ) );</pre><p>For ease of understanding, some falsely draw a parallel between <strong>arrow functions</strong> and <em>hardbound functions</em>.</p><p>An <em>arrow function</em> is not a <em>hardbound function</em>. That is, <em>this</em> is not determined by a dynamically attached at runtime, as in the case of <em>bind</em>, but according to the <strong>lexical scope </strong>of the arrow function.</p><p>So, <em>this</em> in an object indicates this object itself, in global scope — <strong>window</strong>, or in strict mode <em>undefined</em>, etc.</p><p>By the way, the principles of <em>strict mode</em> work in the body of the <strong>Class</strong>, so directly calling the function declared in the class method (according to the 4th condition) also renders <em>this </em>as <em>undefined</em>.</p><p>Consider the following case:</p><p>We will write attach <em>handleClick </em>function to any DOM element as an <em>onClick </em>event handler:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2FKutalia%2Fozrhj8v2%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2FKutalia%2Fozrhj8v2%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2Fb75fb9b7b3ab5134a7022e5cf94ca3f8%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2bdc8329c3ecde4ebc9fa4986388407/href">https://medium.com/media/d2bdc8329c3ecde4ebc9fa4986388407/href</a></iframe><p>Pseudo code of the internals of a browser engine:</p><pre>el.onclick = handleClick;<br>el.onclick(); // &lt;===== &#39;this&#39; will reference to &#39;el&#39;</pre><p>In this case, the value of <em>this </em>refers to this DOM element itself, since it appears that the browser engine called the event handler via the element.</p><p>If the browser remembered this function somewhere as a new variable and called it like that, then when accessing <em>this</em>, the <em>window </em>object would be returned to us:</p><pre>var eventHandler = el.onclick;<br>eventHandler; &lt;===== &#39;this&#39; refers to &#39;window&#39;</pre><p>As a bonus, you can see an example of React JS events:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2Freact-playground-forked-guio18%3Fexpanddevtools%3D1%26fontsize%3D14%26hidenavigation%3D1%26theme%3Ddark&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2Fguio18&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2Fguio18%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8ba94e56a6001160bdf40846aaadb7a/href">https://medium.com/media/b8ba94e56a6001160bdf40846aaadb7a/href</a></iframe><p>I hope my blog has clarified how <em>this </em>works. Then you’ll be less likely in need to overuse <em>arrow functions</em> to insure yourself. A JavaScript <strong>function </strong>is a powerful weapon in the hands of a knowledgeable person.</p><p>For a more in-depth look at the topic, I’d recommend Kyle Simpson’s video course Deep JavaScript Foundations, v3.</p><p>In the comments, you can write the topics that you would like to see analyzed by me.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35bd428f8293" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[რა ჯანდაბა არის this ჯავასკრიპტში?]]></title>
            <link>https://kutalia.medium.com/%E1%83%A0%E1%83%90-%E1%83%AF%E1%83%90%E1%83%9C%E1%83%93%E1%83%90%E1%83%91%E1%83%90-%E1%83%90%E1%83%A0%E1%83%98%E1%83%A1-this-%E1%83%AF%E1%83%90%E1%83%95%E1%83%90%E1%83%A1%E1%83%99%E1%83%A0%E1%83%98%E1%83%9E%E1%83%A2%E1%83%A8%E1%83%98-913e6c296cd?source=rss-70394d2b289d------2</link>
            <guid isPermaLink="false">https://medium.com/p/913e6c296cd</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[object-oriented-program]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Konstantine Kutalia]]></dc:creator>
            <pubDate>Tue, 08 Nov 2022 17:53:19 GMT</pubDate>
            <atom:updated>2022-11-09T18:06:09.004Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*Q1u6NXmX-H-HWURouR4FRg.png" /><figcaption>ის არა და მეორე ჯეკი ჩანის მიმი</figcaption></figure><p><strong>this</strong> არის Javascript-ის ერთ-ერთი ყველაზე გაუგებარი კონცეფცია.</p><p>ჩემი გამოცდილებით, ეს ბუნდოვანება ძირითადად გამომდინარეობს this-ის კლასებთან ინტუიციურ კავშირთან.</p><p>სინამდვილეში, კლასები და this-იც ფუნდამენტურად განსხვავებულად მუშაობს ისეთ ე.წ. ობიექტზე ორიენტირებულ ენებთან შედარებით, როგორებიცაა: Java, C++, C# და ა.შ.</p><p>Javascript-ში this განისაზღვრება რამდენიმე ფაქტორის მიხედვით: ვიძახებთ თუ არა ფუნქციაში, რა ტიპის ფუნქციაში, რა კონტექსტში (scope), რომელ გარემოში და ა.შ.</p><p>განვიხილოთ ჩვეულებრივი, function keyword-ით შექმნილი ფუნქციები. <strong>შემდეგი 4 წესის </strong>დამახსოვრებით მარტივად შეგვეძლება this-ის მნიშვნელობის მიგნება:</p><ol><li>თუ ფუნქცია გამოიძახება <strong>new</strong>-ის გამოყენებით, მაშინ მეხსიერებაში გამოიყოფა ახალი ადგილი, გამოიძახება მითითებული ფუნქცია, რომელშიც this მიუთითებს ამ ახალ მეხსიერების ბლოკს;</li><li>თუ ფუნქცია გამოიძახება <strong>call</strong>, <strong>apply </strong>ან <strong>bind</strong>-ის (ეს უკანასკნელი apply-ის ეყრდნობა) საშუალებით, მაშინ this განისაზღვრება ამ დამხმარე ფუნქციებში გადაცემული შესაბამის არგუმენტის მიხედვით;</li><li>თუ ფუნქცია გამოიძახება რაიმე <strong>ობიექტზე </strong>(მეთოდად, ანუ <em>obj.foo</em> სტილში), მაშინ this მიუთითებს ამ ობიექტს;</li><li><strong>თუ არც ერთი</strong> ზემოთ ჩამოთვლილი პირობა არ შესრულდა, მაშინ this-ის მნიშვნელობა იქნება <strong>გლობალური ობიექტი</strong> (მკაცრ რეჟიმში — undefined).</li></ol><p>აღსანიშნავია, რომ ჩამოთვლილი წესები <strong>იერარქიულადაა</strong> ჩამოთვლილი, ანუ რამდენიმე წესის თანხვედრით გამოყენებისას უპირატესობა მიენიჭება ზედა წესს.</p><p>მაგალითად, თუ ე.წ. hardbound ფუნქციას (bind-ით გამოყვანილ) new-ით გამოვიძახებთ, this მაინც ახალ ობიექტს დაუმიზნებს.</p><pre>let testObj = {</pre><pre>    foo: &#39;this is a test object&#39;,<br>};</pre><pre>function test() {</pre><pre>    return this;</pre><pre>}</pre><pre>console.log( new ( test.bind( testObj ) ) );</pre><p>მარტივად გაგების მიზნით ზოგიერთი არასწორ პარალელს ავლებს ისრიან ფუნქციებსა და hardbound ფუნქციებს შორის.</p><p>ისრიანი ფუნქცია არაა hardbound ფუნქცია. ანუ მისი this არ განისაზღვრება runtime-ში დინამიური გამოძახებით ისე, როგორც bind-ის შემთხვევაში, არამედ ლექსიკური არეალის (lexical scope) მიხედვით.</p><p>ანუ, this ობიექტში მიუთითებს თავად ამ ობიექტს, გლობალურ scope-ში — window-ს, ან strict mode-ში undefined და ა.შ.</p><p>სხვათა შორის, Class-ის ტანში strict mode-ის პრინციპები მუშაობს, ამიტომ კლასის მეთოდში გამოცხადებული ფუნქციის პირდაპირ (მე-4 პირობის მიხედვით) გამოძახებაც this-ს undefined-ით განსაზღვრავს.</p><p>განვიხილოთ შემდეგი შემთხვევა:</p><p>რაიმე DOM ელემენტს onClick event handler-ად გავუწერთ რაღაც handleClick ფუნქციას:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2FKutalia%2Fozrhj8v2%2Fembedded%2F&amp;display_name=jsFiddle&amp;url=https%3A%2F%2Fjsfiddle.net%2FKutalia%2Fozrhj8v2%2F2%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2Fb75fb9b7b3ab5134a7022e5cf94ca3f8%3Fs%3D80&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f6d4d599e7e766af088f069beea5200/href">https://medium.com/media/7f6d4d599e7e766af088f069beea5200/href</a></iframe><p>ბრაუზერის ძრავის მუშაობის ფსევდო კოდი:</p><pre>el.onclick = handleClick;</pre><pre>el.onclick(); // &lt;===== ‘this’-ის მნიშვნელობა განისაზღვრება ‘el’-ით</pre><p>ამ შემთხვევაში this-ის მნიშვნელობა მიუთითებს თავად ამ DOM-ის ელემენტს, ვინაიდან, როგორც ჩანს, ბრაუზერის ძრავამ ამ ელემენტის გავლით გამოიძახა.</p><p>ბრაუზერს რომ ეს ფუნქცია სადმე ახალ ცვლადად დაემახსოვრებინა და ისე გამოეძახა, მაშინ this-ზე წვდომისას window ობიექტი დაგვიბრუნდებოდა:</p><pre>var eventHandler = el.onclick;</pre><pre>eventHandler; &lt;===== ‘this’ მიუთითებდა ‘window’-ს</pre><p>ბონუსად შეგიძლიათ იხილოთ React JS-ის event-ების მაგალითი:</p><p><a href="https://codesandbox.io/embed/react-playground-forked-guio18?expanddevtools=1&amp;fontsize=14&amp;hidenavigation=1&amp;theme=dark">React PlayGround (forked)</a></p><p>იმედი მაქვს, ამ პოსტმა ნათელყო this-ის მუშაობის მექანიზმი. ამის შემდეგ თქვენ ნაკლებად დაგჭირდებათ თავის დასაზღვევად ისრიანი ფუნქციების ზედმეტად ხმარება. ჯავასკრიპტის ფუნქცია (function) მცოდნე ადამიანის ხელში ძლიერი იარაღია.</p><p>საკითხის კიდევ უფრო სიღრმისეულად შესასწავლად გირჩევდით Kyle Simpson-ის ვიდეოკურსებს Deep JavaScript Foundations, v3.</p><p>კომენტარებში შეგიძლიათ დაწეროთ ის თემები, რომელთა გარჩევასაც ისურვებდით.</p><p>გისურვებთ წარმატებებს, happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=913e6c296cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I ported native guitar plugins to JavaScript (in-depth)]]></title>
            <link>https://kutalia.medium.com/how-i-ported-native-musical-plugins-to-javascript-in-depth-dafa014dae01?source=rss-70394d2b289d------2</link>
            <guid isPermaLink="false">https://medium.com/p/dafa014dae01</guid>
            <category><![CDATA[webassembly]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[guitar]]></category>
            <dc:creator><![CDATA[Konstantine Kutalia]]></dc:creator>
            <pubDate>Wed, 01 Sep 2021 19:17:29 GMT</pubDate>
            <atom:updated>2021-09-05T12:39:03.247Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ZW8hgYKBU7PLoL6M" /><figcaption>Photo by <a href="https://unsplash.com/@litangen?utm_source=medium&amp;utm_medium=referral">Thomas Litangen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>TL;DR</h3><p>I converted native (Windows/Linux/Mac) guitar VST plugins into web browser using React JS and WebAssembly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FZjMleBB3N0U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DZjMleBB3N0U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FZjMleBB3N0U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b00d412179743b67efca6c41e9985547/href">https://medium.com/media/b00d412179743b67efca6c41e9985547/href</a></iframe><p>Here’s the full story:</p><h3>Introduction</h3><p>Electric guitar is one of the most popular instrument. You have heard it on countless pop, jazz and rock records. Those iconic sounds are generated by electric devices known as amplifiers. First generations of guitar amplifiers used vacuum tubes to amplify signals. They were heavy, expensive and fragile. In 1970s when solid state technology became widespread transistor-based guitar amplifiers were popularized, yet many players would still prefer “vacuum tube sounds” as they sound warmer and fuller. At the end of 1990s Line 6 POD digital guitar effects processor revolutionized guitar gear market. It gathered a huge fanbase due to its versatility, low cost and lack of maintenance. During 2000s many iterations of digital simulations appeared on various platforms, both as personal computer apps and standalone machines using dedicated DSP (Digital Signal Processing) processors. Just few years ago first web browser-driven amplifier simulations appeared which used Web Audio API. Those were attempts to make electric guitar playing through a computer a bit easier since native applications require setup and are platform-dependent. Since then not much has been done building upon this idea whereas Web Audio API itself has been vastly improved.</p><h3>The mission</h3><p>So the basic idea was to bring native applications experience to browser environment with unquestionable audio quality and performance. That means you would not have to choose specific installer for your platform (x64/x86, Windows/Mac and etc.), install it potentially with other mandatory applications like DAW (Digital Audio Workspace) — not all digital guitar products come as standalone versions, you might need to install them as plugins and run via DAWs. All that manual work is replaced by typing URL of your favorite guitar plugins host website. Downloading all assets and compiling could just take few seconds and you are ready to rock.</p><figure><img alt="Overloud TH-U — popular native standalone application. One of my inspirations for GUI." src="https://cdn-images-1.medium.com/max/1024/0*VCnRlQMRLdz8kO4g.jpeg" /><figcaption>Overloud TH-U — popular native standalone application. One of my inspirations for GUI.</figcaption></figure><h3>Tools</h3><p>DSP algorithms for native apps are usually written in languages like C/C++ or DSLs (domain specific languages) like Feldspar, FAUST (Functional Audio Stream) and etc. A tool for compiling those languages to JavaScript has already been in use for quite some time — Emscripten. You can <a href="https://youtu.be/lDkjb4X6IUA?t=81">export entire games</a> to be compatible with browser utilizing the technology. At first Emscripten compiled to asm.js — a strictly typed JS subset. asm.js could be ran on modern browsers like Mozilla Firefox. As it’s popularity grew new technology came — WebAssembly (Wasm), which superseded asm.js. Wasm is not only a language, but according to WikiPedia:</p><blockquote>an <a href="https://en.wikipedia.org/wiki/Open_standard">open standard</a> that defines a <a href="https://en.wikipedia.org/wiki/Software_portability">portable</a> <a href="https://en.wikipedia.org/wiki/Binary_code">binary-code</a> format for <a href="https://en.wikipedia.org/wiki/Executable">executable programs</a>, and a corresponding textual <a href="https://en.wikipedia.org/wiki/Assembly_language">assembly language</a>, as well as interfaces for facilitating interactions between such programs and their host environment.</blockquote><p>Here’s a neat thing which might blow your mind: with Emscripten you can actually compile compilers to WebAssembly. <a href="https://www.npmjs.com/package/@grame/libfaust">This</a> Node JS package is a great example — libfaust includes FAUST language compiler as a WebAssembly module and appropriate JS wrapper functions to run them in browser, manage memory, type annotations are also included for TypeScript compatibility. So you can compile FAUST language code from .dsp files on demand. To be more technical, the compiled code is executed in <a href="https://developer.mozilla.org/en-US/docs/Web/API/AudioWorklet">AudioWorklet</a> worker thread <a href="https://www.w3.org/TR/webaudio/#control-thread-and-rendering-thread">which runs separately from the main thread</a> (aka the DOM renderer, paint thread). Therefore it helps avoiding UI blocking and other performance issues. As I just told you (shared) memory management is handled by the package. So all you have to do is call given functions. And even if this information is not enough, you can go ahead and read <a href="https://developers.google.com/web/updates/2018/06/audio-worklet-design-pattern">Google developer’s blog</a> about the topic.</p><figure><img alt="FAUST code descriptors generated by libfaust" src="https://cdn-images-1.medium.com/max/841/1*w-SeFmJLaNeYfZNdKeYZ-A.png" /><figcaption>FAUST code descriptors generated by libfaust</figcaption></figure><p>Not only that libfaust handles most crucial things, it also generates descriptors objects for all the virtual knobs and buttons described by special primitives in .dsp codes. For example: <em>tonestack_low = vslider(“bass”,0,-15,15,0.1); </em>The given code describes low frequencies slider labeled <em>“bass” </em>with minimum value of -15, maximum of 15 and default of 0, while 0.1 is a smallest step in a change of value. I used <a href="https://reactjs.org/">React library</a> by Facebook to create UI components from aforementioned descriptors. Control functions are also automatically generated and wrapped in the audio worklet processor class. Therefore you can directly connect components’ <em>onChange</em> events to these function calls.</p><h3>Challenges</h3><p>Most obvious question currently in your head should be: but how does it automatically convert whole native apps, is it some kind of magic? The answer is: it does not. Even though browser engine and the libfaust does some heavy lifting to virtualize native APIs to fit WebAssembly (remember, it’s also a virtual machine) environment, memory management and file system, there are few areas where manual coding solutions are needed: GUI (which we have already talked about) and additional C/C++ wrapper functions which also do DSP and load additional files, but are not compiled to asm.js by libfaust. Even though I could try to manually compile it using Emscripten and <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Audio_API/Using_AudioWorklet">add as a separate audio worklet processor module</a>, I thought it would be too much of a headache so I went and used my little C++ experience from university days to “translate” to JS. In case I haven’t told you I ported the free <a href="https://github.com/olegkapitonov/Kapitonov-Plugins-Pack">Kapitonov Plugins Pack</a> in JS which includes simulations of variety of iconic guitar pedal and amplifier sounds.</p><p>What the code in question does is that it:</p><p>1) <strong>Loads tube amplifier simulation profiles</strong>. I.e. you can have a clean guitar amp profile for playing blues and a high-gain profile for heavy metal music in separate files.</p><p>2) <strong>Does resampling to fit program’s properties to the user’s audio configurations</strong>. Resampling means changing audio data sample rate. If you have an .mp3 track with a sample rate of 96Khz it will be twice as accurate as the same track with a sample rate of 48Khz, which translates to broader frequency spectrum, better lows and highs.</p><p>You might ask: what’s to resample? We’ll get to that later.</p><p><em>kpp_tubeamp</em> plugin profiles are stored in <em>.tapf</em> files as a <strong>raw binary data</strong>. They consist of 3 types of information: <strong>metadata</strong>, <strong>parameters</strong> to use in the FAUST .dsp file as signal building blocks and <strong>impulse responses</strong>. These are all tweakable variables created with dedicated software to simulate different kinds of guitar amplifier while the main “schematic” is described in the .kpp_tubeamp.dsp file and is loosely based on real guitar tube amplifiers. According to the source code .tapf files are read using C++’s famous <a href="https://www.cplusplus.com/reference/cstdio/fread/"><strong>fread</strong></a> function, byte-by-byte. The profile structure is given in <em>profile.h</em> header file implying <em>float</em> and <em>int</em> properties are 4 byte datatypes each. There are multiple ways to download and parse files in JS, Fetch API being my favorite. It provides <strong>arrayBuffer</strong> method on a response to work with raw binary data. The one important part to mimic <em>fread</em> is partial reading of a fetched file by a given size in bytes and number of elements into buffers. Let’s say we have a 16-byte file called <em>JazzProfile.tapf</em> and we want to read 2 float numbers (4 bytes each). It would look something like that:</p><pre>struct profile {<br>    float f1;<br>    float f2;<br>// could be float bass_frequencies; int version_number and etc.<br>}</pre><pre>profile *prof;</pre><pre>FILE *profile_file = fopen(“JazzProfile.tapf”, “rb”);</pre><pre>fread(&amp;prof, sizeof(profile), 2, profile_file);</pre><p>It will load total of 8 bytes to the block of memory <em>&amp;prof </em>will be pointing at. From <em>&amp;prof</em> you could access 2 float numbers: <em>f1</em> and <em>f2</em>. After the operation <em>profile_file</em> input stream intrinsic pointer will shuffle by 8 bytes and will be pointing to the second half of the file. Here’s the JS version:</p><pre>fetch(“JazzProfile.tapf”).then(response =&gt;<br>    response.arrayBuffer()).then(buffer =&gt; {<br>        let bufferPosition = 0;<br>        const floatSize = 4;</pre><pre>const buff1 = buffer.slice(bufferPosition, floatSize);<br>        const f1 = new Float32Array(buff1)[0];</pre><pre>bufferPosition += floatSize;</pre><pre>const buff2 = buffer.slice(bufferPosition, floatSize);<br>        const f2 = new Float32Array(buff2)[0];<br>});</pre><p>Obviously we don’t manipulate pointers in JS, therefore I initialized <em>bufferPosition</em> variable and incremented it after every profile parameter reading by that property size (in our case — 4-byte float). The problem of exposing binary buffers as JS variable(s) is solved by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays">typed arrays</a>. Here we see <em>Float32Array </em>instantiated with <em>buff1. </em>It<em> </em>means a new array is created with 32-bit wide elements and filled with data from <em>buff1. </em>If you are still following you should’ve guessed that the returned array from the constructor will only have 1 element as buff1 is only 4 bytes long = 32 bits.</p><p>Another challenge I met is saturating the plugin itself with profile values. We’ve already digested general process of reading <strong>profile metadata</strong>, <strong>main parameters</strong> and <strong>impulse responses</strong> from <strong>.tapf</strong> files as array buffers. Metadata could help verifying profile validity and correct versioning. Profile parameters are given to Wasm processor module running compiled code form FAUST. Here’s one caveat: there’s a way to inject foreign parameters into FAUST code in native environment. Unfortunately the feature restricted when compiling for web, also I couldn’t find a way to initialize Wasm processor with initial arguments. I had to find the hack: in the original .dsp file I simply swapped the code telling the FAUST compiler to rely on foreign variables with primitive types describing sliders and numeric entries, as if they were set manually. It’s like connecting your heartbeat to a remote control:</p><pre>// original code, fvariable stands for foreign variable<br>tonestack_low = fvariable(float LOW_CTRL, &lt;math.h&gt;);</pre><pre>// optimized for web, vslider primitive abstracts vertical<br>// default, min and max values are there just to avoid errors<br>// useable value is set from JS after a fetching profile filetonestack_low = vslider(“bass”, 0, -10, 10, 0.0001);</pre><p>Ez, right?</p><p>The resampling comes to play with third profile part not yet discussed: impulse responses (IR). Impulse response is a way to shape signal by adding a layer of recorded track in a special manner <a href="https://www.youtube.com/watch?v=cGDXJFeh_8g">called convolution</a>. It can be used for room effects, reverb or speaker simulation. Think of it as an equalizer but in 3D. Guitar amplifiers are connected to guitar speakers. In order to faithfully replicate the whole sound we need to model guitar cabinet frequency response to a signal over time picked by specific microphones as top music producers record guitar tracks in their studios. All these factors: guitar cabinet material, speakers, room acoustics and microphone varieties are captured in a single impulse response file, usually in .wav format, as a very short audio track. The track needs to be in the same sample rate as the input signal. From a programmer’s perspective in JS it all comes down to array buffers fetched from .tapf profile file or from user uploaded .wav tracks.</p><p>After searching and testing numerous packages, I’ve discovered it could be easily done with <a href="https://www.npmjs.com/package/wave-resampler">wave-resampler</a>. You simply supply samples, input sample rate, output sample rate arguments and the function returns resampled data in a form of array-like object. <a href="https://developer.mozilla.org/en-US/docs/Web/API/ConvolverNode">ConvolverNode</a> takes care of wrapping impulse response as a separate node to be applied anywhere in the signal chain: at the beginning or right at the last bits of output. I put speaker simulation convolver node as the last node while preamp convolver loaded from profile file is applied just before main amplifier running compiled kpp_tubeamp.dsp script (hence the name pre-amp).</p><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MG5YF6T-fHNI-emqwG0FTg.png" /></figure><p>The result is (sonically) quite impressive. The only pitfall is noticeable input delay when running on Windows machine, although It’s better than in previous years. Browsers and Microsoft are to blame for not using optimized drivers. Mac system is much more faster responding in this regard. Same goes for Android vs iOS battle (yes, the website on smartphone sounds just like as in PC).</p><p>GUI is still imperfect and glitches are to expected here and there. You can choose an input device, custom speaker IRs, chain various plugins in desired order and so on.</p><p>I hope you enjoyed this guide.</p><p>You can visit the demo at: <a href="https://kutalia.github.io/react-webaudio-5150/">https://kutalia.github.io/react-webaudio-5150/</a></p><p>Source code is available at: <a href="https://github.com/Kutalia/react-webaudio-5150">https://github.com/Kutalia/react-webaudio-5150</a></p><p>For any questions or comments feel free to contact me at <a href="https://www.facebook.com/kote.kutalia/">Facebook</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dafa014dae01" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>