<?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 Yujie Wang on Medium]]></title>
        <description><![CDATA[Stories by Yujie Wang on Medium]]></description>
        <link>https://medium.com/@langyanger?source=rss-2902c8061ed9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CqOIC6P590F1HQeS</url>
            <title>Stories by Yujie Wang on Medium</title>
            <link>https://medium.com/@langyanger?source=rss-2902c8061ed9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:54:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@langyanger/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[Understanding how browsers work by creating one]]></title>
            <link>https://medium.com/jobpal-dev/understanding-how-browsers-work-by-creating-one-9aa63a32851e?source=rss-2902c8061ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/9aa63a32851e</guid>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[tutotial]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yujie Wang]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 08:21:57 GMT</pubDate>
            <atom:updated>2020-08-28T08:23:12.013Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VT0pTtO-BLCqwSay1DwjVw.png" /></figure><p>In this article, I will demonstrate how browsers work by creating a simple mini-browser. This toy example can show the basic rendering principles. After all, learning by doing is always effective, so let’s start the journey by building from scratch a browser that supports HTTP requests, HTML/CSS parsing, and flexbox layout. If you want to view the complete code, please refer to this <a href="https://github.com/BeijiYang/mini-browser">repository</a>.</p><h3>A browser’s basic work process</h3><p>To display a page, the browser takes the following steps:</p><ol><li>Requesting the page from the server using HTTP or HTTPS protocol</li><li>Parsing the HTML to build a DOM tree</li><li>Parsing the CSS to build a CSSOM tree</li><li>Combine the DOM and CSSOM into a render tree</li><li>Rendering the elements according to the CSS properties to get the bitmaps in memory</li><li>Compositing bitmap for better performance (optional)</li><li>Painting to display the content on the screen</li></ol><p>The contents can be displayed on the screen as soon as they are individually ready, because the rendering engine will not wait until all HTML is parsed before starting to build and layout the DOM tree. In this way, the contents can be displayed on the screen gradually as soon as possible.</p><p>In our mini-browser project, we follow the steps below to implement it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ja34YXnWUZF40kwNx5adA.png" /></figure><pre>.<br>├── client<br>│   ├── index.js  (step one)<br>│   ├── parser.js (step two and three)<br>│   ├── layout.js (step four)<br>│   ├── render.js (step five)<br>│   ├── package-lock.json<br>│   ├── package.json<br>│   └── viewport.jpg (the final result)<br>└── server<br>    ├── package-lock.json<br>    ├── package.json<br>    └── server.js</pre><h3>Step one: network request</h3><p>Let’s start with this basic directory structure:</p><pre>.<br>├── client<br>│ └── index.js<br>└── server<br> └── server.js</pre><h4>Set up a server</h4><p>First of all, let’s start a simple HTTP server which can send back a simple sentence “ Hello World\n”.</p><p>./server/server.js</p><pre>const http = require(&quot;http&quot;);</pre><pre>http.createServer((request, response) =&gt; {<br>  let body = [];</pre><pre>  request.on(&#39;error&#39;, error =&gt; {<br>    console.log(error);<br>  })<br>    .on(&#39;data&#39;, chunk =&gt; {<br>      body.push(chunk.toString());<br>      console.log(body)<br>    })<br>    .on(&#39;end&#39;, () =&gt; {<br>      body = body.join(&#39;&#39;);<br>      response.writeHead(200, { &#39;Content-Type&#39;: &#39;text/html&#39; });<br>      response.end(&#39; Hello World\n&#39;);<br>    });<br>}).listen(8080);</pre><pre>console.log(&#39;The server is running!&#39;);</pre><p>After installing the ‘http’ library and run the index.js file, the server is running.</p><pre>npm install http<br>node server.js</pre><p>I would recommend using the <a href="https://www.npmjs.com/package/nodemon">node monitor</a>, so you don’t have to restart the server by hand every time you change something.</p><p>nodemon server.js</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*56sBdbwXEAUGHCH6MG8bAA.png" /></figure><h4>Construct and send an HTTP request</h4><p>To send an HTTP request, we need to</p><ul><li>specify the host for IP</li><li>specify the port for TCP</li><li>specify the method, path, headers and body for HTTP</li></ul><p>We put them in an IIFE (Immediately Invoked Function Expression) like this:</p><p>./client/index.js</p><pre>void async function () {<br>  const request = new Request({<br>    host: &#39;127.0.0.1&#39;,<br>    port: 8080,<br>    method: &#39;POST&#39;,<br>    path: &#39;/&#39;,<br>    headers: {<br>      [&#39;X-Jobpal&#39;]: &#39;chatbots&#39;,<br>    },<br>    body: {<br>      name: &#39;Jobpal&#39;,<br>    }<br>  });</pre><pre>  const response = await request.send();<br>  console.log(response);<br>}()</pre><p>According to these requirements, we can implement the request class as follows.</p><p>./client/index.js</p><pre>const net = require(&#39;net&#39;);</pre><pre>class Request {<br>  constructor({<br>    method,<br>    host,<br>    port,<br>    path,<br>    headers,<br>    body<br>  }) {<br>    this.host = host;<br>    this.port = port || 80;<br>    this.method = method || &#39;GET&#39;;<br>    this.path = path || &#39;/&#39;;<br>    this.headers = headers || {};<br>    this.body = body || {};</pre><pre>    if (!this.headers[&#39;Content-Type&#39;]) {<br>      this.headers[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;;<br>    }<br>    // encode the http body.<br>    if (this.headers[&#39;Content-Type&#39;] === &#39;application/json&#39;) {<br>      this.bodyText = JSON.stringify(this.body);<br>    } else if (this.headers[&#39;Content-Type&#39;] === &#39;application/x-www-form-urlencoded&#39;) {<br>      this.bodyText = Object.keys(this.body).map(<br>        key =&gt; `${key}=${encodeURIComponent(this.body[key])}`<br>      ).join(&#39;&amp;&#39;);<br>    }</pre><pre>    this.headers[&quot;Content-Length&quot;] = this.bodyText.length;<br>  }<br></pre><pre>  // The parameter is a TCP connection.<br>  send(connection) {<br>    return new Promise((resolve, reject) =&gt; {<br>      if (connection) {<br>        connection.write(this.toString());<br>      } else {<br>        // create a TCP connection<br>        connection = net.createConnection(<br>          { host: this.host, port: this.port },<br>          () =&gt; connection.write(this.toString())<br>        );<br>      }</pre><pre>      connection.on(&#39;data&#39;, data =&gt; {<br>        console.log(data.toString());<br>        console.log(JSON.stringify(data.toString()));<br>      });</pre><pre>      connection.on(&#39;error&#39;, error =&gt; {<br>        console.log(error);<br>        reject(error);<br>        connection.end();<br>      })<br>    })<br>  }</pre><pre>  toString() {<br>    // the HTTP request<br>    return `${this.method} ${this.path} HTTP/1.1\r<br>${Object.keys(this.headers).map(key =&gt; `${key}: ${this.headers[key]}`).join(&#39;\r\n&#39;)}\r<br>\r<br>${this.bodyText}`;<br>  }<br>}</pre><p>In the construction function, we save the parameters and set the default values. When dealing with headers, pay attention to content-type. It is required; otherwise, the body can not be parsed correctly, because different formats require different parsing methods.</p><p>These are the four most used format:</p><ul><li>application/json</li><li>application/x-www-form-urlencoded (when submitting form)</li><li>multipart/form-data (when uploading files)</li><li>text/xml</li></ul><p>In the project, we set the default value as application/x-www-form-urlencoded. In this format, the submitted data will be encoded like key1=value1&amp;key2=value2.</p><p>In toString() method, the HTTP request is build. It is composed of a request line, request head, and request body.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*TswijNAbg8_Y50jwxVJ6pg.png" /></figure><p>Then, in the send() method, we send this request and print the response data when success.</p><p>Don’t forget to install the ‘net’ library, we need it to create a TCP connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*8s5fFeo_jMUt5BKSzxeMLg.png" /></figure><p>As we can see, the structure of response data conforms to the above figure.</p><p>Maybe you have noticed that the response body is different from what we sent on the server-side.</p><ul><li>what we sent: ‘ Hello World\n’</li><li>what we get: ‘d\r\n Hello World\n\r\n0\r\n\r\n’</li></ul><p>The reason is the Transfer-Encoding: chunked in the response headers.</p><p>As described <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding">here</a>:</p><blockquote><em>chunked</em></blockquote><blockquote><em>Data is sent in a series of chunks. The Content-Length header is omitted in this case and at the beginning of each chunk you need to add the length of the current chunk in hexadecimal format, followed by </em>\r\n<em> and then the chunk itself, followed by another </em>\r\n<em>. The terminating chunk is a regular chunk, with the exception that its length is zero. It is followed by the trailer, which consists of a (possibly empty) sequence of entity header fields.</em></blockquote><p>So in the first chunk, d is a hexadecimal number, indicating that there are 13 characters, which are ‘HelloWorld’, two spaces, and a \n. The second chunk, the empty one, means the body part is over.</p><p>We have successfully got the response data. Next, let’s parse it.</p><h4>Parse HTTP response</h4><p><strong>Parse response line and response head</strong></p><p>As you can see, the response is such a string:</p><ul><li>the request line and the request header are separated by \r\n</li><li>there are two \r\n between the last request header and the request body</li></ul><p>HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nDate: Sun, 02 Aug 2020 17:05:31 GMT\r\nConnection: keep-alive\r\nTransfer-Encoding: chunked\r\n\r\nd\r\n Hello World\n\r\n0\r\n\r\n</p><p>We can use a state machine to parse this string. The states can be designed according to the format of the response, like the code below.</p><p>In the index.js, we add the ResponseParser class.</p><p>./client/index.js</p><pre>class ResponseParser {<br>  constructor() {<br>    this.WAITING_STATUS_LINE = 0;<br>    this.WAITING_STATUS_LINE_END = 1;</pre><pre>    this.WAITING_HEADER_NAME = 2;<br>    this.WAITING_HEADER_SPACE = 3;<br>    this.WAITING_HEADER_VALUE = 4;<br>    this.WAITING_HEADER_LINE_END = 5;<br>    this.WAITING_HEADER_BLOCK_END = 6;</pre><pre>    this.WAITING_BODY = 7;</pre><pre>    // initial state<br>    this.current = this.WAITING_STATUS_LINE;</pre><pre>    this.statusLine = &#39;&#39;;<br>    this.headers = {};<br>    this.headerName = &#39;&#39;;<br>    this.headerValue = &#39;&#39;;<br>    this.bodyParser = null;<br>  }<br>  get isFinished() { }</pre><pre>  get response() { }</pre><pre>  receive(string) {<br>    for (const char of string) {<br>      this.receiveChar(char);<br>    }<br>    console.log(this.statusLine, &#39;\n&#39;, this.headers)<br>  }<br>  <br>  // a state machine<br>  receiveChar(char) {<br>    switch (this.current) {<br>      case this.WAITING_STATUS_LINE:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_STATUS_LINE_END;<br>        } else {<br>          this.statusLine += char;<br>        }<br>        break;</pre><pre>      case this.WAITING_STATUS_LINE_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_HEADER_NAME;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_NAME:<br>        if (char === &#39;:&#39;) {<br>          this.current = this.WAITING_HEADER_SPACE;<br>        } else if (char === &#39;\r&#39;) {<br>          // no key-value pairs at all or the end of k-v paris (no more)<br>          this.current = this.WAITING_HEADER_BLOCK_END;<br>        } else {<br>          this.headerName += char;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_SPACE:<br>        if (char === &#39; &#39;) {<br>          this.current = this.WAITING_HEADER_VALUE;<br>        }<br>        break;<br>      case this.WAITING_HEADER_VALUE:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_HEADER_LINE_END;<br>        } else {<br>          this.headerValue += char;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_LINE_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_HEADER_NAME;<br>          this.headers = {<br>            ...this.headers,<br>            [this.headerName]: this.headerValue<br>          }<br>          this.headerName = &#39;&#39;;<br>          this.headerValue = &#39;&#39;;<br>        }<br>        break;</pre><pre>      case this.WAITING_HEADER_BLOCK_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_BODY;<br>        }<br>        break;</pre><pre>      case this.WAITING_BODY:<br>        console.log(JSON.stringify(char));<br>        break;</pre><pre>      default:<br>        break;<br>    }<br>  }<br>}</pre><p>Then, in the send() method of the Request class, we pass the data to the parser.</p><pre>send(connection) {<br>    return new Promise((resolve, reject) =&gt; {<br>      const parser = new ResponseParser;</pre><pre>      if (connection) {<br>        connection.write(this.toString());<br>      } else {<br>        // create a TCP connection<br>        connection = net.createConnection(<br>          { host: this.host, port: this.port },<br>          () =&gt; connection.write(this.toString())<br>        );<br>      }</pre><pre>      connection.on(&#39;data&#39;, data =&gt; {<br>        console.log(data.toString());<br>        console.log(JSON.stringify(data.toString()));</pre><pre>        // receive the data and pass it to the parser<br>        parser.receive(data.toString());<br>        if (parser.isFinished) {<br>          resolve(parser.response);<br>          connection.end();<br>        }<br>      });</pre><pre>      connection.on(&#39;error&#39;, error =&gt; {<br>        console.log(error);<br>        reject(error);<br>        connection.end();<br>      })<br>    })<br>  }</pre><p>Executing the file, we can see that the response line and response headers have been parsed successfully, and the content of the response body has been printed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/722/1*Vp3RpNv7cSLtDkaY2E8JPA.png" /></figure><p>Different types of response bodies require different parsing methods. Next, we only take chunked as an example.</p><p><strong>Parse response body</strong></p><p>In the newly added ChunkedBodyParser class, we also use a state machine to parse the response body.</p><p>The hexadecimal number and the content are separated by \r\n, so we design the states like this.</p><p>./client/index.js</p><pre>class ChunkedBodyParser {<br>  constructor() {<br>    this.WAITING_LENGTH = 0;<br>    this.WAITING_LENGTH_LINE_END = 1;</pre><pre>    this.READING_CHUNK = 2;<br>    this.WAITING_BLANK_LINE = 3;<br>    this.WAITING_BLANK_LINE_END = 4;</pre><pre>    this.current = this.WAITING_LENGTH;</pre><pre>    this.content = [];<br>    this.length = 0;<br>    this.isFinished = false;<br>  }</pre><pre>receiveChar(char) {<br>    switch (this.current) {<br>      case this.WAITING_LENGTH:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_LENGTH_LINE_END;<br>          if (this.length === 0) {<br>            this.isFinished = true;<br>          }<br>        } else {<br>          // operation of hexadecimal numbers, for example, 2AF5, 2 =&gt; A =&gt; F =&gt; 5<br>          this.length *= 16;<br>          this.length += parseInt(char, 16);<br>        }<br>        break;</pre><pre>      case this.WAITING_LENGTH_LINE_END:<br>        if (char === &#39;\n&#39; &amp;&amp; !this.isFinished) {<br>          this.current = this.READING_CHUNK;<br>        }<br>        break;</pre><pre>      case this.READING_CHUNK:<br>        this.content.push(char);<br>        this.length -= 1;<br>        if (this.length === 0) {<br>          this.current = this.WAITING_BLANK_LINE;<br>        }<br>        break;</pre><pre>      case this.WAITING_BLANK_LINE:<br>        if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_BLANK_LINE_END;<br>        }<br>        break;</pre><pre>      case this.WAITING_BLANK_LINE_END:<br>        if (char === &#39;\n&#39;) {<br>          this.current = this.WAITING_LENGTH;<br>        }<br>        break;</pre><pre>      default:<br>        break;<br>    }<br>  }<br>}</pre><p>Then, we use the parser in the receiveChar() method of the ResponseParser class.</p><pre>receiveChar(char) {<br>  ...<br>  case this.WAITING_HEADER_NAME:<br>        if (char === &#39;:&#39;) {<br>          this.current = this.WAITING_HEADER_SPACE;<br>        } else if (char === &#39;\r&#39;) {<br>          this.current = this.WAITING_HEADER_BLOCK_END;<br>          if (this.headers[&#39;Transfer-Encoding&#39;] === &#39;chunked&#39;) {<br>            this.bodyParser = new ChunkedBodyParser();<br>          }<br>        } else {<br>          this.headerName += char;<br>        }<br>        break;<br>  ...<br>  case this.WAITING_BODY:<br>        this.bodyParser.receiveChar(char);<br>        break;<br>  ...<br>}</pre><p>At this point, the response line, response header, and response body are all parsed, we can complete the isFinished() and response() methods in ResponseParser class.</p><pre>get isFinished() {<br>  return this.bodyParser &amp;&amp; this.bodyParser.isFinished;<br>}<br></pre><pre>get response() {<br>  this.statusLine.match(/HTTP\/1.1 ([0-9]+) ([\s\S]+)/);<br>  return {<br>    statusCode: RegExp.$1,<br>    statusText: RegExp.$2,<br>    headers: this.headers,<br>    body: this.bodyParser.content.join(&#39;&#39;)<br>  }<br>}</pre><p>This is the printed result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*hdvMe3IYQFeCzkcBdLDS0A.png" /></figure><p>Let’s send HTML from the server. After saving the changes, the node monitor should automatically restart the server. Requesting again from the client-side, the response is printed out.</p><p>./server/server.js</p><pre>const http = require(&quot;http&quot;);</pre><pre>http.createServer((request, response) =&gt; {<br>  let body = [];</pre><pre>  request.on(&#39;error&#39;, error =&gt; {<br>    console.log(error);<br>  })<br>    .on(&#39;data&#39;, chunk =&gt; {<br>      body.push(chunk.toString());<br>      console.log(body)<br>    })<br>    .on(&#39;end&#39;, () =&gt; {<br>      body = body.join(&#39;&#39;);<br>      response.writeHead(200, { &#39;Content-Type&#39;: &#39;text/html&#39; });<br>      response.end(<br>        `&lt;html maaa=a &gt;<br>    &lt;head&gt;<br>          &lt;style&gt;<br>    body div #myid{<br>      width:100px;<br>      background-color: #ff5000;<br>    }<br>    body div img{<br>      width:30px;<br>      background-color: #ff1111;<br>    }<br>      &lt;/style&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>      &lt;div&gt;<br>          &lt;img id=&quot;myid&quot;/&gt;<br>          &lt;img /&gt;<br>      &lt;/div&gt;<br>    &lt;/body&gt;<br>    &lt;/html&gt;`);<br>    });<br>}).listen(8080);</pre><pre>console.log(&#39;The server is running!&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*_AOzYDJnXjEE0FxGZMy9hQ.png" /></figure><p>So far, we have successfully received the HTML from the network request.</p><p>Now, we can try to parse HTML to get a DOM tree.</p><h3>Step two: HTML parsing</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*aY3u_N43jh2D2ZII7eNvZQ.png" /></figure><h4>Tokenization (lexical analysis)</h4><p>A token represents the smallest meaningful unit in the compilation principle. In terms of HTML, 90% of the token that we need for daily development is only about startTag, attributes, endTag, comments, and CDATA nodes.</p><p>Take &lt;p class=&quot;a&quot;&gt;text&lt;/p&gt; as an example, split it to the smallest meaningful units, we can get:</p><ul><li>&lt;p the start of an opening tag</li><li>class=&quot;a&quot; attribute</li><li>&gt; the end of an opening tag</li><li>text</li><li>closing tag</li></ul><p>Similar to the previous, we also use a state machine for parsing. Fortunately, the state machine has been well designed in the <a href="https://html.spec.whatwg.org/multipage/parsing.html#tokenization">HTML standard</a>, what we need to do is just translate it to JavaScript.</p><p>There are more than 80 states specified, but we don’t need so many states to parse our simple HTML. So in our sample code, some simplifications are made.</p><h4>Setup an empty state machine</h4><p>We design the state as a function so that the state transition part is very simple.</p><pre>let state = data; // the initial state is called &#39;data&#39; in the HTML standard</pre><pre>for (const char of html) {<br>  state = state(char);<br>}</pre><p>Add a new file “parser.js”.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;); // end of file token</pre><pre>module.exports.parseHTML = function (html) {<br>  let state = data;</pre><pre>  for (const char of html) {<br>    console.log(JSON.stringify(char), state.name)<br>    state = state(char);<br>  }<br>  state = state(EOF);<br>}</pre><pre>// There are three kinds of HTML tags: opening tag &lt;div&gt;, closing tag &lt;/div&gt;, self-closing tag &lt;div/&gt;</pre><pre>// the initial state is called &#39;data&#39; in the HTML standard<br>function data(char) {<br>  if (char === &#39;&lt;&#39;) {<br>    return tagOpen;<br>  } else if (char === EOF) {<br>    return;<br>  } else {<br>    // text node<br>    return data;<br>  }<br>}</pre><pre>// when the state is tagOpen, we don&#39;t know what kind of tag it is yet. like &#39;&lt;&#39;<br>function tagOpen(char) {<br>  if (char === &#39;/&#39;) {<br>    // &#39;&lt;/&#39; ,e.g. &#39;&lt;/div&gt;&#39;<br>    return endTagOpen;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    // the char is a letter, the tag could be a opening tag or a self-closing tag. e.g. &#39;&lt;d&#39;  =&gt; &#39;&lt;div&gt;&#39; or &#39;&lt;/div&gt;&#39;<br>    return tagName(char); // reconsume the char<br>  } else {<br>    // Parse error<br>    return;<br>  }<br>}<br><br>function endTagOpen(char) {<br>  if (char.match(/^[a-zA-Z]$/)) {<br>    return tagName(char);<br>  } else if (char === &#39;&gt;&#39;) {<br>    // error  /&gt;  It&#39;s html, not JSX<br>    // Parse error<br>  } else if (char === EOF) {<br>    // Parse error<br>  } else {<br>    // Parse error<br>  }<br>}</pre><pre>function tagName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    // tagname start from a &#39;&lt;&#39;, end with a &#39; &#39; e.g. &#39;&lt;div prop&#39;<br>    return beforeAttributeName;<br>  } else if (char === &#39;/&#39;) {<br>    return selfClosingStartTag;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    return tagName;<br>  } else if (char === &#39;&gt;&#39;) {<br>    // the current tag is over, go back to the initial state to parse the next tag<br>    return data;<br>  } else {<br>    return tagName;<br>  }<br>}</pre><pre>// Only &#39;&gt;&#39; is valid after &#39;&lt;div/&#39;<br>function selfClosingStartTag(char) {<br>  if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {</pre><pre>  }<br>}</pre><pre>function beforeAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    // Parse error<br>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) { // end of a pair of attribute, e.g. &quot;&lt;div class=&#39;abc&#39; &quot;<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) { // e.g. &#39;class=&#39;<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) { // null</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) {</pre><pre>  } else {<br>    return attributeName;<br>  }<br>}<br></pre><pre>function beforeAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\&quot;&quot;) {<br>    return doubleQuotedAttributeValue; // e.g. &lt;html attribute=&quot;<br>  } else if (char === &quot;\&#39;&quot;) {<br>    return singleQuotedAttributeValue; // e.g. &lt;html attribute=&#39;<br>  } else if (char === &quot;&gt;&quot;) {<br>    // return data<br>  } else {<br>    return UnquotedAttributeValue(char); // e.g. &lt;html attribute=<br>  }<br>}</pre><pre>function doubleQuotedAttributeValue(char) {<br>  if (char === &quot;\&quot;&quot;) { // the second double quotes<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function singleQuotedAttributeValue(char) {<br>  if (char === &quot;\&#39;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return singleQuotedAttributeValue;<br>  }<br>}</pre><pre>// when the attribute part is over, save attribute name and value to the current token<br>function UnquotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) { // end of unquoted Attribute value<br>    return beforeAttributeName; // to parse a new pair of attribute<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot; || char === &quot;=&quot; || char === &quot;`&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return UnquotedAttributeValue;<br>  }<br>}</pre><pre>function afterQuotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function afterAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return afterAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><p>Then, use the new parser in the index.js.</p><p>./client/index.js</p><pre>const parser = require(&#39;./parser&#39;);<br>...</pre><pre>void async function () {<br>  const request = new Request({<br>   ...<br>  });</pre><pre>  const response = await request.send();<br>  const dom = parser.parseHTML(response.body);<br>  console.log(JSON.stringify(dom, null, 2));<br>}()</pre><p>Run the index.js, now the state machine is running! You can see the correspondence between characters and states at each step in the printed log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*evb6L1qRJ7tBgKoioFkIKw.png" /></figure><p>The dom is undefined because now this state machine is empty, it does nothing. In the next step, let&#39;s add the corresponding logic code in these states to build the DOM tree.</p><h4>Emit tokens</h4><p>The tag types are nothing more than the starting-tag, the closing tag, and the self-closing tag. In the state machine, we emit the tag token when we encounter the end of a tag.</p><p>The emit() function takes the token generated from the state machine. In this step, it does nothing but prints the received token.</p><p>So the parser.js looks like this.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;);<br>let currentToken = null;</pre><pre>function emit(token) {<br>  console.log(token);<br>}</pre><pre>module.exports.parseHTML = function (html) {<br>  let state = data;</pre><pre>  for (const char of html) {<br>    state = state(char);<br>  }<br>  state = state(EOF);<br>}</pre><pre>function data(char) {<br>  if (char === &#39;&lt;&#39;) {<br>    return tagOpen;<br>  } else if (char === EOF) {<br>    emit({ type: &#39;EOF&#39; });<br>    return;<br>  } else {<br>    // emit the text nodes one by one, we can join them later<br>    emit({<br>      type: &#39;text&#39;,<br>      content: char,<br>    });<br>    return data;<br>  }<br>}</pre><pre>function tagOpen(char) {<br>  if (char === &#39;/&#39;) {<br>    return endTagOpen;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    currentToken = {<br>      type: &#39;startTag&#39;,<br>      tagName: &#39;&#39;,<br>    }<br>    return tagName(char); // reconsume<br>  } else {<br>    // Parse error<br>    return;<br>  }<br>}<br><br>function endTagOpen(char) {<br>  if (char.match(/^[a-zA-Z]$/)) {<br>    currentToken = {<br>      type: &#39;endTag&#39;,<br>      tagName: &#39;&#39;<br>    }<br>    return tagName(char);<br>  } else if (char === &#39;&gt;&#39;) {<br>    // Parse error<br>  } else if (char === EOF) {<br>    // Parse error<br>  } else {<br>    // Parse error<br>  }<br>}</pre><pre>function tagName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &#39;/&#39;) {<br>    return selfClosingStartTag;<br>  } else if (char.match(/^[a-zA-Z]$/)) {<br>    currentToken.tagName += char;<br>    return tagName;<br>  } else if (char === &#39;&gt;&#39;) {<br>    // the current tag is over, go back to the initial state to parse the next tag<br>    emit(currentToken);<br>    return data;<br>  } else {<br>    return tagName;<br>  }<br>}</pre><pre>function selfClosingStartTag(char) {<br>  if (char === &quot;&gt;&quot;) {<br>    currentToken.isSelfClosing = true;<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {</pre><pre>  }<br>}</pre><pre>function beforeAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    // parser error<br>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) { // null</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) {</pre><pre>  } else {<br>    return attributeName;<br>  }<br>}</pre><pre>function beforeAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\&quot;&quot;) {<br>    return doubleQuotedAttributeValue;<br>  } else if (char === &quot;\&#39;&quot;) {<br>    return singleQuotedAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    // return data<br>  } else {<br>    return UnquotedAttributeValue(char);<br>  }<br>}</pre><pre>function doubleQuotedAttributeValue(char) {<br>  if (char === &quot;\&quot;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function singleQuotedAttributeValue(char) {<br>  if (char === &quot;\&#39;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return singleQuotedAttributeValue;<br>  }<br>}</pre><pre>function UnquotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot; || char === &quot;=&quot; || char === &quot;`&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return UnquotedAttributeValue;<br>  }<br>}</pre><pre>function afterQuotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function afterAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return afterAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/599/1*xFfrgeg5pZCxTXCxA8zeCw.png" /></figure><p>Now, we get these tokens. You might have noticed that the attributes are missing. For example, the token of the img tag with id &quot;myid&quot; is { type: &#39;startTag&#39;, tagName: &#39;img&#39;, isSelfClosing: true }. The id is not included.</p><p>The way of adding attributes is similar to the previous step. Add the currentAttribute variable and complete the logic in the state machine like below.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;);<br>let currentToken = null;<br>let currentAttribute = null;</pre><pre>...</pre><pre>function beforeAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    // parse error<br>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) { </pre><pre>  } else {<br>    return attributeName;<br>  }<br>}<br></pre><pre>function attributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === EOF) {<br>    return afterAttributeName(char);<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) { // null</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot;) {</pre><pre>  } else {<br>    return attributeName;<br>  }<br>}</pre><pre>function beforeAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/) || char === &quot;/&quot; || char === &quot;&gt;&quot; || char === EOF) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;\&quot;&quot;) {<br>    return doubleQuotedAttributeValue;<br>  } else if (char === &quot;\&#39;&quot;) {<br>    return singleQuotedAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    // return data<br>  } else {<br>    return UnquotedAttributeValue(char);<br>  }<br>}</pre><pre>function doubleQuotedAttributeValue(char) {<br>  if (char === &quot;\&quot;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function singleQuotedAttributeValue(char) {<br>  if (char === &quot;\&#39;&quot;) {<br>    return afterQuotedAttributeValue;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return singleQuotedAttributeValue;<br>  }<br>}</pre><pre>function UnquotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === &quot;\u0000&quot;) {</pre><pre>  } else if (char === &quot;\&quot;&quot; || char === &quot;&#39;&quot; || char === &quot;&lt;&quot; || char === &quot;=&quot; || char === &quot;`&quot;) {</pre><pre>  } else if (char === EOF) {</pre><pre>  } else {<br>    return UnquotedAttributeValue;<br>  }<br>}</pre><pre>function afterQuotedAttributeValue(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return beforeAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return doubleQuotedAttributeValue;<br>  }<br>}</pre><pre>function afterAttributeName(char) {<br>  if (char.match(/^[\t\n\f ]$/)) {<br>    return afterAttributeName;<br>  } else if (char === &quot;/&quot;) {<br>    return selfClosingStartTag;<br>  } else if (char === &quot;=&quot;) {<br>    return beforeAttributeValue;<br>  } else if (char === &quot;&gt;&quot;) {<br>    emit(currentToken);<br>    return data;<br>  } else if (char === EOF) {</pre><pre>  } else {<br>    return attributeName(char);<br>  }<br>}</pre><p>Run the index again, you can find out that now the attributes come back!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*C4fIm3t8uABUNNlp8qH_hw.png" /></figure><p>At this point, we have split the character stream into tokens, and then let’s use these tokens to build a DOM tree.</p><h4>DOM tree construction (syntactic analysis)</h4><p>In real browsers, the HTML nodes inheritance from different subclasses of Node. To simplify our code, we only divide Node into Element and Text.</p><p>For elements, we construct the DOM tree by using a stack to match the tags.</p><p>Specifically, when the emit function receives the token, it starts to build the DOM tree. When it encounters a startTag, it pushes the element into the stack, and when it encounters the matching endTag, it pops the top element out of the stack. Self-closing tags do not need to be pushed into the stack.</p><p>It is worth mentioning that when a tag mismatch occurs, the real browser will do fault-tolerant processing, while we just throw an error here.</p><p>When all tokens are received, the top element (the document element) of the stack is the root node of the DOM tree.</p><p>For Text nodes, we need to merge them when they are adjacent. When it is pushed into the stack, check whether the top node of the stack is a Text node. If so, merge the Text nodes and then add the text nodes to the DOM tree.</p><p>./client/parser.js</p><pre>const EOF = Symbol(&#39;EOF&#39;);<br>let currentToken = null;<br>let currentAttribute = null;<br>let currentTextNode = null;</pre><pre>// a stack containing the root node<br>const stack = [{ type: &#39;document&#39;, children: [] }];</pre><pre>module.exports.parseHTML = function (html) {<br>  let state = data;</pre><pre>  for (const char of html) {<br>    state = state(char);<br>  }<br>  state = state(EOF);<br>  // return the DOM tree<br>  return stack[0];<br>}</pre><pre>...</pre><pre>function emit(token) {<br>  let top = stack[stack.length - 1];</pre><pre>  if (token.type === &#39;startTag&#39;) {<br>    // create the element<br>    let element = {<br>      type: &#39;element&#39;,<br>      children: [],<br>      attributes: [],<br>      tagName: token.tagName<br>    }</pre><pre>for (const prop in token) {<br>      if (prop !== &quot;type&quot; &amp;&amp; prop !== &quot;tagName&quot;) {<br>        element.attributes.push({<br>          name: prop,<br>          value: token[prop],<br>        })<br>      }<br>    }<br><br>    top.children.push(element);<br>    // comment out this line to avoid the circular structure error when print the DOM tree<br>    // element.parent = top;</pre><pre>    if (!token.isSelfClosing) {<br>      stack.push(element);<br>    }</pre><pre>    currentTextNode = null;<br>  } else if (token.type === &#39;endTag&#39;) {<br>    if (top.tagName !== token.tagName) {<br>      throw new Error(&#39;Tag does not match&#39;);<br>    } else {<br>      stack.pop();<br>    }<br>    currentTextNode = null;<br>  } else if (token.type === &#39;text&#39;) {<br>    if (currentTextNode === null) {<br>      currentTextNode = {<br>        type: &quot;text&quot;,<br>        content: &quot;&quot;,<br>      }<br>      top.children.push(currentTextNode);<br>    }<br>    currentTextNode.content += token.content;<br>  }<br>}</pre><p>Run the index again, instead of undefined, now we can see a DOM tree here! Under the document node is the html node, below it is the head node and the body node.</p><pre>{<br>  &quot;type&quot;: &quot;document&quot;,<br>  &quot;children&quot;: [<br>    {<br>      &quot;type&quot;: &quot;element&quot;,<br>      &quot;children&quot;: [<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;content&quot;: &quot;\n      &quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;element&quot;,<br>          &quot;children&quot;: [<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n            &quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;element&quot;,<br>              &quot;children&quot;: [<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n      body div #myid{\n        width:100px;\n        background-color: #ff5000;\n      }\n      body div img{\n        width:30px;\n        background-color: #ff1111;\n      }\n        &quot;<br>                }<br>              ],<br>              &quot;attributes&quot;: [],<br>              &quot;tagName&quot;: &quot;style&quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n      &quot;<br>            }<br>          ],<br>          &quot;attributes&quot;: [],<br>          &quot;tagName&quot;: &quot;head&quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;content&quot;: &quot;\n      &quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;element&quot;,<br>          &quot;children&quot;: [<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n        &quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;element&quot;,<br>              &quot;children&quot;: [<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n            &quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;element&quot;,<br>                  &quot;children&quot;: [],<br>                  &quot;attributes&quot;: [<br>                    {<br>                      &quot;name&quot;: &quot;id&quot;,<br>                      &quot;value&quot;: &quot;myid&quot;<br>                    },<br>                    {<br>                      &quot;name&quot;: &quot;isSelfClosing&quot;,<br>                      &quot;value&quot;: true<br>                    }<br>                  ],<br>                  &quot;tagName&quot;: &quot;img&quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n            &quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;element&quot;,<br>                  &quot;children&quot;: [],<br>                  &quot;attributes&quot;: [<br>                    {<br>                      &quot;name&quot;: &quot;isSelfClosing&quot;,<br>                      &quot;value&quot;: true<br>                    }<br>                  ],<br>                  &quot;tagName&quot;: &quot;img&quot;<br>                },<br>                {<br>                  &quot;type&quot;: &quot;text&quot;,<br>                  &quot;content&quot;: &quot;\n        &quot;<br>                }<br>              ],<br>              &quot;attributes&quot;: [],<br>              &quot;tagName&quot;: &quot;div&quot;<br>            },<br>            {<br>              &quot;type&quot;: &quot;text&quot;,<br>              &quot;content&quot;: &quot;\n      &quot;<br>            }<br>          ],<br>          &quot;attributes&quot;: [],<br>          &quot;tagName&quot;: &quot;body&quot;<br>        },<br>        {<br>          &quot;type&quot;: &quot;text&quot;,<br>          &quot;content&quot;: &quot;\n      &quot;<br>        }<br>      ],<br>      &quot;attributes&quot;: [<br>        {<br>          &quot;name&quot;: &quot;maaa&quot;,<br>          &quot;value&quot;: &quot;a&quot;<br>        }<br>      ],<br>      &quot;tagName&quot;: &quot;html&quot;<br>    }<br>  ]<br>}</pre><p>Look at the DOM tree we have here. The structure is correct, but it is bare, without any decoration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XsEVaNB9wM-nIJIioWD6uA.jpeg" /></figure><h3>Step three: CSS computing</h3><p>Let’s make it a beautiful Christmas tree with CSS in this step!</p><p>During the CSS computation step, parsed CSS rules are added to the matched DOM elements. Note that CSS computing also occurs during the construction of the DOM tree.</p><p>We need to install the css library which can parse the CSS code into a CSS AST (abstract syntax tree). To simplify, we use the AST to replace the role of CSSOM in our sample project.</p><p>npm install css</p><h4>Gather the CSS rules</h4><p>First, we need to gather all CSS rules together from the CSS AST.</p><p>./client/parser.js</p><pre>const css = require(&quot;css&quot;);<br>...</pre><pre>// to save the CSS rules<br>const rules = []; </pre><pre>// gather all the CSS rules<br>function addCSSRules(text) {<br>  const ast = css.parse(text);<br>  rules.push(...ast.stylesheet.rules);<br>}</pre><p>Then, execute it at the end of the style tag (ignore CSS in other locations).</p><p>So, in the emit() method:</p><pre>...<br>else if (token.type === &#39;endTag&#39;) {<br>  if (top.tagName !== token.tagName) {<br>    throw new Error(&#39;Tag does not match&#39;);<br>  } else {<br>    if (top.tagName === &#39;style&#39;) {<br>      addCSSRules(top.children[0].content); // The children of the top element in the stack are the current element<br>    }<br>    stack.pop();<br>  }<br>  currentTextNode = null;<br>}<br>...</pre><p>If you print the rules, you’ll find that the CSS rules have been collected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ci3djq_UvIwyw1EdyCMYIQ.png" /></figure><h4>Match CSS rules and elements</h4><p>When to do it? Generally speaking, we will try to ensure that all selectors can be judged when startTag is entered. With the later addition of advanced selectors, this rule has been loosened. Due to the limited length of the article, we only use simple selectors in our sample code. So when there is a startTag, it is already possible to determine which CSS rules the element matches.</p><p>In real browsers, there may be style tags in the body that require recalculation of CSS. We ignore this kind of situation.</p><p>Call the computeCSS in the emit function.</p><p>./client/parser.js</p><pre>function emit(token) {<br>  let top = stack[stack.length - 1];</pre><pre>  if (token.type === &#39;startTag&#39;) {<br>    let element = {...}</pre><pre>    for (const prop in token) {<br>      ...<br>    }<br>    // CSS computing happens during the DOM tree construction <br>    computeCSS(element);<br>    <br>    top.children.push(element);<br>    ...</pre><p>In the computeCSS function, in order to match the selector with the corresponding element, we need to get the ancestor element sequence of the current element.</p><p>const elements = stack.slice().reverse();</p><p>All ancestor elements of the current element are stored in the stack. Because the stack is changing, the slice() method is used to save a copy of the current state.</p><p>When we try to determine whether an element matches the selector, we start with the current element, then its parent element, and step by step outward. Take “div #myid” as an example, the div can be any ancestor element, but #myid must be the current element.</p><p>In addition, we need a way to calculate whether the selector matches the element. Also for simplicity, we only deal with the case of descendant selectors composed of simple selectors and spaces, like ‘div #myid’.</p><p>./client/parser.js</p><pre>...</pre><pre>// assuming selector is a simple selector (.class #id tagname)<br>function match(element, selector) {<br>  if (!selector || !element.attributes) return false;</pre><pre>  if (selector.charAt(0) === &#39;#&#39;) { // id selector<br>    const attr = element.attributes.filter(<br>      ({ name }) =&gt; (name === &#39;id&#39;)<br>    )[0];<br>    if (attr &amp;&amp; attr.value === selector.replace(&#39;#&#39;, &#39;&#39;)) {<br>      return true;<br>    }<br>  } else if (selector.charAt(0) === &#39;.&#39;) { // class selector<br>    const attr = element.attributes.filter(<br>      ({ name }) =&gt; (name === &#39;class&#39;)<br>    )[0];<br>    if (attr &amp;&amp; attr.value === selector.replace(&quot;.&quot;, &quot;&quot;)) {<br>      return true;<br>    }<br>  } else { // type selector<br>    if (element.tagName === selector) return true;<br>  }<br>}<br></pre><pre>function computeCSS(element) {<br>  const elements = stack.slice().reverse();</pre><pre>for (const rule of rules) {<br>    const selectors = rule.selectors[0].split(&#39; &#39;).reverse(); //  the structure of the ast and don&#39;t forget to do the reversing<br>    // selectors are like &#39;[ &#39;#myid&#39;, &#39;div&#39;, &#39;body&#39; ]&#39;</pre><pre>    if (!match(element, selectors[0])) continue;</pre><pre>    let matched = false;</pre><pre>let selectorIndex = 1; // elements is parent element or ancestor element, so here we start from 1<br>    for (let elementIndex = 0; elementIndex &lt; elements.length; elementIndex++) {<br>      if (match(elements[elementIndex], selectors[selectorIndex])) {<br>        selectorIndex++;<br>      }<br>    }<br>    if (selectorIndex &gt;= selectors.length) {<br>      // all selectors are matched<br>      matched = true;<br>    }<br>    if (matched) {<br>      console.log(`Selector &quot;${rule.selectors[0]}&quot; has matched element ${JSON.stringify(element)}`)<br>    }<br>  }<br>}</pre><pre>...</pre><p>From the printed result, we can see that the element and the selector have been correctly matched.</p><p>Selector &quot;body div #myid&quot; has matched element {&quot;type&quot;:&quot;element&quot;,&quot;children&quot;:[],&quot;attributes&quot;:[{&quot;name&quot;:&quot;id&quot;,&quot;value&quot;:&quot;myid&quot;},{&quot;name&quot;:&quot;isSelfClosing&quot;,&quot;value&quot;:true}],&quot;tagName&quot;:&quot;img&quot;}</p><p>After the successful match, we should add CSS rules to the corresponding elements.</p><p>This step is very simple. In the computeCSS function, we add a computedStyle property to the element and save the CSS rules into it when matching.</p><pre>function computeCSS(element) {<br>  if (!element.computedStyle) {<br>    element.computedStyle = {};<br>  }</pre><pre>  const elements = stack.slice().reverse();</pre><pre>  for (const rule of rules) {<br>    ...<br>    <br>    if (matched) {<br>      const { computedStyle } = element;<br>      for (const declaration of rule.declarations) {<br>        const { property, value } = declaration;<br>        if (!computedStyle[property]) {<br>          computedStyle[property] = {};<br>        }<br>        computedStyle[property] = value;<br>      }<br>    }<br>  }<br>  console.log(element.computedStyle)<br>}</pre><p>Now the elements have their CSS rules, but it’s not enough yet. Go check these two img elements, you’ll find that they have the same computedstyle property, which is wrong.</p><p>{ width: &#39;30px&#39;, &#39;background-color&#39;: &#39;#ff1111&#39; }</p><p>Why? The reason is the CSS specificity. The rules with higher specificity should always have higher priority. The currently wrong result is because the later low-specificity rules overwrite the previous high-specificity rules.</p><p>To calculate the CSS specificity, we need a quaternion: [inline, id, class/attribute, tagName]（Inline styles have the highest priority, and the rest is number of each type of selectors）.</p><p>For example, for the case[a, b, c, d], the calculation formula is:</p><p>specificity = a * N³ + b * N² + c * N + d</p><p>N is a big number. In the old version of IE, in order to save memory, the value of N is 255, which is not large enough, resulting in a funny bug that 256 classes are equivalent to one id. Of course, any sane developer would not write 256 selectors. Nowadays, most browsers set N as 65536.</p><p>Based on this, we can implement functions for calculating and comparing CSS specificity. Again, this is also a simplified version.</p><pre>function getSpecificity(selector) {<br>  const specificity = [0, 0, 0, 0];<br>  //Similarly, assuming that selector is composed of simple selectors.<br>  const selectors = selector.split(&#39; &#39;);</pre><pre>  for (const item of selectors) {<br>    if (item.charAt(0) === &#39;#&#39;) {<br>      specificity[1] += 1;<br>    } else if (item.charAt(0) === &#39;.&#39;) {<br>      specificity[2] += 1;<br>    } else {<br>      specificity[3] += 1;<br>    }<br>  }<br>  return specificity;<br>}</pre><pre>function compareSpecificity(sp1, sp2) {<br>  if (sp1[0] - sp2[0]) {<br>    return sp1[0] - sp2[0];<br>  }<br>  if (sp1[1] - sp2[1]) {<br>    return sp1[1] - sp2[1];<br>  }<br>  if (sp1[2] - sp2[2]) {<br>    return sp1[2] - sp2[2];<br>  }<br>  return sp1[3] - sp2[3];<br>}</pre><p>In the computeCSS function, when an element matches a selector, instead of simply apply the CSS rules, we need to compare the CSS specificity and use the rules with higher specificity.</p><pre>if (matched) {<br>      const { computedStyle } = element;<br>      const specificity = getSpecificity(rule.selectors[0]);</pre><pre>      for (const declaration of rule.declarations) {<br>        const { property, value } = declaration;<br>        if (!computedStyle[property]) {<br>          computedStyle[property] = {};<br>        }<br>        // computedStyle[property] = value;<br>        // CSS specificity<br>        if (!computedStyle[property].specificity) {<br>          computedStyle[property] = {<br>            value,<br>            specificity,<br>            ...computedStyle[property],<br>          }<br>        } else if (compareSpecificity(computedStyle[property].specificity, specificity) &lt; 0) {<br>          // current CSS selector have higher specificity than the previous, cover the previous rules<br>          computedStyle[property] = {<br>            value,<br>            specificity,<br>            ...computedStyle[property],<br>          }<br>        }<br>      }<br>    }</pre><p>Run it again, as it printed, the img element with ID is correctly displayed as &#39;#ff5000&#39;.</p><p>Now, if you print the DOM tree again, you will see a beautiful Christmas tree with all the CSS decoration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PBDd0KlFX7qBTURHSSUP-Q.jpeg" /></figure><p>Next, our job is to calculate the position of each element so we can get a DOM tree with position information.</p><h3>Step four: layout</h3><p>In CSS, there are three generations of layout technology:</p><ul><li>normal flow</li><li>flexbox</li><li>grid</li></ul><p>We are going to implement the most popular one: flexbox. If you are not familiar with this technique, please check this <a href="https://css-tricks.com/snippets/css/a-guide-to-flexbox/">link</a>.</p><h4>Main axis and cross axis</h4><p>Before we start, we must first understand the concepts of the main axis and the cross axis. By default, the main axis is horizontal (from left to right) and the cross axis is vertical (from top to bottom). It can also change with our settings. For example, when the value of ‘flex-direction’ is ‘row’, the main axis is horizontal, when the value is ‘column’, the main axis is vertical. Using these concepts can help us reduce a lot of unnecessary if-else code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W2H_FOT-eUrGecEIsQc0GQ.png" /></figure><h4>When to do the layout</h4><p>Suppose we already have the layout() function, when should we call it? To calculate the flexbox layout, we need to know all the children elements of the current element. So we should call the layout() function in the ‘endTag’ branch.</p><p>./client/parser.js</p><pre>const css = require(&quot;css&quot;);<br>const layout = require(&quot;./layout.js&quot;);</pre><pre>...</pre><pre>function emit(token) {<br>  ...<br>   else if (token.type === &#39;endTag&#39;) {<br>    if (top.tagName !== token.tagName) {<br>      throw new Error(&#39;Tag does not match&#39;);<br>    } else {<br>      if (top.tagName === &#39;style&#39;) {<br>        addCSSRules(top.children[0].content);<br>      }<br>      // right here!<br>      layout(top);<br>      stack.pop();<br>    }<br>    currentTextNode = null;<br>  }<br>  ...<br>}</pre><h4>Pre-processing</h4><p>In the newly created layout.js file, let&#39;s add a getStyle() function to do some pre-processing work like filtering out unwanted elements and type conversion(string to number).</p><p>./client/layout.js</p><pre>function getStyle(element) {<br>  if (!element.style) element.style = {};</pre><pre>  const { computedStyle, style } = element;</pre><pre>  for (const prop in computedStyle) {<br>    if (style[prop]) continue;<br>    <br>    element.style[prop] = computedStyle[prop].value;</pre><pre>    if (element.style[prop].toString().match(/px$/)) {<br>      element.style[prop] = parseInt(element.style[prop]);<br>    }<br><br>    if (element.style[prop].toString().match(/^[0-9\.]+$/)) {<br>      element.style[prop] = parseInt(element.style[prop]);<br>    }<br>  }<br>  return element.style;<br>}</pre><h4>Set default values</h4><p>Set default values in the layout function.</p><p>./client/layout.js</p><pre>function layout(element) {<br>  if (!element.computedStyle) return;</pre><pre>  const elementStyle = getStyle(element);<br><br>  if (elementStyle.display !== &#39;flex&#39;) return;</pre><pre>  // filter out text nodes<br>  const elementItems = element.children.filter(<br>    el =&gt; el.type === &#39;element&#39;<br>  );</pre><pre>  // to support the order property<br>  elementItems.sort((a, b) =&gt; (a.order || 0) - (b.order || 0));</pre><pre>  const style = elementStyle;</pre><pre>  [&#39;width&#39;, &#39;height&#39;].forEach(size =&gt; {<br>    if (style[size] === &#39;auto&#39; || style[size] === &#39;&#39;) {<br>      style[size] = null;<br>    }<br>  })</pre><pre>  // set default values<br>  if (!style[&#39;flex-direction&#39;] || style[&#39;flex-direction&#39;] === &#39;auto&#39;) {<br>    style[&#39;flex-direction&#39;] = &#39;row&#39;;<br>  }<br>  if (!style[&#39;align-items&#39;] || style[&#39;align-items&#39;] === &#39;auto&#39;) {<br>    style[&#39;align-items&#39;] = &#39;stretch&#39;;<br>  }<br>  if (!style[&#39;justify-content&#39;] || style[&#39;justify-content&#39;] === &#39;auto&#39;) {<br>    style[&#39;justify-content&#39;] = &#39;flex-start&#39;;<br>  }<br>  if (!style[&#39;flex-wrap&#39;] || style[&#39;flex-wrap&#39;] === &#39;auto&#39;) {<br>    style[&#39;flex-wrap&#39;] = &#39;nowrap&#39;;<br>  }<br>  if (!style[&#39;align-content&#39;] || style[&#39;align-content&#39;] === &#39;auto&#39;) {<br>    style[&#39;align-content&#39;] = &#39;stretch&#39;;<br>  }</pre><pre>  let mainSize,<br>    mainStart,<br>    mainEnd,<br>    mainSign,<br>    mainBase,<br>    crossSize,<br>    crossStart,<br>    crossEnd,<br>    crossSign,<br>    crossBase;</pre><pre>  if (style[&#39;flex-direction&#39;] === &#39;row&#39;) {<br>    mainSize = &#39;width&#39;;<br>    mainStart = &#39;left&#39;;<br>    mainEnd = &#39;right&#39;;<br>    mainSign = +1;<br>    mainBase = 0;</pre><pre>    crossSize = &#39;height&#39;;<br>    crossStart = &#39;top&#39;;<br>    crossEnd = &#39;bottom&#39;;<br>  } else if (style[&#39;flex-direction&#39;] === &#39;row-reverse&#39;) {<br>    mainSize = &#39;width&#39;;<br>    mainStart = &#39;right&#39;;<br>    mainEnd = &#39;left&#39;;<br>    mainSign = -1;<br>    mainBase = style.width;</pre><pre>    crossSize = &#39;height&#39;;<br>    crossStart = &#39;top&#39;;<br>    crossEnd = &#39;bottom&#39;;<br>  } else if (style[&#39;flex-direction&#39;] === &#39;column&#39;) {<br>    mainSize = &#39;height&#39;;<br>    mainStart = &#39;top&#39;;<br>    mainEnd = &#39;bottom&#39;;<br>    mainSign = +1;<br>    mainBase = 0;</pre><pre>    crossSize = &#39;width&#39;;<br>    crossStart = &#39;left&#39;;<br>    crossEnd = &#39;right&#39;;<br>  } else if (style[&#39;flex-direction&#39;] === &#39;column-reverse&#39;) {<br>    mainSize = &#39;height&#39;;<br>    mainStart = &#39;bottom&#39;;<br>    mainEnd = &#39;top&#39;;<br>    mainSign = -1;<br>    mainBase = style.height;</pre><pre>    crossSize = &#39;width&#39;;<br>    crossStart = &#39;left&#39;;<br>    crossEnd = &#39;right&#39;;<br>  }</pre><pre>  if (style[&#39;flex-wrap&#39;] === &#39;wrap-reverse&#39;) {<br>    const [crossEnd, crossStart] = [crossStart, crossEnd];<br>    crossSign = -1;<br>  } else {<br>    crossBase = 0;<br>    crossSign = +1;<br>  }</pre><pre>}</pre><h4>Collect elements into flex line</h4><p>Put the elements in one line if there is enough room or no-wrap, otherwise, start a new line.</p><p>There might be a special case: If the parent element does not have a main axis size (like width), the parent element is stretched by the child element. This mode is called the “auto main size”. In this case, the elements are gathered in one line.</p><p>./client/layout.js (continue with the previous code block)</p><pre>  // the special case<br>  let isAutoMainSize = false;<br>  if (!style[mainSize]) {<br>    // auto sizing<br>    elementStyle[mainSize] = 0;<br>    for (let i = 0; i &lt; elementItems.length; i++) {<br>      const itemStyle = getStyle(elementItems[i]);<br>      if (itemStyle[mainSize] !== null || itemStyle[mainSize] !== (void 0)) {<br>        elementStyle[mainSize] = elementStyle[mainSize] + itemStyle[mainSize];<br>      }<br>    }<br>    isAutoMainSize = true;<br>  }<br></pre><pre>  // normal case<br>  let flexLine = [];<br>  const flexLines = [flexLine];</pre><pre>  // mainSpace is the current remaining space, set it to the mainsize of the parent element<br>  let mainSpace = elementStyle[mainSize];<br>  let crossSpace = 0;</pre><pre>  // loop all the flex items<br>  for (let i = 0; i &lt; elementItems.length; i++) {<br>    const item = elementItems[i];<br>    const itemStyle = getStyle(item);<br><br>    if (itemStyle[mainSize] === null) {<br>      itemStyle[mainSize] = 0;<br>    }<br><br>    if (itemStyle.flex) { // one line<br>      flexLine.push(item);<br>    } else if (style[&#39;flex-wrap&#39;] === &#39;nowrap&#39; &amp;&amp; isAutoMainSize) {<br>      mainSpace -= itemStyle[mainSize];<br>      if (itemStyle[crossSize] !== null &amp;&amp; itemStyle[crossSize] !== (void 0)) {<br>        crossSpace = Math.max(crossSpace, itemStyle[crossSize]);<br>      }<br>      // because of &#39;nowrap&#39;<br>      flexLine.push(item);<br>    } else { // multiple lines<br>      // if the mainsize of the element is larger than it&#39;s parent element, it will be compressed to the same size as the parent element.<br>      if (itemStyle[mainSize] &gt; style[mainSize]) {<br>        itemStyle[mainSize] = style[mainSize];<br>      }<br>      // start a new line<br>      if (mainSpace &lt; itemStyle[mainSize]) {<br>        flexLine.mainSpace = mainSpace;<br>        flexLine.crossSpace = crossSpace;<br> <br>        // create the new line<br>        flexLine = [item];<br>        flexLines.push(flexLine);<br>        // reset these two props<br>        mainSpace = style[mainSize];<br>        crossSpace = 0;<br>      } else {<br>        flexLine.push(item);<br>      }<br><br>      if (itemStyle[crossSize] !== null &amp;&amp; itemStyle[crossSize] !== (void 0)) {<br>        crossSpace = Math.max(crossSpace, itemStyle[crossSize]);<br>      }<br>      mainSpace -= itemStyle[mainSize];<br>    }<br>  }<br>  flexLine.mainSpace = mainSpace;</pre><h4>Calculate the main axis</h4><p>Find all flex items and assign the remaining space mainspace in the main axis direction to these flex items proportionally. Special case: if the remaining space is a negative number (like in the “no-wrap” mode), set the size of the main axis of all flex items elements to 0, and compress the remaining elements proportionally.</p><p>If there are no flex items, calculate the position of each element according to the value of justify-content.</p><p>./client/layout.js (continue with the previous code block)</p><pre>if (style[&#39;flex-wrap&#39;] === &quot;nowrap&quot; || isAutoMainSize) {<br>    flexLine.crossSpace = (style[crossSize] !== undefined)<br>      ? style[crossSize]<br>      : crossSpace;<br>  } else {<br>    flexLine.crossSpace = crossSpace;<br>  }</pre><pre>if (mainSpace &lt; 0) {<br>    // overflow (happens only if container is single line), scale every item <br>    // the special case, proportional compression<br>    let scale = style[mainSize] / (style[mainSize] - mainSpace);<br>    let currentMain = mainBase;</pre><pre>for (let i = 0; i &lt; elementItems.length; i++) {<br>      const itemStyle = getStyle(elementItems[i]);<br>      if (itemStyle.flex) {<br>        // flex elements do not participate in proportional compression<br>        itemStyle[mainSize] = 0;<br>      }</pre><pre>      itemStyle[mainSize] = itemStyle[mainSize] * scale;</pre><pre>      // if the flex direction is row，this part is to calculate left and right after compression<br>      itemStyle[mainStart] = currentMain;<br>      itemStyle[mainEnd] = itemStyle[mainStart] + mainSign * itemStyle[mainSize];<br>      currentMain = itemStyle[mainEnd];<br>    }<br>  } else {<br>    // multiple lines<br>    // process each flex line<br>    flexLines.forEach(flexLine =&gt; {<br>      const mainSpace = flexLine.mainSpace;<br>      let itemStyle;<br>      let flexTotal = 0;<br>      for (let i = 0; i &lt; flexLine.length; i++) {<br>        itemStyle = getStyle(flexLine[i]);<br>        // find the flex items to get the value of flexTotal<br>        if ((itemStyle.flex !== null) &amp;&amp; (itemStyle.flex !== (void 0))) {<br>          flexTotal += itemStyle.flex;<br>          continue;<br>        }<br>      }</pre><pre>      // if flex elements exist, distribute mianSpace evenly to each flex element<br>      if (flexTotal &gt; 0) {<br>        let currentMain = mainBase;<br>        for (let i = 0; i &lt; flexLine.length; i++) {<br>          itemStyle = getStyle(flexLine[i]);<br>  <br>          if (itemStyle.flex) {<br>            itemStyle[mainSize] = (mainSpace / flexTotal) * itemStyle.flex;<br>          }          itemStyle[mainStart] = currentMain;<br>          itemStyle[mainEnd] = itemStyle[mainStart] + mainSign * itemStyle[mainSize];<br>          currentMain = itemStyle[mainEnd];<br>        }<br>      } else {<br>        // if there is no flex element, the remaining space in the main axis direction is allocated according to the rules of justifyContent<br>        let currentMain, gap;<br>        if (style[&#39;justify-content&#39;] === &#39;flex-start&#39;) {<br>          currentMain = mainBase;<br>          gap = 0; // there is no space between each element<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;flex-end&#39;) {<br>          currentMain = mainBase + mainSpace * mainSign;<br>          gap = 0;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;center&#39;) {<br>          currentMain = mainBase + mainSpace / 2 * mainSign;<br>          gap = 0;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;space-between&#39;) {<br>          currentMain = mainBase;<br>          gap = mainSpace / (elementItems.length - 1) * mainSign;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;space-around&#39;) {<br>          currentMain = gap / 2 + mainBase;<br>          gap = mainSpace / elementItems.length * mainSign;<br>        }<br>        if (style[&#39;justify-content&#39;] === &#39;space-evenly&#39;) {<br>          gap = mainSpace / (elementItems.length + 1) * mainSign<br>          currentMain = gap + mainBase<br>        }<br>        // calculate mainend based on mainstart and mainsize<br>        for (let i = 0; i &lt; flexLine.length; i++) {<br>          itemStyle[mainStart] = currentMain;<br>          itemStyle[mainEnd] = itemStyle[mainStart] + mainSign * itemStyle[mainSize];<br>          currentMain = itemStyle[mainEnd] + gap;<br>        }<br>      }<br>    })<br>  }</pre><p>If the flex-direction is “row”, at this point we have the value of width, left, and right. The next step is to calculate the cross axis to get the value of height, top, and bottom. When these are determined, the position of the element is also determined.</p><h4>Calculate the cross axis</h4><ul><li>the height of the line based on the height of the largest element</li><li>the specific position of elements can be calculated according to the value of flex-align and item-align</li></ul><p>./client/layout.js (continue with the previous code block)</p><pre>  if (!style[crossSize]) {<br>    // if the parent element has no crossSize, crossSpace will always be zero<br>    crossSpace = 0;<br>    elementStyle[crossSize] = 0;<br>    // add the height of the expansion<br>    for (let i = 0; i &lt; flexLines.length; i++) {<br>      elementStyle[crossSize] = elementStyle[crossSize] + flexLines[i].crossSpace;<br>    }<br>  } else {<br>    crossSpace = style[crossSize];<br>    for (let i = 0; i &lt; flexLines.length; i++) {<br>      crossSpace -= flexLines[i].crossSpace;<br>    }<br>  }</pre><pre>  // wrap-reverse    this affects crossBase<br>  if (style[&#39;flex-wrap&#39;] === &#39;wrap-reverse&#39;) {<br>    crossBase = style[crossSize];<br>  } else {<br>    crossBase = 0;<br>  }</pre><pre>  let lineSize = style[crossSize] / flexLines.length;<br>  let gap;<br><br>  if (style[&#39;align-content&#39;] === &#39;flex-start&#39;) {<br>    crossBase += 0;<br>    gap = 0;<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;flex-end&#39;) {<br>    crossBase += crossSpace * crossSign;<br>    gap = 0;<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;center&#39;) {<br>    crossBase += crossSpace * crossSign / 2;<br>    gap = 0;<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;space-between&#39;) {<br>    crossBase += 0;<br>    gap = crossSpace / (flexLines.length - 1);<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;space-around&#39;) {<br>    crossBase += crossSign * gap / 2;<br>    gap = crossSpace / (flexLines.length);<br>  }<br>  if (style[&#39;align-content&#39;] === &#39;stretch&#39;) {<br>    crossBase += 0;<br>    gap = 0;<br>  }</pre><pre>  flexLines.forEach(flexLine =&gt; {<br>    let lineCrossSize = style[&#39;align-content&#39;] === &#39;stretch&#39;<br>      ? flexLine.crossSpace + crossSpace / flexLines.length<br>      : flexLine.crossSpace;<br><br>    for (let i = 0; i &lt; flexLine.length; i++) {<br>      let itemStyle = getStyle(flexLine[i]);<br>      let align = itemStyle[&#39;align-self&#39;] || style[&#39;align-items&#39;];</pre><pre>      if (itemStyle[crossSize] === null) {<br>        itemStyle[crossSize] = align === &#39;stretch&#39;<br>          ? lineCrossSize<br>          : 0;<br>      }</pre><pre>      if (align === &#39;flex-start&#39;) {<br>        itemStyle[crossStart] = crossBase;<br>        itemStyle[crossEnd] = itemStyle[crossStart] + crossSign * itemStyle[crossSize];<br>      }<br>      if (align === &#39;flex-end&#39;) {<br>        itemStyle[crossStart] = crossBase + crossSign * lineCrossSize;<br>        itemStyle[crossEnd] = itemStyle[crossEnd] - crossSign * itemStyle[crossSize];<br>      }<br>      if (align === &#39;center&#39;) {<br>        itemStyle[crossStart] = crossBase + crossSign * lineCrossSize[crossSize] / 2;<br>        itemStyle[crossEnd] = itemStyle[crossStart] + crossSign * itemStyle[crossSize];<br>      }<br>      if (align === &#39;stretch&#39;) {<br>        itemStyle[crossStart] = crossBase;<br>        itemStyle[crossEnd] = crossBase + crossSign * ((itemStyle[crossSize] !== null &amp;&amp; itemStyle[crossSize] !== (void 0)) ? itemStyle[crossSize] : lineCrossSize);<br>        itemStyle[crossSize] = crossSign * (itemStyle[crossEnd] - itemStyle[crossStart]);<br>      }<br>    }<br>    crossBase += crossSign * (lineCrossSize + gap);<br>  })</pre><p>Now, we have a DOM tree with the position data!</p><h4>Send an HTML with flexbox layout from the server</h4><p>./server/server.js</p><pre>...<br>     <br>     response.end(<br>        `&lt;html maaa=a &gt;<br>      &lt;head&gt;<br>            &lt;style&gt;<br>      #container {<br>        width:500px;<br>        height:300px;<br>        display:flex;<br>        background-color:rgb(139,195,74);<br>      }<br>      #container #myid {<br>        width:200px;<br>        height:100px;<br>        background-color:rgb(255,235,59);<br>      }<br>      #container .c1 {<br>        flex:1;<br>        background-color:rgb(56,142,60);<br>      }<br>        &lt;/style&gt;<br>      &lt;/head&gt;<br>      &lt;body&gt;<br>        &lt;div id=&quot;container&quot;&gt;<br>            &lt;div id=&quot;myid&quot;/&gt;<br>            &lt;div class=&quot;c1&quot; /&gt;<br>        &lt;/div&gt;<br>      &lt;/body&gt;<br>      &lt;/html&gt;`);<br>      ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*mQGXL-0_kNnI5TW80jxZeg.png" /></figure><p>As you can see from the new DOM tree, the positions of the elements are already there. It’s ready to be rendered!</p><h3>Step five: render</h3><p>In the field of computer graphics, the term “render” specifically refers to the process of turning a model into a bitmap. Note that some frameworks, like React, call the “process from data to HTML code” as to render, which is different.</p><p>The bitmap here is a two-dimensional table built in memory, and the color corresponding to each pixel of a picture is saved.</p><p>Here we use the “images” library for painting in the viewport, it supports painting background-color, border, background-image, etc.</p><p>npm install images</p><h4>Render one flex item</h4><p>In the beginning, let’s try to render one flex item.</p><p>./client/render.js</p><pre>const images = require(&quot;images&quot;);</pre><pre>function render(viewport, element) {<br>  if (element.style) {<br>    let img = images(element.style.width, element.style.height);<br>    // to simplify, only deal with background color<br>    if (element.style[&quot;background-color&quot;]) {<br>      let color = element.style[&quot;background-color&quot;] || &quot;rgb(0, 0, 0)&quot;;<br>      color.match(/rgb\((\d+),(\d+),(\d+)\)/);<br>      img.fill(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3));<br>      viewport.draw(<br>        img,<br>        element.style.left || 0,<br>        element.style.top || 0<br>      );<br>    }<br>  }<br>}</pre><pre>module.exports = render;</pre><p>./client/index.js</p><pre>const net = require(&#39;net&#39;);<br>const images = require(&quot;images&quot;);<br>const parser = require(&#39;./parser&#39;);<br>const render = require(&quot;./render&quot;);</pre><pre>...</pre><pre>void async function () {<br>  const request = new Request({...});</pre><pre>  const response = await request.send();<br>  const dom = parser.parseHTML(response.body);</pre><pre>  const viewport = images(800, 600);<br>  render(viewport, dom.children[0].children[3].children[1].children[3]); // the element to render<br>  viewport.save(&#39;viewport.jpg&#39;);<br>}()</pre><p>Go check the viewport.jpg, we rendered the item out successfully!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*C--W4nSK0HxNZuMHyPPkdA.jpeg" /></figure><h4>Full rendering</h4><p>This step is quite easy, calling the render() method of the children elements recursively can render the whole DOM tree.</p><p>Text rendering is difficult, it relying on the font library to turn the font into a picture. We ignore it in our mini-browser project.</p><p>./client/render.js</p><pre>function render(viewport, element) {<br>  if (element.style) {<br>    ...<br>  }</pre><pre>  if (element.children) {<br>    for (const child of element.children) {<br>      render(viewport, child);<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sowzMWRazs0QMAWQ3dZhHg.jpeg" /></figure><p>Run the index.js and check the picture again, you’ll find that the elements are rendered perfectly.</p><p>Let’s change some flex rules to see whether the browser can handle it, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TbWTj_-TZHDxxI1EBOqMKw.png" /></figure><p>The answer is yes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0QnnmIFkQPx4uJy1nIhlTg.jpeg" /></figure><p>We have successfully developed a toy mini-browser that supports HTTP requests, HTML/CSS parsing, and flexbox layout.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ja34YXnWUZF40kwNx5adA.png" /></figure><p>After going through these steps, I hope you have a deeper understanding of how browsers works. If you want to view the complete code, please refer to this <a href="https://github.com/BeijiYang/mini-browser">repository</a>. The index.js in the client-side is separated into a few more files, but the basic structure remains.</p><pre>src<br>├── client<br>│   ├── index.js<br>│   ├── Request.js<br>│   ├── HTMLparser.js<br>│   ├── ResponseParser.js<br>│   ├── ChunkedBodyParser.js<br>│   ├── layout.js<br>│   ├── render.js<br>│   ├── package.json<br>│   ├── package-lock.json<br>│   └── viewport.jpg<br>└── server<br>    ├── server.js<br>    ├── package.json<br>    └── package-lock.json</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9aa63a32851e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/understanding-how-browsers-work-by-creating-one-9aa63a32851e">Understanding how browsers work by creating one</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</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 Beautiful Time-Series Visualisation with React-Vega]]></title>
            <link>https://medium.com/jobpal-dev/how-to-create-a-beautiful-time-series-visualisation-with-react-vega-3fd3e22ec445?source=rss-2902c8061ed9------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fd3e22ec445</guid>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[vegas]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Yujie Wang]]></dc:creator>
            <pubDate>Thu, 31 Oct 2019 10:55:48 GMT</pubDate>
            <atom:updated>2019-10-31T10:55:48.998Z</atom:updated>
            <content:encoded><![CDATA[<p>Vega is a powerful grammar for visualisation, but to use it in a real web app project, it is necessary to make subtle and important UX tweaks dynamically. In this article, we walk you through a time-series area plot with facets, and additional line-chart layer in a React.js project. Here are the topics we cover:</p><ul><li>Showing integers in the y-axis.</li><li>Showing more readable timestamps on the x-axis by dynamically switching between ordinal and temporal data types.</li><li>Adding a more readable and customizable color legend to a layered chart.</li><li>Including the chart in a React project, including all the above UX tweaks as well as showing only the SVG/PNG exports in the export widget.</li><li>Enabling dynamic resizing of the chart when the user changes window size.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*XHIGLTsshSYc37GZPF3_oA.gif" /></figure><h3>Libraries</h3><p>Open Google.com, search for “Vega”, and this is what you’ll see: <strong>Vega</strong>, <strong>Vega-Lite</strong>, <strong>Vega-Embed</strong>, <strong>React-Vega</strong>, so many libraries. If you don’t have much knowledge about them, you will get lost.</p><p>Don’t worry, below is the most simplified explanation:</p><ul><li><a href="https://vega.github.io/vega/"><strong>Vega</strong></a>: A visualization grammar. You can describe the chart using JSON, and get a Canvas or SVG. It is powerful and flexible.</li><li><a href="https://vega.github.io/vega-lite/"><strong>Vega-Lite</strong></a>: A high-level grammar for interactive charts and graphs, also JSON in Canvas/SVG out. Vega-Lite specifications can be compiled to Vega specifications. It is a convenient way to create a chart quickly.</li><li><a href="https://github.com/vega/vega-embed"><strong>Vega-Embed</strong></a>: A tool to embed the Vega/Vega-Lite chart into web pages.</li><li><a href="https://github.com/vega/react-vega/tree/master/packages/react-vega"><strong>React-Vega</strong></a>: A tool to help you use the Vega/Vega-Lite chart in a React project.</li></ul><p>Since Vega-Lite is quicker but not as powerful as Vega, you can first quickly express your idea using Vega-Lite, then edit/add more advanced functionality based on the Vega specifications generated from Vega-Lite.</p><h3>The chart</h3><p>Since most of the articles online focus on the bar chart as an example, in this post we will focus on making a good time-series area chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*c5u_i9wl_9tJBpKZtkinbg.png" /></figure><p>First, we start with a basic area chart. It shows the active users in the first week in October.</p><p>You can copy &amp; paste this JSON specification into the<a href="https://vega.github.io/editor/#/">Vega editor</a>.</p><pre>{<br>  &quot;$schema&quot;: &quot;https://vega.github.io/schema/vega-lite/v4.json&quot;,<br>  &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#0084FF&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>  &quot;encoding&quot;: {<br>    &quot;x&quot;: {<br>      &quot;field&quot;: &quot;date&quot;,<br>      &quot;type&quot;: &quot;temporal&quot;,<br>      &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>      &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;}<br>    },<br>    &quot;y&quot;: {<br>      &quot;field&quot;: &quot;active_users&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {&quot;title&quot;: &quot;Active Users&quot;}<br>    },<br>    &quot;opacity&quot;: {&quot;value&quot;: 1}<br>  },<br>  &quot;width&quot;: 400,<br>  &quot;height&quot;: 300,<br>  &quot;data&quot;: {<br>    &quot;values&quot;: [<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot;}<br>    ]<br>  },<br>  &quot;config&quot;: {}<br>}</pre><p>It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/448/1*ntoxb4Uxhgguj-AM7SGi7Q.png" /></figure><h3>Show integer labels in the y-axis</h3><p>As you may have noticed, the number of active users is pretty small. We do this to highlight one problem of Vega’s default behavior. The chart looks very good for larger numbers, but for smaller numbers, the labels of the y-axis become float numbers. You can edit the data in the Vega editor by yourself.</p><p>There is no “half of a user”, the labels are supposed to be integers.</p><p>According to the official documentation, we can use the format function d to make the labels integers.</p><pre>...<br> &quot;y&quot;: {<br>      &quot;field&quot;: &quot;active_users&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {<br>        &quot;title&quot;: &quot;Active Users&quot;,<br>        &quot;format&quot;: &quot;d&quot;<br>        }<br>    },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*vkua6Pd0uukbzb41CIQM2w.png" /></figure><p>Now the floats are gone but a new issue appears. Some labels are duplicated.</p><p>We need to explicitly set the visible axis tick values using values on the y-axis.</p><pre>...<br> &quot;y&quot;: {<br>      &quot;field&quot;: &quot;active_users&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {<br>        &quot;title&quot;: &quot;Active Users&quot;,<br>        &quot;format&quot;: &quot;d&quot;,<br>        &quot;values&quot;: [1,2]<br>        }<br>    },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*0v4V6l91o2knYTn1WDRaMA.png" /></figure><p>Now we get a proper y-axis. Notice that there is no 0 in the array, so we can omit the label when the data is empty.</p><p>The values will change when the data change, so it needs to be passed into the spec JSON in the React component dynamically. We will return to this later in the article.</p><h3>Show proper labels in the x-axis(time axis)</h3><p>Currently, the x-axis looks good. But if we minimize the amount of data, or increase the width of the chart, the same duplicate-issue occurs.</p><p>Let’s try to make the chart larger.</p><pre>&quot;width&quot;: 1200,<br>&quot;height&quot;: 600,</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uHAIfjbltKJWueKvfjn91Q.png" /></figure><p>Setting the type as <a href="https://vega.github.io/vega-lite/docs/type.html#ordinal">ordinal</a> can solve this problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQY9HpDqs24rGa2Ncf87ag.png" /></figure><p>But it is not a silver bullet: when the amount of data increases, too-crowded labels harms readability.</p><pre>...<br>  &quot;width&quot;: 400,<br>  &quot;height&quot;: 300,<br>  &quot;data&quot;: {<br>    &quot;values&quot;: [<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-08&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-09&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-10&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-11&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-12&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-13&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-14&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-15&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-16&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-17&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-18&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-19&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-20&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-21&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-22&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-23&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-24&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-25&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-26&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-27&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-28&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-29&quot;}<br>    ]<br>  },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*BhrD8XLZbGNhxb0j4ZxpNg.png" /></figure><p>So we need to add a condition: if the range is longer than 30 days, use temporal, otherwise, use ordinal.</p><p>For the sake of the user’s neck, let’s adjust the angle of the labels by setting labelAngle.</p><pre>const getDateXObj = rangeLen =&gt; ({<br>  field: &#39;date&#39;,<br>  type: `${rangeLen &gt; 30 ? &#39;temporal&#39; : &#39;ordinal&#39;}`,<br>  timeUnit: &#39;yearmonthdate&#39;,<br>  axis: {<br>    title: &#39;Date&#39;,<br>    labelAngle: -45,<br>  },<br>});</pre><p>If we only want to solve the labels-too-crowded problem, basically the labelAngle can do the job.</p><pre>...<br>&quot;x&quot;: {<br>    &quot;field&quot;: &quot;date&quot;,<br>    &quot;type&quot;: &quot;ordinal&quot;,<br>    &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>    &quot;axis&quot;: {<br>      &quot;title&quot;: &quot;Date&quot;,<br>      &quot;labelAngle&quot;: -45<br>    }<br> },</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*fNr_3j6pZBh9fryZ8fW5xg.png" /></figure><p>The true difference between temporal and ordinal is:</p><ul><li>The former puts the data on an <strong>incompressible</strong> timeline.</li><li>The latter only displays the existing data.</li></ul><p>The following two pictures can be used to illustrate the difference. Note that only one day is added to the data.</p><pre>&quot;values&quot;: [<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot;},<br>      {&quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot;},<br>      {&quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot;},<br>      {&quot;active_users&quot;: 2, &quot;date&quot;: &quot;2020-01-01&quot;} // happy new year~<br>    ]</pre><p><strong>temporal</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*2I_u6KGzmZbEvh3997LYfw.png" /></figure><p><strong>ordinal</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*SCdNXw5PbKOstEgnYIWPxA.png" /></figure><p>Now we already know how to make a single layer chart. What about multi layer chart?</p><h3>Multi-layer Chart</h3><p>There is nothing special about the multi-layer chart. All we need to do is to add a layer array. It is like a stack, we push the chart items in from the top.</p><p>To demonstrate a multi-layer chart, we add the &quot;user_comments&quot; in the previous data.</p><pre>...<br>&quot;data&quot;: {<br>  &quot;values&quot;: [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>  ]<br>},<br>...</pre><p>We can create a single layer “User Comments” chart using the same Vega-Lite grammar as the previous one. Just replacing certain items in the y-axis object is enough.</p><pre>...<br>&quot;mark&quot;: { &quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot; },<br>  &quot;encoding&quot;: {<br>    &quot;x&quot;: {<br>      &quot;field&quot;: &quot;date&quot;,<br>      &quot;type&quot;: &quot;ordinal&quot;,<br>      &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>       &quot;axis&quot;: { &quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45 }<br>    },<br>    &quot;y&quot;: {<br>      &quot;field&quot;: &quot;user_comments&quot;,<br>      &quot;type&quot;: &quot;quantitative&quot;,<br>      &quot;axis&quot;: {<br>        &quot;title&quot;: &quot;User Comments&quot;,<br>        &quot;format&quot;: &quot;d&quot;,<br>        &quot;values&quot;: [1, 2, 3]<br>      }<br>    }<br>  },<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*nr9NMof98U33K6lDlOkN3A.png" /></figure><p>Then we add a layer array. Push the &quot;User Comments&quot; chart object in this array. Nothing changed, it is still a single layer chart.</p><pre>...<br>&quot;layer&quot;:[<br>    {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;:{<br>           &quot;field&quot;: &quot;date&quot;,<br>           &quot;type&quot;: &quot;ordinal&quot;,<br>           &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>           &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>            &quot;field&quot;: &quot;user_comments&quot;,<br>            &quot;type&quot;: &quot;quantitative&quot;,<br>            &quot;axis&quot;: {<br>                &quot;title&quot;: &quot;User Comments&quot;,<br>                &quot;format&quot;: &quot;d&quot;,<br>                &quot;values&quot;: [1,2,3]<br>             }<br>          }<br>      }<br>    }<br>  ],<br>  ...</pre><p>What will happen if we push the “Active Users” object in this array, too?</p><pre>...<br>&quot;layer&quot;:[<br>    {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;:{<br>           &quot;field&quot;: &quot;date&quot;,<br>           &quot;type&quot;: &quot;ordinal&quot;,<br>           &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>           &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>            &quot;field&quot;: &quot;user_comments&quot;,<br>            &quot;type&quot;: &quot;quantitative&quot;,<br>            &quot;axis&quot;: {<br>                &quot;title&quot;: &quot;User Comments&quot;,<br>                &quot;format&quot;: &quot;d&quot;,<br>                &quot;values&quot;: [1,2,3]<br>             }<br>          }<br>      }<br>    },<br>    {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#0084FF&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;: {<br>          &quot;field&quot;: &quot;date&quot;,<br>          &quot;type&quot;: &quot;ordinal&quot;,<br>          &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>          &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>          &quot;field&quot;: &quot;active_users&quot;,<br>          &quot;type&quot;: &quot;quantitative&quot;,<br>          &quot;axis&quot;: {<br>          &quot;title&quot;: &quot;Active Users&quot;,<br>          &quot;format&quot;: &quot;d&quot;,<br>          &quot;values&quot;: [1,2]<br>          }<br>        }<br>      }<br>    }<br>  ],<br>  ...</pre><p>Here it is! A double layer chart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*5jFDKrimUfkf9ZswLUGFEQ.png" /></figure><h3>Add legend</h3><p>Although this chart looks pretty, it has a problem with clarity. Our user can not know which color indicates which data in a glance. Now is when we need to add legends in the chart.</p><p>There are several approaches to make it happen, here is my solution:</p><ul><li>using stroke to create the legend.</li><li>using legend to optimize the style.</li></ul><p>Add the stroke object in any chart object:</p><pre>...<br>  {<br>      &quot;mark&quot;: {&quot;type&quot;: &quot;area&quot;, &quot;color&quot;: &quot;#e0e0e0&quot;, &quot;interpolate&quot;: &quot;monotone&quot;},<br>      &quot;encoding&quot;: {<br>        &quot;x&quot;:{<br>           &quot;field&quot;: &quot;date&quot;,<br>           &quot;type&quot;: &quot;ordinal&quot;,<br>           &quot;timeUnit&quot;: &quot;yearmonthdate&quot;,<br>           &quot;axis&quot;: {&quot;title&quot;: &quot;Date&quot;, &quot;labelAngle&quot;: -45}<br>        },<br>        &quot;y&quot;: {<br>            &quot;field&quot;: &quot;user_comments&quot;,<br>            &quot;type&quot;: &quot;quantitative&quot;,<br>            &quot;axis&quot;: {<br>                &quot;title&quot;: &quot;User Comments&quot;,<br>                &quot;format&quot;: &quot;d&quot;,<br>                &quot;values&quot;: [1,2,3]<br>             }<br>          },<br>        &quot;stroke&quot;: {<br>          &quot;field&quot;: &quot;symbol&quot;,<br>          &quot;type&quot;: &quot;ordinal&quot;,<br>          &quot;scale&quot;: {<br>            &quot;domain&quot;: [&quot;User Comments&quot;, &quot;Active Users&quot;],<br>            &quot;range&quot;: [&quot;#e0e0e0&quot;, &quot;#0084FF&quot;]<br>          }<br>        }<br>      }<br>  },<br>    ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*AyK_HqzKF0HvOOTYMwrB7Q.png" /></figure><p>We get a lame legend in the right-top corner.</p><p>Let’s make it look a bit better! First, we add legend object in the top config object.</p><pre>...<br> &quot;legend&quot;: {<br>        &quot;offset&quot;: -106, // Adjust the horizontal distance of the legend<br>        &quot;title&quot;: null,<br>        &quot;padding&quot;: 5,<br>        &quot;strokeColor&quot;: &quot;#9e9e9e&quot;,<br>        &quot;strokeWidth&quot;: 2,<br>        &quot;symbolType&quot;: &quot;stroke&quot;,<br>        &quot;symbolOffset&quot;: 0,<br>        &quot;symbolStrokeWidth&quot;: 10,<br>        &quot;labelOffset&quot;: 0,<br>        &quot;cornerRadius&quot;: 10,<br>        &quot;symbolSize&quot;: 100,<br>        &quot;clipHeight&quot;: 20<br>    }<br>   ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/439/1*vPJmJH1XyEArEFYI-fpA0w.png" /></figure><p>Already it looks so much better.</p><p>Since we already have the legend, we can safely get rid of the labels on the y-axis. Just delete the title of y.axis object, or leave it empty.</p><p>When the amount of the layer grows, we can also use both the area chart and the line chart at the same time, just like the example down blew. Looks nice, doesn’t it?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*in9UfhnfvWsOqj6Ff22TkA.png" /></figure><h3>Display Vega-Lite chart in the React project</h3><p>Install the react-vega library.</p><pre>npm install react vega vega-lite react-vega --save</pre><p>First, let’s simply put our chart above in the React project.</p><pre>...<br>import { Vega } from &#39;react-vega&#39;;<br><br><br>const spec = {<br>  $schema: &#39;https://vega.github.io/schema/vega-lite/v4.json&#39;,<br>  title: &#39;Demo Chart&#39;, <br>  layer: [<br>    {<br>      mark: { type: &#39;area&#39;, color: &#39;#e0e0e0&#39;, interpolate: &#39;monotone&#39; },<br>      encoding: {<br>        x: {<br>          field: &#39;date&#39;,<br>          type: &#39;ordinal&#39;,<br>          timeUnit: &#39;yearmonthdate&#39;,<br>          axis: { title: &#39;Date&#39;, labelAngle: -45 },<br>        },<br>        y: {<br>          field: &#39;user_comments&#39;,<br>          type: &#39;quantitative&#39;,<br>          axis: {<br>            title: &#39;User Comments&#39;,<br>            format: &#39;d&#39;,<br>            values: [1, 2, 3],<br>          },<br>        },<br>        stroke: {<br>          field: &#39;symbol&#39;,<br>          type: &#39;ordinal&#39;,<br>          scale: {<br>            domain: [&#39;User Comments&#39;, &#39;Active Users&#39;],<br>            range: [&#39;#e0e0e0&#39;, &#39;#0084FF&#39;],<br>          },<br>        },<br>      },<br>    },<br>    {<br>      mark: { type: &#39;area&#39;, color: &#39;#0084FF&#39;, interpolate: &#39;monotone&#39; },<br>      encoding: {<br>        x: {<br>          field: &#39;date&#39;,<br>          type: &#39;ordinal&#39;,<br>          timeUnit: &#39;yearmonthdate&#39;,<br>          axis: { title: &#39;Date&#39;, labelAngle: -45 },<br>        },<br>        y: {<br>          field: &#39;active_users&#39;,<br>          type: &#39;quantitative&#39;,<br>          axis: {<br>            title: &#39;Active Users&#39;,<br>            format: &#39;d&#39;,<br>            values: [1, 2],<br>          },<br>        },<br>      },<br>    },<br>  ],<br>  config: {<br>    legend: {<br>      offset: -106, // Adjust the horizontal distance of the legend<br>      title: null,<br>      padding: 5,<br>      strokeColor: &#39;#9e9e9e&#39;,<br>      strokeWidth: 2,<br>      symbolType: &#39;stroke&#39;,<br>      symbolOffset: 0,<br>      symbolStrokeWidth: 10,<br>      labelOffset: 0,<br>      cornerRadius: 10,<br>      symbolSize: 100,<br>      clipHeight: 20,<br>    },<br>  },<br>};<br><br>const data = [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>    ]<br><br>...<br><br>return (<br>  ...<br><br>    &lt;Vega<br>      spec={{<br>        ...spec,<br>         width: 400,<br>         height: 300,<br>         data: { values: data },<br>       }}<br>      /&gt;<br>  ...<br>)</pre><p>Then we can make it chart better by doing some refactoring work.</p><ul><li>the condition function on the x-axis we have talked about earlier.</li><li>a new getSpec function to return the spec object.</li><li>a function to generate the values array based on the biggest key value from the data.</li></ul><pre>import React from &#39;react&#39;;<br>import { Vega } from &#39;react-vega&#39;;<br><br>// chart config<br>const jobpalBlue = &#39;#e0e0e0&#39;;<br>const jobpalLightGrey = &#39;#0084FF&#39;;<br>const jobpalDarkGrey = &#39;#9e9e9e&#39;;<br><br>const areaMark = {<br>  type: &#39;area&#39;,<br>  color: jobpalBlue,<br>  interpolate: &#39;monotone&#39;,<br>};<br><br>const getDateXObj = rangeLen =&gt; ({<br>  field: &#39;date&#39;,<br>  type: `${rangeLen &gt; 30 ? &#39;temporal&#39; : &#39;ordinal&#39;}`,<br>  timeUnit: &#39;yearmonthdate&#39;,<br>  axis: {<br>    title: &#39;Date&#39;,<br>    labelAngle: -45,<br>  },<br>});<br><br>const getQuantitativeYObj = (field, title, values) =&gt; ({<br>  field,<br>  type: &#39;quantitative&#39;,<br>  axis: {<br>    title,<br>    format: &#39;d&#39;,<br>    values,<br>  },<br>});<br><br>const legendConfig = {<br>  title: null,<br>  offset: -106,<br>  padding: 5,<br>  strokeColor: jobpalDarkGrey,<br>  strokeWidth: 2,<br>  symbolType: &#39;stroke&#39;,<br>  symbolOffset: 0,<br>  symbolStrokeWidth: 10,<br>  labelOffset: 0,<br>  cornerRadius: 10,<br>  symbolSize: 100,<br>  clipHeight: 20,<br>};<br><br>const getSpec = (yAxisValues = [], rangeLen = 0) =&gt; ({<br>  $schema: &#39;https://vega.github.io/schema/vega-lite/v4.json&#39;,<br>  title: &#39;Demo Chart&#39;,<br>  layer: [<br>    {<br>      mark: {<br>        ...areaMark,<br>        color: jobpalLightGrey,<br>      },<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;user_comments&#39;, &#39;&#39;, yAxisValues),<br>        stroke: {<br>          field: &#39;symbol&#39;,<br>          type: &#39;ordinal&#39;,<br>          scale: {<br>            domain: [&#39;User Comments&#39;, &#39;Active Users&#39;],<br>            range: [jobpalLightGrey, jobpalBlue],<br>          },<br>        },<br>      },<br>    }, {<br>      mark: areaMark,<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;active_users&#39;, &#39;&#39;, yAxisValues),<br>      },<br>    },<br>  ],<br>  config: {<br>    legend: legendConfig,<br>  },<br>})<br><br>const data = [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>  ]</pre><pre>// React component</pre><pre>const App = () =&gt; {<br>  // get max value from data arary<br>  const yAxisMaxValueFor = (...keys) =&gt; {<br>    const maxList = keys.map(key =&gt; data.reduce(<br>         // find the item containing the max value<br>        (acc, cur) =&gt; (cur[key] &gt; acc[key] ? cur : acc)<br>      )[key]<br>    );<br>    return Math.max(...maxList);<br>  };<br><br>  const yAxisValues = Array.from(<br>    { length: yAxisMaxValueFor(&#39;active_users&#39;, &#39;user_comments&#39;) },<br>  ).map((v, i) =&gt; (i + 1));<br><br><br>  const spec = getSpec(yAxisValues, data.length);<br><br>  return (<br>    &lt;div className=&quot;App&quot;&gt;<br>      &lt;Vega<br>        spec={{<br>          ...spec,<br>          autosize: &#39;fit&#39;,<br>          resize: true,<br>          contains: &#39;padding&#39;,<br>          width: 400,<br>          height: 300,<br>          data: { values: data },<br>        }}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default App;</pre><p>So far, we have successfully introduced the charts described by Vega-Lite in the React project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*Wu-edUjnQ4IFc_LAbjJ4QA.png" /></figure><h3>Manage the widget</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*gyqXPVKvcY9KkjVwG6k0Ig.png" /></figure><p>On the right-top corner, there is a widget. Click it and you’ll see all the actions you can take: download the chart in different formats, view source/complied Vega, open in Vega editor.</p><p>The last three items should only appear in the development stage. In the production, we leave the first two download options, and it would be better if we can specify the download file name instead of a default one.</p><p>Luckily, it can be done using React-Vega. This is an advantage of React-Vega, which supports several configuration features of Vega-Embed, as described in the <a href="https://vegawidget.github.io/vegawidget/reference/vega_embed.html">documentation</a>.</p><p>Here, we only need two more configurations: actions and downloadFileName. The former uses Boolean values to control exported functions, the latter specifies the name of the downloaded file.</p><pre>...<br>  &lt;Vega<br>    spec={ ... }<br>    actions={{<br>        export: true,<br>        source: false,<br>        compiled: false,<br>        editor: false,<br>      }}<br>      downloadFileName={&#39;Just Name It&#39;}<br>    /&gt;<br>  ...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*CqP4wIb1KguwM5TF3GbwAQ.png" /></figure><h3>Resize</h3><p>In a real project, we have to make sure that the size of the chart always fits the browser window. Currently the chart doesn’t rescale, but we can make it happen by letting the React component take charge of the width/height of the chart.</p><p>Basically:</p><ul><li>mange width/height in state.</li><li>repaint the chart by using setState.</li><li>in the lifecycle method, set event listener to listen to resize event.</li><li>get the current right width/height value by using CSS and ref in the wrapper div.</li></ul><p>Talk is cheap, here is the code.</p><pre>import React from &#39;react&#39;;<br>import { Vega } from &#39;react-vega&#39;;<br><br>// chart config<br>const jobpalBlue = &#39;#e0e0e0&#39;;<br>const jobpalLightGrey = &#39;#0084FF&#39;;<br>const jobpalDarkGrey = &#39;#9e9e9e&#39;;<br><br>const areaMark = {<br>  type: &#39;area&#39;,<br>  color: jobpalBlue,<br>  interpolate: &#39;monotone&#39;,<br>};<br><br>const getDateXObj = rangeLen =&gt; ({<br>  field: &#39;date&#39;,<br>  type: `${rangeLen &gt; 30 ? &#39;temporal&#39; : &#39;ordinal&#39;}`,<br>  timeUnit: &#39;yearmonthdate&#39;,<br>  axis: {<br>    title: &#39;Date&#39;,<br>    labelAngle: -45,<br>  },<br>});<br><br>const getQuantitativeYObj = (field, title, values) =&gt; ({<br>  field,<br>  type: &#39;quantitative&#39;,<br>  axis: {<br>    title,<br>    format: &#39;d&#39;,<br>    values,<br>  },<br>});<br><br>const legendConfig = {<br>  title: null,<br>  offset: -106,<br>  padding: 5,<br>  strokeColor: jobpalDarkGrey,<br>  strokeWidth: 2,<br>  symbolType: &#39;stroke&#39;,<br>  symbolOffset: 0,<br>  symbolStrokeWidth: 10,<br>  labelOffset: 0,<br>  cornerRadius: 10,<br>  symbolSize: 100,<br>  clipHeight: 20,<br>};<br><br>const getSpec = (yAxisValues = [], rangeLen = 0) =&gt; ({<br>  $schema: &#39;https://vega.github.io/schema/vega-lite/v4.json&#39;,<br>  title: &#39;Demo Chart&#39;,<br>  layer: [<br>    {<br>      mark: {<br>        ...areaMark,<br>        color: jobpalLightGrey,<br>      },<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;user_comments&#39;, &#39;&#39;, yAxisValues),<br>        stroke: {<br>          field: &#39;symbol&#39;,<br>          type: &#39;ordinal&#39;,<br>          scale: {<br>            domain: [&#39;User Comments&#39;, &#39;Active Users&#39;],<br>            range: [jobpalLightGrey, jobpalBlue],<br>          },<br>        },<br>      },<br>    }, {<br>      mark: areaMark,<br>      encoding: {<br>        x: getDateXObj(rangeLen),<br>        y: getQuantitativeYObj(&#39;active_users&#39;, &#39;&#39;, yAxisValues),<br>      },<br>    },<br>  ],<br>  config: {<br>    legend: legendConfig,<br>  },<br>})<br><br>const data = [<br>    { &quot;user_comments&quot;: 0, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-01&quot; },<br>    { &quot;user_comments&quot;: 3, &quot;active_users&quot;: 2, &quot;date&quot;: &quot;2019-10-02&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-03&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-04&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-05&quot; },<br>    { &quot;user_comments&quot;: 1, &quot;active_users&quot;: 0, &quot;date&quot;: &quot;2019-10-06&quot; },<br>    { &quot;user_comments&quot;: 2, &quot;active_users&quot;: 1, &quot;date&quot;: &quot;2019-10-07&quot; }<br>  ];<br><br>// get max value from data arary<br>const yAxisMaxValueFor = (...keys) =&gt; {<br>  const maxList = keys.map(key =&gt; data.reduce(<br>    // find the item containing the max value<br>    (acc, cur) =&gt; (cur[key] &gt; acc[key] ? cur : acc)<br>  )[key]<br>  );<br>  return Math.max(...maxList);<br>};<br><br>const { addEventListener, removeEventListener } = window;<br><br>class App extends React.Component {<br><br>  state = {<br>    width: 400,<br>    height: 300,<br>  }<br><br>  componentDidMount() {<br>    addEventListener(&#39;resize&#39;, this.resizeListener, { passive: true, capture: false });<br>  }<br><br>  componentWillUnmount() {<br>    removeEventListener(&#39;resize&#39;, this.resizeListener, { passive: true, capture: false });<br>  }<br><br>  resizeListener = () =&gt; {<br>    if (!this.chartWrapper) return;<br><br>    const child = this.chartWrapper.querySelector(&#39;div&#39;);<br>    child.style.display = &#39;none&#39;;<br><br>    const {<br>      clientWidth,<br>      clientHeight: height,<br>    } = this.chartWrapper;<br>    const width = clientWidth - 40; // as padding: &quot;0 20px&quot;<br>    this.setState({ width, height });<br><br>    child.style.display = &#39;block&#39;;<br>  }<br><br>  refChartWrapper = el =&gt; {<br>    this.chartWrapper = el<br>    if (el) this.resizeListener();<br>  }<br><br>  yAxisValues = Array.from(<br>    { length: yAxisMaxValueFor(&#39;active_users&#39;, &#39;user_comments&#39;) },<br>  ).map((v, i) =&gt; (i + 1));<br><br>  render() {<br>    const { <br>      state: { width, height},<br>      yAxisValues,<br>    } = this;<br><br>    const spec = getSpec(yAxisValues, data.length);<br><br>    return (<br>      &lt;div<br>        ref={this.refChartWrapper}<br>        style={{ margin: &#39;10vh 10vw&#39;, width: &#39;80vw&#39;, height: &#39;50vh&#39; }}<br>        &gt;<br>        &lt;Vega<br>          spec={{<br>            ...spec,<br>            autosize: &#39;fit&#39;,<br>            resize: true,<br>            contains: &#39;padding&#39;,<br>            width,<br>            height,<br>            data: { values: data },<br>          }}<br>          actions={{<br>            export: true,<br>            source: false,<br>            compiled: false,<br>            editor: false,<br>          }}<br>          downloadFileName={&#39;Just Name It&#39;}<br>        /&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}<br><br>export default App;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*XHIGLTsshSYc37GZPF3_oA.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fd3e22ec445" width="1" height="1" alt=""><hr><p><a href="https://medium.com/jobpal-dev/how-to-create-a-beautiful-time-series-visualisation-with-react-vega-3fd3e22ec445">How to Create a Beautiful Time-Series Visualisation with React-Vega</a> was originally published in <a href="https://medium.com/jobpal-dev">jobpal has been acquired by SmartRecruiters!</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>