<?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 Babette Landmesser on Medium]]></title>
        <description><![CDATA[Stories by Babette Landmesser on Medium]]></description>
        <link>https://medium.com/@babettelandmesser?source=rss-621c4a28ffcb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Pbwhties56Rd4ITpwJygJA.jpeg</url>
            <title>Stories by Babette Landmesser on Medium</title>
            <link>https://medium.com/@babettelandmesser?source=rss-621c4a28ffcb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:10:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@babettelandmesser/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[Corona, soccer and missing fans in the stadium]]></title>
            <link>https://medium.com/data-smart-services/corona-soccer-and-missing-fans-in-the-stadium-679d4afb5b85?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/679d4afb5b85</guid>
            <category><![CDATA[soccer]]></category>
            <category><![CDATA[corona]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 12:51:11 GMT</pubDate>
            <atom:updated>2021-06-02T13:01:11.642Z</atom:updated>
            <content:encoded><![CDATA[<h4>What effect do the missing fans have on results in Europe’s largest soccer leagues?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JcxiPiJQ8gKCpD1NXtFoDw.jpeg" /><figcaption>unsplash.com, Vienna Reyes</figcaption></figure><p>One afternoon in March 2021, a colleague from <a href="https://www.mediaman.com/">mediaman</a> and I asked ourselves, if the missing fans in the stadium do have an impact on the results in Europe’s largest soccer leagues — primarily in the German Bundesliga.</p><p>Luckily we’re both developers and soccer fans, so we immediately started collecting data of the Bundesliga and some other European leagues. Fetching, storing, analyzing and displaying data is our daily work at mediaman.</p><blockquote>Note that this article will cover some conceptional <strong>nerd stuff</strong> as well as the <strong>results</strong> that I see in our <strong>analysis</strong>.</blockquote><h3>The background</h3><p>Since March 2020 the stadiums all over Europe were quite empty due to the Corona pandemic. In Germany the Bundesliga stopped playing for a while and restarted in May but without any fan in the stadium.</p><p>Season 2020/2021 started quite normal in September but still without fans. After a very bad first half of the season of my personal favorite club, we had to investigate further and see if the results of the matches changed.</p><h3>The nerd stuff</h3><p>In this case, collecting the data was quite easy. First, we fetched the results from previous seasons for later comparison between “Non-Corona-Seasons” and “Corona-Seasons”. Then, every monday after the matches in the Bundesliga were finished, we fetched the results by simply requesting data from an API. Next, we stored all results in a DynamoDB table in the AWS cloud.</p><p>The rest is pretty easy as well: We created a node.js backend with API Gateway and Lambda functions to enable the frontend application to fetch these results. In the frontend, the data is grouped by wins, draws and defeats of the matches at home and simply displayed with a D3.js chart. For this case we decided to use a horizontal stacked bar chart to make comparison between seasons easier to read. Because we only want to compare the results per season, the x- and y-axes are simple: The x-axis just displays numbers between 0 and about 300 — as there are about 300 matches in German Bundesliga per season (note: this can change for other European leagues). The y-axis displays the seasons.</p><p>The result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PnIk_mCZuusbk7AbVZdxSg.png" /><figcaption>Displaying wins, draws and loses at home per season for German Bundesliga</figcaption></figure><h3>Thesis</h3><p><em>The results will change in a way that more teams would lose matches at home, because the away team does not have to fight against both: 11 players in the home team and the cheering fans.</em></p><h4>Setup</h4><p>For better comparison, we decided to display data from two seasons before Corona changed our way of living until now. <br>Remember that everything changed midway through season 2019/2020.</p><h3>Less loses, more wins at home</h3><p>When comparing season 2019/2020 it’s obvious that something had happened. There are about 20% more wins at home (for the home team) than in both seasons before. Also, around 11% less loses at home.</p><p>Comparing season 2020/2021 with season 2019/2020 the results seem to “normalize” again. The 20% more wins at home are nearly gone and the 11% less loses at home reduced to about 7% less loses at home. Hence, there were more draws at home than in season 2019/2020 and even 2018/2019.</p><p>But when looking at season 2018/2019 and 2020/2021, the difference is minimal. The wins at home are about the same, a few more draws at home and a few less loses at home but nothing really noticeable.</p><h4>Fans do not have an impact on the results?!</h4><p>Seeing this analysis, it seems that fans at home do not really make an impact on the home teams result.</p><p>For me, as I had experienced thrilling matches at the end of the season, seeing my team fighting against going down to league 2, cheering 90 minutes for my team and finally seeing them win at home, makes me feel weird about these results. Does that mean that me, as a season card holder, am nearly unimportant for my team to win or lose at home?</p><h3>Another view</h3><p>With this in mind, I started reflecting these results and trying to get deeper into analysis. There are studies which quote that there is a home advantage in sports (e.g. <a href="https://link.springer.com/article/10.2165/00007256-199928040-00001">this one</a>) — for example the crowd influencing the referees and also pushing the teams. <br><a href="https://psychology.iresearchnet.com/papers/home-advantage/">Other papers</a> also quote that there are a lot of reasons for the home advantage. From less travel time to higher comfort zone, the whole surrounding is the basis for a better physical and mental well-being of the players.</p><p>But this does not explain the difference between season 2019/2020 and the previous and next season. My <strong>personal</strong> assumption is: Because the lockdown occurred right in the middle of the season, the teams had no time to get used to empty stadiums. Hence, one factor of all the home advantage factors changed. To prove this thesis, another analysis of data would be needed. The distribution of the home wins, draws and loses over time in regard of the Corona pandemic should be analyzed. When did the wins increased — during the complete seasons or after Corona lockdown?</p><p>Coming back to my thesis for the changes only happening in 2019/2020: After the season 2019/2020 was finished and all the players and staff were to some extend “used” to empty stadiums, the new season 2020/2021 felt a bit more “normal” or at least empty stadiums weren’t a new phenomenon. This would explain the quite “normalized” results in the past season.</p><h3>Final words</h3><p>I am a bit disappointed about the results of this data analysis as I hoped to see our thesis being proved — and as a soccer fan I would’ve liked to see the importance of the fans in the stadium. But obviously that didn’t turned out. Anyway, fans belong into the stadium and the results just state that the teams are good at adapting when it’s about to get used to new circumstances.</p><p>Nevertheless, I’m pretty sure that all sports fans around the globe can’t wait to return to the stadiums, cheering for their teams and getting back to normal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=679d4afb5b85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-smart-services/corona-soccer-and-missing-fans-in-the-stadium-679d4afb5b85">Corona, soccer and missing fans in the stadium</a> was originally published in <a href="https://medium.com/data-smart-services">Data &amp; Smart Services</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a radar diagram with d3.js]]></title>
            <link>https://medium.com/create-code/build-a-radar-diagram-with-d3-js-9db6458a9248?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9db6458a9248</guid>
            <category><![CDATA[diagrams]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[radar]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Fri, 08 Jan 2021 08:56:29 GMT</pubDate>
            <atom:updated>2021-01-08T08:56:29.201Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this tutorial I am going to show you how to create a radar diagram with random dots within 4 segments. Each dot will be assigned to a quadrant of the radar.</h4><p>At <a href="https://www.mediaman.com/">mediaman</a>, we recently launched the very first and still very rough MVP of our <a href="https://data-radar.mediaman.com/">smart data radar</a>. With this small application we are presenting tools and techniques around data science in quadrants. We rate the different possibilities by our day-to-day usage up to „we have heard of it but have not yet tried it“. For that, we divided each quadrant into four rings holding our evaluation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qPnHjGGpFS_5pF1yzIvVyA.png" /><figcaption>mediaman’s Smart Data Radar</figcaption></figure><p>Now, I am going to explain how you are able to create your own radar based on this layout by using the JavaScript library D3.</p><blockquote>I prefer using TypeScript over Vanilla JS simply because I am used to TS.</blockquote><h3>Step 1: Install dependencies</h3><p>Of course we need to install our dependencies via npm (or yarn). Run</p><pre>npm install — save d3</pre><p>Next add the following devDependencies to your package.json and run</p><pre>npm i </pre><p>afterwards.</p><pre>&quot;devDependencies&quot;: {<br>    &quot;@babel/core&quot;: &quot;^7.4.5&quot;,<br>    &quot;@babel/preset-env&quot;: &quot;^7.4.5&quot;,<br>    &quot;@types/d3&quot;: &quot;^6.2.0&quot;,<br>    &quot;autoprefixer&quot;: &quot;^9.1.3&quot;,<br>    &quot;babel-loader&quot;: &quot;^8.0.6&quot;,<br>    &quot;copy-webpack-plugin&quot;: &quot;^6.4.0&quot;,<br>    &quot;core-js&quot;: &quot;^3.1.4&quot;,<br>    &quot;css-loader&quot;: &quot;^3.0.0&quot;,<br>    &quot;extract-loader&quot;: &quot;^2.0.1&quot;,<br>    &quot;file-loader&quot;: &quot;^2.0.0&quot;,<br>    &quot;node-sass&quot;: &quot;^4.9.3&quot;,<br>    &quot;postcss-cli&quot;: &quot;^6.0.0&quot;,<br>    &quot;postcss-loader&quot;: &quot;^3.0.0&quot;,<br>    &quot;regenerator-runtime&quot;: &quot;^0.13.2&quot;,<br>    &quot;sass-loader&quot;: &quot;^7.1.0&quot;,<br>    &quot;style-loader&quot;: &quot;^0.23.1&quot;,<br>    &quot;ts-loader&quot;: &quot;^8.0.4&quot;,<br>    &quot;ts-node&quot;: &quot;^9.0.0&quot;,<br>    &quot;typescript&quot;: &quot;^4.0.3&quot;,<br>    &quot;webpack&quot;: &quot;^4.35.0&quot;,<br>    &quot;webpack-cli&quot;: &quot;^3.3.5&quot;,<br>    &quot;webpack-dev-server&quot;: &quot;^3.7.2&quot;<br>},</pre><p>I’m going to compile the TypeScript via Babel and Webpack, including styles as well.</p><h3>Step 2: Setup your project and implement webpack and TypeScript</h3><p><a href="https://gist.github.com/babette-landmesser/8167698c2bf3785afef779b83978574b">My personal webpack file can be found here.</a></p><p>Create an <em>index.html</em> and a <em>main.ts</em> file. Paste the following minimum HTML code into your file:</p><pre>&lt;div class=”techradar__chart”&gt;<br>  &lt;div class=”chart”&gt;<br>    &lt;svg id=”radar”&gt;&lt;/svg&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Here, we have some containers for our individual use: In our <em>.chart</em> container we’re adding the SVG element for later extending it via D3.</p><h3>Step 3: Extend the SVG with some basic stuff</h3><p>In this part, we’re going to set our D3 domain, the axes and our range. Remember, we want to display 4 circles and always start in the middle.</p><pre>const svgOuter = d3.select(&#39;#radar&#39;),<br>    margin = {top: 20, right: 20, bottom: 20, left: 20},<br>    width = 900,<br>    height = 900,<br>    domainwidth = width - margin.left - margin.right,<br>    domainheight = height - margin.top - margin.bottom,<br>    tooltip = d3.select(&#39;.tooltip&#39;);<br><br>svgOuter.attr(&#39;viewBox&#39;, &#39;0 0 &#39; + (width + margin.left + margin.right) + &#39; &#39; + (height + margin.top + margin.bottom));<br><br>const svg = svgOuter.append(&#39;g&#39;).style(&#39;transform&#39;, &#39;translate(&#39; + margin.left + &#39;px, &#39; + margin.top + &#39;px)&#39;)<br><br>const x = d3.scaleLinear()<br>    .domain([-4, 4])<br>    .range([0, domainwidth]);<br>const y = d3.scaleLinear()<br>    .domain([-4, 4])<br>    .range([domainheight, 0]);<br><br>const xAxis = svg.append(&#39;g&#39;)<br>    .attr(&#39;class&#39;, &#39;x-axis&#39;)<br>    .attr(&#39;transform&#39;, &#39;translate(0,&#39; + y.range()[0] / 2 + &#39;)&#39;);<br><br>xAxis.call(d3.axisBottom(x).ticks(6))<br>    .call(g =&gt; g.selectAll(&#39;.tick text&#39;).remove())<br>    .call(g =&gt; g.selectAll(&#39;.tick line&#39;).remove())<br>    .call(g =&gt; g.selectAll(&#39;.domain&#39;).remove());<br><br>svg.append(&#39;g&#39;)<br>    .attr(&#39;class&#39;, &#39;y-axis&#39;)<br>    .attr(&#39;transform&#39;, &#39;translate(&#39; + x.range()[1] / 2 + &#39;, 0)&#39;)<br>    .call(d3.axisLeft(y).ticks(6))<br>    .call(g =&gt; g.selectAll(&#39;.tick text&#39;).remove())<br>    .call(g =&gt; g.selectAll(&#39;.tick line&#39;).remove())<br>    .call(g =&gt; g.selectAll(&#39;.domain&#39;).remove());</pre><p>The radar has a value range from -4 to 4 on both axes. That allows us to put four circles on it: The inner circle has a radius of 1, the second of 2, .. and so on.</p><blockquote>In case you just copied the code above, you may see nothing now as I remove the complete axis texts and lines. But that doesn’t matter — we will create the circles shortly.</blockquote><h3>Excursion: Some theoretical maths stuff</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfwf8tPN29gPPACIbSCJtA.jpeg" /></figure><p>Since we want to differentiate each quadrant with another color, we need to calculate the arc. This is done via the radius of this ring. The formula for this part is:</p><p><strong>2*π*radius * (degree / 360)</strong></p><p>In our case this is quite simple as the degree is always 90. As you will see later, D3 already has a function for this part.</p><p>For the dot calculation we need to know several parts about how to calculate with and within circles.</p><p>First of all, we should keep in mind that circles are usually calculated with degrees. But for our „coordinate system“ we need to calculate with radian measure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QKnihWAXeGo3HzzfZRbrhQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LeI72q5VnqNqxyYbI688qw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qVoB27LdnrXIhZGzODqzag.jpeg" /></figure><p><strong>1° = 1 * (π/ 180)</strong> <br><strong>30° = 30 * (π/ 180)</strong></p><p>Turning that around for getting our angle we calculate:</p><p><strong>α = DEGREEVALUE * π / 180</strong></p><p>To get the x- and y-coordinates in our system, sinus and cosine come into play.</p><p><strong>x = cos(α) </strong>while<strong> y = sin(α)</strong></p><p>Hence, for all dot calculation we can combine the radius with sinus and cosine to get the exact x and y values:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RuCrhgxaK4-i30u48tbvTw.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Ve9tkDK_TMkBu9hgb701g.jpeg" /></figure><p>At last, remember that we want to fill all four quadrants. Therefore, it might be easy to calculate with some kind of shift or offset.</p><p>Remember, 1/4 — or 90deg — of a circle is <strong>1/2π</strong>.</p><p>Well, that’s the basics.</p><h3>Step 4: Creating the radar circles</h3><p>First of all, we need to draw 4 arcs of 90 degree. Luckily, D3 already brings a function called <em>arc()</em>. With four chained methods we’re able to draw arcs for all four rings in all four quadrants:</p><pre>const arcGen = (innerRadius, outerRadius, startAngle, endAngle) =&gt; d3.arc()<br>    .innerRadius(innerRadius)<br>    .outerRadius(outerRadius)<br>    .startAngle(startAngle)<br>    .endAngle(endAngle);</pre><p>In the example from mediaman you can see that the outer circles are thinner than the inner ones. This is the reason for adding innerRadius and outerRadius here. StartAngle and endAngle will be multiples from 90: 0–90, 90–180, 180–270, 270–360 — for each quadrant.</p><p>Then, I also extracted the calculation for all four circles per quadrant into functions:</p><pre>const innerFirstCircle = (startAngle: number, endAngle: number) =&gt; {<br>    return arcGen((domainheight / 8) + 8, (domainheight / 8) - 8, startAngle, endAngle);<br>};</pre><pre>const innerSecondCircle = (startAngle: number, endAngle: number) =&gt; {<br>    return arcGen((domainheight / 4) + 6, (domainheight / 4) - 6, startAngle, endAngle);<br>};</pre><pre>const innerThirdCircle = (startAngle: number, endAngle: number) =&gt; {<br>    return arcGen((domainheight / 8 * 3) + 4, (domainheight / 8 * 3) - 4, startAngle, endAngle);<br>};</pre><pre>const innerFourthCircle = (startAngle: number, endAngle: number) =&gt; {<br>    return arcGen((domainheight / 2) + 2, (domainheight / 2) - 2, startAngle, endAngle);<br>};</pre><p>Here, the inner and outer radius of the arc are calculated by the height of our circle adding and subtracting some pixels for the circle thickness. Remember, our axis were -4 to 4 for x and y. So this means that the arc need to start and end on exactly these values. That’s why I calculated for all circles the height divided by 8 — for the smallest circle which has a radius of 1, 4 — for the 2nd circle which has a radius of 2, 3/8 — for the third circle which has a radius of 3, and by 2 for the outer circle which has a radius of 4.</p><p>Next, create all arcs with colors. Repeat the step below for all four colors.</p><pre>const circleTransform = &#39;translate(&#39; + (domainwidth / 2) + &#39;px, &#39; + (domainheight / 2) + &#39;px)&#39;;<br>const GREEN = &#39;#84BFA4&#39;;</pre><pre>const green = svg.append(&#39;g&#39;)<br>    .attr(&#39;class&#39;, &#39;green&#39;);<br><br>// green background gradient area<br>green.append(&#39;rect&#39;)<br>    .attr(&#39;width&#39;, domainwidth / 2)<br>    .attr(&#39;height&#39;, domainheight / 2)<br>    .attr(&#39;x&#39;, 0)<br>    .attr(&#39;y&#39;, 0)<br>    .attr(&#39;fill&#39;, &#39;url(#green-radial-gradient)&#39;)<br>    .style(&#39;opacity&#39;, .25);<br><br>// green circle borders<br>green.append(&#39;path&#39;)<br>    .attr(&#39;fill&#39;, GREEN)<br>    .attr(&#39;d&#39;, innerFirstCircle(3 * <strong><em>Math</em></strong>.PI / 2, 4 * <strong><em>Math</em></strong>.PI / 2))<br>    .style(&#39;transform&#39;, circleTransform);<br>green.append(&#39;path&#39;)<br>    .attr(&#39;fill&#39;, GREEN)<br>    .attr(&#39;d&#39;, innerSecondCircle(3 * <strong><em>Math</em></strong>.PI / 2, 4 * <strong><em>Math</em></strong>.PI / 2))<br>    .style(&#39;transform&#39;, circleTransform);<br>green.append(&#39;path&#39;)<br>    .attr(&#39;fill&#39;, GREEN)<br>    .attr(&#39;d&#39;, innerThirdCircle(3 * <strong><em>Math</em></strong>.PI / 2, 4 * <strong><em>Math</em></strong>.PI / 2))<br>    .style(&#39;transform&#39;, circleTransform);<br>green.append(&#39;path&#39;)<br>    .attr(&#39;fill&#39;, GREEN)<br>    .attr(&#39;d&#39;, innerFourthCircle(3 * <strong><em>Math</em></strong>.PI / 2, 4 * <strong><em>Math</em></strong>.PI / 2))<br>    .style(&#39;transform&#39;, circleTransform);</pre><p>Let me explain the code. My green area is my first quadrant. It’s the upper left hand side of a circle. Think of our arc logic from the math part and remember that 90deg is 0,5π. As the green are starts at 270deg (clockwise counted) and ends at 360deg, we pass 3π/2 and 4π/2 to the arc function for all four circles.</p><blockquote>Pay attention here to the function calls. The parameters for startAngle and endAngle passed to the “inner circle” functions are always the same as we are still in the same quadrant. For the other quadrants this would mean:</blockquote><p>For the second quadrant — upper righthand side — this would mean to pass 0deg to 90deg: 0, π/2.<br>For the third quarter — lower righthand side — it is 90deg to 180deg: π/2 to π.<br>And the fourth quarter — lower lefthand side — it is 180deg to 270deg: π to 3π/2.</p><p>Then you should see all four circles and in case you changed the fill color of the path for each group, you should also see all four quadrants in different colors.</p><h3>Step 5: Placing the dots inside the circles.</h3><p>For the dots, you should add a JSON file with a structure similar to this one:</p><pre>{<br>  &quot;text&quot;: &quot;Dot-Name&quot;,<br>  &quot;quadrant&quot;: 1,<br>  &quot;circle&quot;: 2<br>}</pre><p>The quadrant should be self-explainable. The circle number defines the ring in which the dot should be placed. For circle, it means somewhere between the inner and the second circle.</p><p>Now, we loop through all our values in the data JSON file (don’t forget to import the JSON file).</p><pre>const values: Dots[] = (data as Data[]).reduce((list: Dots[], element: Data) =&gt; {<br>    const entry: Dots = {<br>        x: null,<br>        y: null,<br>        text: element.text,<br>        quadrant: element.quadrant,<br>        fillColor: [&#39;green&#39;, &#39;blue&#39;, &#39;red&#39;, &#39;orange&#39;][element.quadrant - 1]<br>    };<br><br>    let dot;<br>    do {<br>        dot = calculateDot(element, x, y);<br>        // calculate this exact dot new until it has a distance to every other dot that is longer than 28 (2x dot radius)<br>    } while (list.some(item =&gt; checkDistanceBetweenDots(dot.xValue, item.x, dot.yValue, item.y) &lt; 20));<br><br>    entry.x = dot.xValue;<br>    entry.y = dot.yValue;<br><br>    list.push(entry);<br><br>    return list;<br>}, []);</pre><p>First of all, we create a new object for each dot. Here we’re going to prepare the dot data for the D3 processing when we later add the dots to our SVG. But first we need to calculate x- and y-values for each dot.</p><p>As I want the dots to be positioned randomly, I also need a check against the distance between each dot. Otherwise a user might not see or perceive all dots.</p><p>So, how are the dots calculated?</p><pre>const pi = <strong><em>Math</em></strong>.PI;<br>export const calculateDot = (element: Data, x: d3.ScaleLinear&lt;number, number&gt;, y: d3.ScaleLinear&lt;number, number&gt;) =&gt; {<br>    // radian between 5 and 85<br>    const randomDegree = ((<strong><em>Math</em></strong>.random() * 80 + 5) * pi) / 180;<br>    const circle = element.circle - 0.2;<br>    const r = <strong><em>Math</em></strong>.random() * 0.6 + (circle - 0.6);<br>    // multiples of PI/2<br>    // loops through every quadrant starting from top left, bottom left, bottom right, top right<br>    const shift = pi * [1,4,3,2][element.quadrant - 1] / 2;<br><br>    return {<br>        xValue: x(<strong><em>Math</em></strong>.cos(randomDegree + shift) * r),<br>        yValue: y(<strong><em>Math</em></strong>.sin(randomDegree + shift) * r)<br>    };<br>};</pre><p>After all, it’s pretty simple when recalling the mathematical formula and logic behind circles. First we create a random degree in radian measure, from 5 to 85 — to avoid dots overlapping quadrants: The „normal“ formula for a fixed degree value would be: <strong>DEG * π / 180</strong>. Here, I replace DEG by my Math.random function.</p><p>Next, we know in which circle (1–4) the dot should be placed. I subtract 0.2 here — again to avoid overlapping into another circle.</p><p>Then we calculate the radius (r). Don’t mess it up with the dots’ radius because here it is the „distance“ from the center of our „coordinate system“ to this dot. I call it radius here because it’s similar to a circle calculation.</p><p>The next part of „shift“ is a special one. Scroll back to my math section: an arc of exactly 90 degree — which is our quadrant size — is 1π/2. So, for calculating all dots for all circles and all quadrants, we simply multiply π with the quadrant number. Unfortunately, my quadrant number is in a different order than circle calculation which is why I added the array [1, 4, 3, 2] here to show that it’s the other way around this time (upper left, lower left, lower right, upper right). For example a dot has a quadrant number of 3, it will return index 2 of this array — which is 3. Another example for quadrant 4: This will return value 2 — so the lower righthand quadrant. This would be pretty wrong as quadrant 4 is the lower lefthand quadrant. But see in the return statement that the shift of one quarter is always added to the random degree. Then, the dot for quadrant 4 will be within the lower lefthand quadrant.</p><p>Next, we return an object for each dot, containing the exact x- and y-value. You may ask yourself what is this x() and y() function about: Check how I’ve set up the x-axis and y-axis at the beginning of the TypeScript and see that I created scaling functions using d3-scaleLinear for x and y values. Continue reading about <a href="https://github.com/d3/d3-scale">d3-scales</a> here.</p><p>And that’s it for the dot calculation. The distance between each dot which is checked in the do-while-loop is just using Pythagoras:</p><pre>export const checkDistanceBetweenDots = (x1: number, x2: number, y1: number, y2: number) =&gt; {<br>    const a = x2 - x1;<br>    const b = y2 - y1;<br>    return <strong><em>Math</em></strong>.sqrt((a * a) + (b * b));<br>};</pre><p>Now, that you calculated all x- and y-values for the dots, you can implement the dots into the SVG using d3:</p><pre>g.append(&#39;g&#39;)<br>    .attr(&#39;class&#39;, &#39;circles&#39;)<br>    .selectAll(&#39;circle&#39;)<br>    .data(values)<br>    .enter().append(&#39;circle&#39;)<br>    .attr(&#39;class&#39;, d =&gt; &#39;dot is-&#39; + d.fillColor)<br>    .attr(&#39;r&#39;, 5)<br>    .attr(&#39;data-value&#39;, d =&gt; d.text)<br>    .attr(&#39;cx&#39;, d =&gt; d.x)<br>    .attr(&#39;cy&#39;, d =&gt; d.y)</pre><p>You should now see all the dots from your JSON file randomized positioned in your radar. Feel free to add texts or mouseover functions here.</p><h3>🥳</h3><h3>Summary</h3><p>This example shows pretty clear that D3 is a very powerful and extendible framework. I assume, it would be a lot more time consuming to create different arcs in different colors for creating circles with any other framework. Here, we highly benefit from the huge possibilities in terms of customization.</p><p>For beginners it might look very confusing and messy but once you understand how D3 expects your SVG to be created and all its children to be arranged in code, it is quite handy to create beautiful visualizations. Also, it becomes easier to extract parts of the code into functions for reusing them.</p><p>My personal struggle with a visualization like this was definitely the maths theory — as my last maths class had been years ago… 😁</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9db6458a9248" width="1" height="1" alt=""><hr><p><a href="https://medium.com/create-code/build-a-radar-diagram-with-d3-js-9db6458a9248">Build a radar diagram with d3.js</a> was originally published in <a href="https://medium.com/create-code">Create &amp; Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a simple line chart with D3.js in Angular]]></title>
            <link>https://medium.com/weekly-webtips/build-a-simple-line-chart-with-d3-js-in-angular-ccd06e328bff?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccd06e328bff</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[line-charts]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Sun, 15 Nov 2020 09:48:15 GMT</pubDate>
            <atom:updated>2020-11-18T16:37:39.099Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*grat8k_k04uN5F-bOcNc2Q.jpeg" /></figure><p>In this post I’m going to show you how to integrate D3.js into your Angular application and how to create a simple styled line chart. Also, we’re covering changes of the chart data and on responsiveness.</p><p>I assume you already have an Angular app running on your local machine.</p><h3>Pre-requisites</h3><p>Install D3.js as a dependency and as we’re working with Typescript, install the d3 types as well:</p><pre>npm i --save d3<br>npm i --save-dev @types/d3</pre><p>Next, create a component for your chart via Angular CLI:</p><pre>ng generate component line-chart</pre><p>Within the Typescript file of this component, we’re going to import d3:</p><pre>import * as d3 from &#39;d3&#39;</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58d1cc7f0b603496986bcd53f464c284/href">https://medium.com/media/58d1cc7f0b603496986bcd53f464c284/href</a></iframe><p>Add the above JSON to your <strong><em>app.component.ts</em></strong>:</p><pre>public data = [<br>  {<br>    value: 20,<br>    date: &#39;2020-05-12T12:19:00+00:00&#39;<br>  },<br>...<br>];</pre><p>We want to pass it as an input to our line chart component.</p><h3>Line Chart Component</h3><p>In the <strong><em>line-chart.component.html</em></strong> we only need to add a div:</p><pre>&lt;div class=„linechart”&gt;&lt;/div&gt;</pre><p>In the<strong><em> line-chart.component.ts</em></strong> the first line to add is the following:</p><pre>@Input() public data: { value: number, date: string }[];</pre><p>This line enables passing the data from the parent component to the line-chart component. Next, in the parent component we can use the line chart component:</p><pre>&lt;app-line-chart [data]=”data”&gt;&lt;/app-line-chart&gt;</pre><p>After that, go back to the <strong><em>line-chart.component.ts</em></strong> and add the following basics:</p><pre>private width = 700;<br>private height = 700;<br>private margin = 50;</pre><pre>public svg;<br>public svgInner;<br>public yScale;<br>public xScale;<br>public xAxis;<br>public yAxis;<br>public lineGroup;</pre><pre>public constructor(public chartElem: ElementRef) {<br>}</pre><p>The chart should be 700x700px large and have a margin of 50px. To make it easier for changes later, I usually set these values to component variables. This will also help when adding responsiveness as it depends on the width of the chart.</p><p>All other component attributes are also needed for the SVG creation, the axes, and lines. Here again, using component attributes will be useful for responsiveness and also for reacting to data changes.</p><h3>Drawing the chart</h3><p>I’m usually splitting up the code for charts into two functions: One function to initialize all elements that I am going to need and one function to actually use and place the elements. This makes it easier in the end to enable responsiveness in which the chart needs to react on browser width sizes. The second function therefore changes all values that are dependent on the width of the chart: all elements that have to do with the x-Axis but also the lines and the complete SVG.</p><h4>Initializing the chart elements</h4><p>Create a function called „<strong>initializeChart</strong>“. At first, the SVG has to be created inside our element reference:</p><pre>this.svg = d3<br>  .select(this.chartElem.nativeElement)<br>  .select(‘.linechart’)<br>  .append(‘svg’)<br>  .attr(‘height’, this.height);</pre><p>Here is one of the Angular specific changes in comparison to „simple“ D3 projects: First, d3 has to select the element reference with its nativeElement and then select the element with my classname. It would also be possible to work with <strong>@ViewChild</strong> and a template reference here but I prefer the element reference.</p><p>Either way, be aware that if you only select an element with a class name — which would also work — there will later be issues if you want to reuse the component, having two instances in one parent component. By using the element or template reference you’re ensuring that all code is applied to this exact instance.</p><p>Inside the SVG element I want to have a group which adds the margin to my chart:</p><pre>this.svgInner = this.svg<br>  .append(‘g’)<br>  .style(‘transform’, ‘translate(‘ + this.margin + ‘px, ‘ + this.margin + ‘px)’);</pre><p>Now, we’re digging deeper into the SVG creation and also into our passed data. As you can see in the gist, I’m using a date and a value for each entry. I want to have the dates displayed on the x-axis and the values on the y-axis. So we need to add two scales, xScale and yScale, for being able to display all our datasets within our width and height of the SVG.</p><pre>this.yScale = d3<br>  .scaleLinear()<br>  .domain([d3.max(this.data, d =&gt; d.value) + 1, d3.min(this.data, d =&gt; d.value) — 1])<br>  .range([0, this.height — 2 * this.margin]);</pre><pre>this.xScale = d3.scaleTime().domain(d3.extent(this.data, d =&gt; new <strong><em>Date</em></strong>(d.date)));</pre><p>Here you can see the difference between using a time scale and a simple linear scale. For the linear scale, I use the d3 helper functions <strong>max()</strong> and <strong>min()</strong> to get the lowest and highest value of my datasets. I do add and remove one to get a small „padding“ — meaning the highest and lowest value in the line are not exactly placed on the top or bottom of my SVG.</p><p>As the x-axis depends on the width of the element, we’re here unable to set the range which sets the scaling to the container width.</p><p>Next, we’re going to add the axes.</p><pre>this.yAxis = this.svgInner<br>  .append(‘g’)<br>  .attr(‘id’, ‘y-axis’)<br>  .style(‘transform’, ‘translate(‘ + this.margin + ‘px, 0)‘);</pre><pre>this.xAxis = this.svgInner<br>  .append(‘g’)<br>  .attr(‘id’, ‘x-axis’)<br>  .style(‘transform’, ‘translate(0, ‘ + (this.height — 2 * this.margin) + ‘px)’);</pre><p>Those of you who are already familiar with D3.js will recognize that I don’t call the axes with their scales. As they depend on the screen sizes, this is something I’m going to add later when filling the chart. These initializations here ensure that the axes with their containers are already available and I don’t need to instantiate them on every resize.</p><p>The same applies to the line:</p><pre>this.lineGroup = this.svgInner<br>  .append(&#39;g&#39;)<br>  .append(&#39;path&#39;)<br>  .attr(&#39;id&#39;, &#39;line&#39;)<br>  .style(&#39;fill&#39;, &#39;none&#39;)<br>  .style(&#39;stroke&#39;, &#39;red&#39;)<br>  .style(&#39;stroke-width&#39;, &#39;2px&#39;);</pre><p>That’s all for initializing the SVG chart. Let’s head over to applying data to it.</p><h4>Apply data to the SVG</h4><p>Create a function named „<strong>drawChart</strong>“. Keep in mind, that this function is going to be our function to react to resizing events. That’s why everything in there relies on the element width. So first of all, we’re setting the new width, calculated from our element reference:</p><pre>this.width = this.chartElem.nativeElement.getBoundingClientRect().width;</pre><pre>this.svg.attr(‘width’, this.width);</pre><p>Also, we’re setting the range for the x-axis and filling both axes with their scales and hence the data:</p><pre>this.xScale.range([this.margin, this.width — 2 * this.margin]);</pre><pre>const xAxis = d3<br>  .axisBottom(this.xScale)<br>  .ticks(10)<br>  .tickFormat(d3.timeFormat(&#39;%m / %Y&#39;));</pre><pre>this.xAxis.call(xAxis);</pre><pre>const yAxis = d3<br>  .axisRight(this.yScale);</pre><pre>this.yAxis.call(yAxis);</pre><p>The last thing we’re going to do is to add our line. We first generate a line path with a monotone curve. Also, we need to map our data by creating a two-level array in which every entry contains the X and Y value:</p><pre>const line = d3<br>  .line()<br>  .x(d =&gt; d[0])<br>  .y(d =&gt; d[1])<br>  .curve(d3.<strong><em>curveMonotoneX</em></strong>);</pre><pre>const points: [number, number][] = this.data.map(<br>  d =&gt; [this.xScale(new <strong><em>Date</em></strong>(d.date)), this.yScale(d.value)]<br>);</pre><pre>this.lineGroup.attr(‘d’, line(points));</pre><p>Then, we simply set the d attribute on the line path we created in our initializer.</p><h3>Make the chart responsive and listen to changes</h3><p>The very last part of this tutorial includes the listening to changes and the listener for resizing.</p><p>We want to check that whenever the data from outside is changing, the chart gets updated. Angular provides the lifecycle hook „<strong>OnChanges</strong>“ which we’re going to use. For the resizing issue, we’re always listening to window resizing and also draw the chart again. Hence, we’re able to cover both cases in our <strong>ngOnChanges</strong> function:</p><pre>public ngOnChanges(changes): void {<br>  if (changes.hasOwnProperty(‘data’) &amp;&amp; this.data) {<br>     this.initializeChart();<br>     this.drawChart();<br>     <strong><em>window</em></strong>.addEventListener(‘resize’, () =&gt; this.drawChart());<br>  }<br>}</pre><p>And that’s it. 🥳 Your chart should look similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Fb_tn2VrfnGSbRPbkD4Cgw.png" /><figcaption>The result of the generated chart.</figcaption></figure><p>Your complete component code should be like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1eba065e67783fc0cdb4d56eb115347/href">https://medium.com/media/e1eba065e67783fc0cdb4d56eb115347/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccd06e328bff" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/build-a-simple-line-chart-with-d3-js-in-angular-ccd06e328bff">Build a simple line chart with D3.js in Angular</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IT first, User Experience Design second.]]></title>
            <link>https://medium.com/create-code/it-first-user-experience-design-second-abfb98616f58?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/abfb98616f58</guid>
            <category><![CDATA[it]]></category>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[ux-design]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Mon, 05 Oct 2020 13:11:03 GMT</pubDate>
            <atom:updated>2021-08-31T14:44:25.456Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lGLACsVJ5LLtWOQMcy79GA.jpeg" /></figure><h4>How we made the IT Infrastructure more important in the first place and how we made User Experience Design came second — an experience report of a 2-Month-Side-Project.</h4><p>Lately, I’ve been working on a project with an IT-first approach. User Experience Design came second. In this article I’m going to share my experiences with you: what made the process special, how did we approach things and how it changed our minds of developing platforms — from developer’s point of view.</p><p>Don’t get me wrong, we worked on User Experience as well and did a good job there, too.</p><h3>The Project</h3><p>At <a href="https://mediaman.com/">mediaman</a> we had a running challenge in May: We separated our athletes into two teams and the team which ran the most kilometer within two week would win the challenge. Quickly we’ve built dashboards to show our statistics. <a href="https://www.mediaman.com/projekte/remoterun-challenge">Read our blog post about the first challenge here</a>.<br>Afterwards, our goal was to build a platform called <a href="https://www.remoterun.de/">remoterun.de</a> which was determined to motivate companies to walk, hike or run together. Each company can choose its own donation amount which will be donated to a charity organization.</p><h3>The Idea</h3><p>In our first version, every entry in our dashboards was done manually — a crucial point that we wanted to change. We wished to connect different running apps (like Strava) to collect activities automatically.</p><h3>So, why IT first?</h3><p>In the very beginning we started with a very rough proof of concept: Register a Strava App with API keys and fetch the activity data. Our main goal here was to use AWS Lambda for a serverless application.</p><p>After a few hours of setting up this infrastructure and make Strava automatically call our endpoints, the very base was done. We were able to collect data.</p><p>That was when our approach to do IT first was approved. <strong>This was the very first step to make the project work at all.</strong> From then, we started setting up database structures, endpoint structures and a very basic Frontend Angular application.</p><p>I can’t remember how many hours were already on the clock — but it was lot.</p><p>Only after this setup was made, our Designer was asked to create a user experience design. We were working closely together. At every point of development the designer did know about the IT restrictions and possibilities. We as developers were able to get glances on the design at every time.</p><p>It was an amazing experience to work closely together with the design department, to make him understand our idea of data driven frontends and vice versa showing us his opinion about user experience design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FMiw6A0GV633qxhiaU0tg.png" /><figcaption>Our final IT Infrastructure</figcaption></figure><h3>Change of minds</h3><p>We all learned a lot during these days. All in all the project went to production within 2 months as a side project — yes, we did that all in our leisure time! At this point we all had work to do for our employer.</p><p>Every time we as developers published a new feature in the frontend, we asked our designer to support us in how to display data. In addition, he was already part of the IT concept phases in which we decided on how to build our software architecture. That’s a crucial point in our workflow: understand the designers work and make them understand our work.</p><h3>Conclusion</h3><p>My personal opinion about this approach is that it’s very worth it. Make IT first build the infrastructure and then closely together with designers, create and expand the platform. This is so time-saving because we got rid of endless feedback loops, of bug reports that were just a result of misunderstandings.</p><p>In addition to that we were able to create the design based on what’s the most logical and safe way of implementing the frontend and backend. Developer might understand me: Often we are asked to “hack” the IT infrastructure and mainly the frontend based on what Designers designed and clients approved. Here, we were able to focus on the core of this application in its technical part and still creating the best solution on both sides, IT and Design.</p><p><strong>Besides, we developed a super strong team spirit by listening and giving honest feedback every time and working closely together. 😍</strong></p><p>Yes, we were developing an MVP in a short amount of time but as soon as the project went live, it didn’t feel like an MVP anymore. It felt so real, so cool to finally see our system being used by other people than us.</p><blockquote>Check out our project on <a href="https://remoterun.de/">https://remoterun.de</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abfb98616f58" width="1" height="1" alt=""><hr><p><a href="https://medium.com/create-code/it-first-user-experience-design-second-abfb98616f58">IT first, User Experience Design second.</a> was originally published in <a href="https://medium.com/create-code">Create &amp; Code</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 build a sitemap with a node.js crawler and D3.js (Part 2/2)]]></title>
            <link>https://medium.com/create-code/how-to-build-a-sitemap-with-a-node-js-crawler-and-d3-js-part-2-2-44c425ef4871?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/44c425ef4871</guid>
            <category><![CDATA[sitemap]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[generator]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 12:45:06 GMT</pubDate>
            <atom:updated>2020-06-02T08:27:53.277Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this second part of the series we’re going to use the crawler output from part 1 and end up having a tree sitemap in our browser, in an index.html.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*ljoATpU14XbSxgn86QfKFg.jpeg" /></figure><blockquote>This tutorial is based on <a href="https://observablehq.com/@d3/tidy-tree">this d3.js example</a>.</blockquote><h4>Prerequisites</h4><ul><li><a href="https://medium.com/@babette.landmesser/how-to-build-a-sitemap-with-a-node-js-crawler-and-d3-js-part-1-2-3f65f95268c8?source=friends_link&amp;sk=de125f47297ba9471cc0916804bb3c2c">Read part 1.</a></li><li>webpack cli installed</li><li>crawler output as json</li></ul><h3>File Setup</h3><p>Create an <em>index.html</em>, <em>main.js</em> and a <em>data.js</em>. That’s all that is needed.</p><p>Fill the <em>index.html</em> with this few lines of content</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html lang=”en”&gt;<br>&lt;head&gt;<br>    &lt;meta charset=”UTF-8&quot;&gt;<br>    &lt;title&gt;Tree&lt;/title&gt;<br>    &lt;script src=”<a href="https://d3js.org/d3.v5.min.js">https://d3js.org/d3.v5.min.js</a>&quot;&gt;&lt;/script&gt;<br>    &lt;script src=”build/main.js”&gt;&lt;/script&gt;<br>&lt;/head&gt;<br>&lt;body&gt;<br>    &lt;img&gt;<br>&lt;/body&gt;<br>&lt;/html&gt;</pre><p>You see, we’re importing d3js from the original source. Also, don’t worry about the path to the <em>main.js</em> file because as we will compile es6 with <strong>webpack</strong>, the compiled file will then be stored in the build folder.</p><p>Inside of the body we only need an image tag to fill it with svg source later and to be able to download the sitemap.</p><p>For the <em>data.js</em> file, paste the output of the crawler into a javascript object like this:</p><pre>export default {<br>    data: [<br>        { name: … }<br>    ]<br>}</pre><p>In the <em>main.js</em> we first need to import our data and set our final svg width:</p><pre>import source from ‘./data.js’;</pre><pre>const data = source.data;</pre><pre>const width = 1440;</pre><p>In your console type</p><pre>$ webpack main.js -o build/main.js -w</pre><p>and your <em>main.js</em> is being watched for changes and automatically compiled to <em>build/main.js</em>.</p><h3>Data Preparations</h3><p>First, we need to prepare the data, find out which elements are child elements of the main domain and which are located below another child. Create a function that will process our data:</p><pre>const processData = (data) =&gt; {<br>  const base = data[0].name;</pre><pre>  // assuming, the first entry of data is the parent of all<br>  const newData = {<br>    name: base,<br>    children: [],<br>  };<br>};</pre><p>This will create the base of the tree later. Also, we assume that the very first entry of our data array is the base url of the website that we crawled. When remembering the crawler code, this is absolutely logical because we only inserted the domain and added a slash as the first entry of the output. So in case you followed the first part of the tutorial, this assumption should be fine for you.</p><p>Our <em>newData</em> object will contain the name of the base and — so far — an empty array with children. Next, we’re going to loop through all links in our data array and sort them into children or even grandchildren.</p><p>Short explanation of the upcoming steps. A URL consists of “domain — slash — path — slash — path” and so on. So our divider for finding children and grandchildren can easily be the slash. As we assume our base is the “domain + slash”, we’re going to remove this part for finding the children. Hence, the path to check will always start with letters: <strong>domain.com/my-products</strong> is going to be <strong>my-products</strong>. <strong>domain.com/my-products/awesome-product</strong> is going to be <strong>my-products/awesome-product</strong>. This makes it easier to sort it into children and grandchildren.</p><pre>data.forEach(({ name }) =&gt; {<br>  let path = name;<br>  if (name.indexOf(base) !== -1) {<br>    path = name.substring(base.length, name.length);<br>  }<br>  if (path === ‘’) {<br>    return;<br>  }<br>});</pre><p>Next, we need to check if there’s still a slash in the path. If not — it’s a direct child of the domain, if yes — it includes grandchildren.</p><pre>if (path.indexOf(‘/’) === -1) {<br>  if (!newData.children.find(child =&gt; child === path)) {<br>    newData.children.push({name: path, children: []});<br>  };<br>} else {<br>  // the grandchildren processing<br>}</pre><p>Here, we’re going to push the whole dataset entry to the children array for not losing any information. But we’re going to change the name of dataset entry to only store the path. This is relevant for the tree diagram later to only show the paths instead of full URLs.</p><p>For the grandchildren, we need to cut the path again in parts, finding out which path is the parent path.</p><pre>const parent = path.substring(0, path.indexOf(‘/’));</pre><p>Then we need to check if this parent path is already stored inside our children array. and if not, we need to add it — because we don’t know if this path will be added automatically later. For example if there is no complete product overview on the page but all products are stored as /products/product.</p><pre>let parentObj = newData.children.find((child) =&gt; child.name === parent);</pre><pre>if (!parentObj) {<br>   let quickParent = data.find(d =&gt; d.name === base + parent ? parent : undefined);<br>   if (!quickParent) {<br>       quickParent = {<br>           name: parent,<br>       }<br>   }<br>   const parentObjIndex = newData.children.push(quickParent);<br>   parentObj = newData.children[parentObjIndex-1];<br>}</pre><pre>path = path.substring(path.indexOf(&#39;/&#39;) + 1, path.length);</pre><pre>if (parentObj.children) {<br>   parentObj.children.push({name: path});<br>} else {<br>   parentObj.children = [{name: path}];<br>}</pre><p>Here we check for the parent of the current path. If the parent was already added to the <em>newData</em> children array, then we’ll use this object. Otherwise we will check in our original data to find an object with the parent path or else create a new parent. Either way, we push the current path to the children of the parent object.</p><p>After the whole data loop, simple return the new data.</p><pre>return newData;</pre><h3>Generating the tree</h3><p>Now, we need a function that uses the <a href="https://github.com/d3/d3-hierarchy">d3 hierarchy</a> logic and generates the sizes for our svg.</p><pre>const tree = (treeData) =&gt; {<br>    const root = d3.hierarchy(treeData);<br>    root.dx = 10;<br>    root.dy = width / (root.height + 1);<br>    return d3.tree().nodeSize([root.dx, root.dy])(root);<br>};</pre><p>At this point, it’s important for all that to work, to stick to the data structure:</p><pre>{</pre><pre>  name: ..</pre><pre>  children: [</pre><pre>    {</pre><pre>      name: …,</pre><pre>      children: [],</pre><pre>    }</pre><pre>  ]</pre><pre>}</pre><p>Otherwise d3 hierarchy won’t work.</p><h3>Creating the final svg</h3><p>The last function is huge and it’s mainly some SVG adjusting, styling and adding texts. I won’t go into much detail here because its mainly base svg knowledge — although it is based on d3 which brings some special functions such as data, joins, selections and so on.</p><pre>const chart = () =&gt; {<br>    const processedData = processData(data);<br>    const root = tree(processedData);</pre><pre>    let x0 = Infinity;<br>    let x1 = -x0;<br>    root.each(d =&gt; {<br>        if (d.x &gt; x1) x1 = d.x;<br>        if (d.x &lt; x0) x0 = d.x;<br>    });</pre><pre>    const svg = d3.create(&quot;svg&quot;)<br>        .attr(&quot;viewBox&quot;, [0, 0, width, x1 - x0 + root.dx * 2]);</pre><pre>    const g = svg.append(&quot;g&quot;)<br>        .attr(&quot;font-family&quot;, &quot;sans-serif&quot;)<br>        .attr(&quot;font-size&quot;, 8)<br>        .attr(&quot;transform&quot;, `translate(${root.dy / 3},${root.dx - x0})`);</pre><pre>    const link = g.append(&quot;g&quot;)<br>        .attr(&quot;fill&quot;, &quot;none&quot;)<br>        .attr(&quot;stroke&quot;, &quot;#555&quot;)<br>        .attr(&quot;stroke-opacity&quot;, 0.4)<br>        .attr(&quot;stroke-width&quot;, 1.5)<br>        .selectAll(&quot;path&quot;)<br>        .data(root.links())<br>        .join(&quot;path&quot;)<br>        .attr(&quot;d&quot;, d3.linkHorizontal()<br>            .x(d =&gt; d.y)<br>            .y(d =&gt; d.x));</pre><pre>    const node = g.append(&quot;g&quot;)<br>        .attr(&quot;stroke-linejoin&quot;, &quot;round&quot;)<br>        .attr(&quot;stroke-width&quot;, 3)<br>        .selectAll(&quot;g&quot;)<br>        .data(root.descendants())<br>        .join(&quot;g&quot;)<br>        .attr(&quot;transform&quot;, d =&gt; `translate(${d.y},${d.x})`);</pre><pre>    node.append(&quot;circle&quot;)<br>        .attr(&quot;fill&quot;, d =&gt; d.children ? &quot;#555&quot; : &quot;#999&quot;)<br>        .attr(&quot;r&quot;, 2.5);</pre><pre>    node.append(&quot;text&quot;)<br>        .attr(&quot;dy&quot;, &quot;0.31em&quot;)<br>        .attr(&quot;x&quot;, d =&gt; d.children ? -6 : 6)<br>        .attr(&quot;text-anchor&quot;, d =&gt; d.children ? &quot;end&quot; : &quot;start&quot;)<br>        .text(d =&gt; d.data.name)<br>        .clone(true).lower()<br>        .attr(&quot;stroke&quot;, &quot;white&quot;);</pre><pre>    return svg.node();<br>}</pre><p>At the end of our <em>main.js</em> we simply attach the chart function to the window object:</p><pre>window.treeChart = chart;</pre><h3>Displaying the chart</h3><p>Now, head back to the <em>index.html</em> and insert a script part below the image. I use to set <strong>type=“module“</strong> because I am only starting Chrome to display this image and download it. I do not plan to make it work for several browsers.</p><p>So, what are we doing here? First of all, we store the tree svg in a local chart variable. Then we serialize this string and create a bas64 out of it to put as image source. And that’s it. The sitemap will show up.</p><pre>&lt;script type=&quot;module&quot;&gt;<br>    var chart = window.treeChart();</pre><pre>    var img = document.querySelector(&#39;img&#39;);<br>    // get svg data<br>    var xml = new XMLSerializer().serializeToString(chart);</pre><pre>    // make it base64<br>    var svg64 = btoa(xml);<br>    var b64Start = &#39;data:image/svg+xml;base64,&#39;;</pre><pre>    // prepend a &quot;header&quot;<br>    var image64 = b64Start + svg64;</pre><pre>    // set it as the source of the img element<br>    img.src = image64;<br>&lt;/script&gt;</pre><blockquote><strong>Additional notes</strong>: I haven’t tried the JavaScript code on deeper level than 2. And as always: if you think, I did a part too complicated, let me know <em>😉</em></blockquote><h3>The result</h3><p>So, in case of the website of my employer (<a href="https://mediaman.com/">mediaman.com</a>), the current sitemap looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lmnJTFSaeayKc2Gmi107Qg.png" /></figure><p>Again, you find the complete code that I used in Gist:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d3a965064d102fa495d4bd0486a18c7/href">https://medium.com/media/7d3a965064d102fa495d4bd0486a18c7/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44c425ef4871" width="1" height="1" alt=""><hr><p><a href="https://medium.com/create-code/how-to-build-a-sitemap-with-a-node-js-crawler-and-d3-js-part-2-2-44c425ef4871">How to build a sitemap with a node.js crawler and D3.js (Part 2/2)</a> was originally published in <a href="https://medium.com/create-code">Create &amp; Code</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 build a sitemap with a node.js crawler and D3.js (Part 1/2)]]></title>
            <link>https://medium.com/create-code/how-to-build-a-sitemap-with-a-node-js-crawler-and-d3-js-part-1-2-3f65f95268c8?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f65f95268c8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[sitemap]]></category>
            <category><![CDATA[crawler]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Sun, 31 May 2020 10:04:08 GMT</pubDate>
            <atom:updated>2021-05-07T09:19:04.830Z</atom:updated>
            <content:encoded><![CDATA[<h4>When pitching for a new website job or when a company wants to relaunch their website, one of the most important part of the new concept is the information architecture. Therefore a sitemap of the existing page is very helpful to get a complete overview. But before someone extracts all links and hierarchies manually, we can use NodeJS to crawl the page for us.</h4><blockquote>In this part of a two posts series we’re going to build a NodeJS crawler which will save all internal links that are found on a webpage into a json file.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*ljoATpU14XbSxgn86QfKFg.jpeg" /></figure><p>We want to start the crawler by a command in our terminal and the domain should be an argument. This ensures that the crawler will be usable for every website we want. Next, it should only crawl pages that it has not seen before. Otherwise it would run forever and it’ll never stop.</p><h3>Setup</h3><p>In your terminal, create a new project folder and navigate into it.</p><pre>$ mkdir crawler &amp;&amp; cd crawler</pre><p>Run <strong><em>npm init</em></strong> and fill in your values. The entry point <em>index.js</em> is perfect for our case.</p><p>Next, install the main dependencies:</p><pre>$ npm i --save-dev cheerio request fs</pre><p>These three packages will be the only ones for the crawler.</p><ul><li><strong>cheerio</strong> will help us read the DOM and extract information.</li><li><strong>request</strong> will open the website</li><li><strong>fs</strong> will obviously store the URLs in a json file</li></ul><p>Now, add the following lines to your index.js</p><pre>// load all our dependencies<br>const cheerio = require(‘cheerio’);<br>const request = require(‘request’);<br>const fs = require(‘fs’);</pre><pre>// get the domain name from our command $ node . mydomain.com<br>const domain = process.argv[2];<br></pre><pre>// initialize the local variables<br>const crawledPages = [];<br>const crawledPagesData = [];<br>let foundPages = [];<br>let index = 0;</pre><p>In <em>crawledPages</em> we’re going to push all URLs that the crawler already visited. This will later make sure it only visits every page once. <em>crawledPagesData</em> will represent the JSON which the script will put into the JSON file at the very end. <em>foundPages</em> will hold all URLs that the crawler finds. And finally the index will help to loop through foundPages.</p><h3>Crawl Function</h3><p>Add a new function to your <em>index.js</em></p><pre>crawl = async () =&gt; {<br>   // here goes the magic<br>}</pre><p>As the start point for the crawler is similar to the domain given via arguments, we’re going to set the first foundPages entry to<strong> “domain + /”</strong></p><pre>// if it&#39;s the first start<br>if (index === 0) {<br>    // use / as first page.<br>    foundPages.push(domain + &#39;/&#39;);<br>}</pre><p>Next, the page to crawl is the indexed entry of <em>foundPages</em>. As the index is still 0 and we just added the first element to the array, it’s going to crawl the front page first.</p><p>Before we start crawling we need to check if this page was already crawled before.</p><pre>// if pageToCrawl is not yet in list of crawledPages<br>if (crawledPages.indexOf(pageToCrawl) === -1) {<br>   if (pageToCrawl) {<br>      new Promise(resolve =&gt; {<br>         // visit the page<br>         visitPage(pageToCrawl, resolve);<br>      }).then(function() {<br>         index++;<br>         crawl();<br>      });<br>   } else {<br>      process.nextTick(crawl);<br>   }<br>} else {<br>   // go to next crawl<br>   process.nextTick(crawl);<br>}</pre><p>Why do I work with promises? The answer is easy: With promises I can ensure that asynchronous calls ended before the crawler continues. Especially the request to the URL is async which means the crawler should wait for that to happen.</p><p><strong>process.nextTick(callbackFunc)</strong> is needed to avoid running into node timeouts. You can try the code without waiting for the nextTick but for larger pages it may not work.</p><h3>Visit the page</h3><p>Create a new function to actually visit the page. You can also put all the code inline but I’d recommend to separate the crawling and the actual visit and DOM extraction.</p><pre>visitPage = (url, callback) =&gt; {<br>    // requesting the page and extracting the links<br>}</pre><p>Here, we’re going to actually visit the page by requesting it. We need to check if the page is available and the request returns status code 200. If not, we’re restarting the crawler with the next index.</p><pre>// Check status code (200 is HTTP OK)<br>if (!response || response.statusCode !== 200) {<br>    process.nextTick(callback);<br>    return;<br>}</pre><p>If the response is 200, we add the url to crawled pages and an object with page information to <em>crawledPagesData</em>.</p><pre>// Add URL to crawled Pages<br>crawledPages.push(url);<br>crawledPagesData.push({<br>    name: url<br>});</pre><p>I do use an object for <em>crawledPagesData</em> here that only holds the URL for now. But in case you’d like to extend this crawler by for example getting the page title, this would be the easiest way to add it here. Also, be aware that we reuse this structure in part 2 of this series.</p><p>Next, cheerio can load the body and we can implement to collect all internal links. Cheerio is working similar to jQuery which is why it’s mostly used with <strong>$</strong> as constant name.</p><pre>// Parse the document body<br>const $ = cheerio.load(body);</pre><pre>// collect all links<br>collectInternalLinks($, domain, foundPages).then(<br>    (newFoundPages) =&gt; {<br>        foundPages = newFoundPages;<br>        callback();<br>});</pre><p>Again, I am using a dedicated function for that which would return the adjusted <em>foundPages</em> array with the new entries already added. As this code snippet is part of the <strong>visitPage</strong> function, it calls the callback function afterwards to state the end of this process.</p><h3>Collect Internal links</h3><p>First, create a new function that accepts <em>cheerio</em>, the <em>domain</em> and the <em>foundPages</em> array as parameter. We’re expecting a promise as return value and the <em>foundPages</em> array as well.</p><pre>collectInternalLinks = ($, domain, foundPages) =&gt; {<br>    // collecting starts<br>    return new Promise(resolve =&gt; {<br>         resolve(foundPages);<br>    })<br>}</pre><p>So, how to find all internal links? Well, the function already gets the domain as a parameter. So we can extract all <strong>href</strong> of all link tags that include the domain. But this may also include links to subdomains or to social media networks in case the account is called the same as the domain. Plus, all <strong>mailto</strong> links may be included as well. To summarize: too much information.</p><p>Therefore we’re going to only allow links that either start with http, https or with a slash (/) directly. Unfortunately, as not all website admins do redirects, we also need to include links with www and without.</p><p>Cheerio is super easy and the selectors work similar to CSS selectors which makes a string like:</p><pre>const elements = “a[href^=’http://” + domain + “‘], “ +<br>                 “a[href^=’https://” + domain + “‘], “ +<br>                 “a[href^=’<a href="https://www/">https://www</a>.&quot; + domain + “‘], “ +<br>                 “a[href^=’<a href="http://www/">http://www</a>.&quot; + domain + “‘], “ +<br>                 “a[href^=’/’]“;</pre><pre>const relativeLinks = $(elements);</pre><p>I think, that covers all cases.</p><p>Now, loop through all links and extract the href. Also, we need to remove the <strong>“http(s)://(www)”</strong> stuff again before we can add this url to our <em>foundPages</em> array. Lastly, we need to check if this URL is already there and if so, skip it.</p><pre>relativeLinks.each(function(i, e) {</pre><pre>    let href = $(this).attr(&#39;href&#39;);</pre><pre>    if (href.indexOf(&#39;<a href="http://www.&/#39;">www.&#39;</a>) !== -1) {<br>       href = href.substr(href.indexOf(&#39;<a href="http://www.&/#39;">www.&#39;</a>) + 4, href.length);<br>    }<br>    if (href.indexOf(&#39;http&#39;) === 0) {<br>       href = href.substr(href.indexOf(&#39;://&#39;) + 3, href.length);<br>    } else if (href.indexOf(&#39;/&#39;) === 0) {<br>       href = domain + href;<br>    }</pre><pre>    // only add the href to the foundPages if it&#39;s not there yet.<br>    if (foundPages.indexOf(href) === -1) {<br>       foundPages.push(href);<br>    }<br>});</pre><p>Finally, resolve the promise with the <em>foundPages</em> as return value.</p><blockquote>In case you know a prettier way to remove the http(s)://(www) things, let me know <em>😉</em></blockquote><p>Okay, we’re nearly done. The very last part to add is our exit condition. Go back to the <strong>crawl</strong> function and after initializing the <em>pageToCrawl</em> we need to check if the <em>foundPages</em> array is similar to the <em>crawledPages</em> array or if the <em>pageToCrawl</em> is undefined — which would mean that the index is not available in foundPages.</p><p>Then we write the <em>crawledPagesData</em> into a json file and exit the process.</p><pre>// exit the process if both arrays are the same or the next page is not defined</pre><pre>if (foundPages === crawledPages || !pageToCrawl) {<br>   // stop<br>   fs.writeFileSync(<br>      &#39;urls_&#39;+domain+&#39;.json&#39;,<br>      JSON.stringify({ data: crawledPagesData }),<br>      function (err) {<br>          if (err) throw err;<br>      }<br>   );<br>   process.exit();<br>}</pre><h3>Perfect, you’re done. 🥳</h3><p>In the very last line of your <em>index.js</em> call <strong>crawl()</strong>; to actually start the crawling once the entry point of this little node script is triggered.</p><p>In your terminal run</p><pre>$ node . [YOURDOMAIN]</pre><p>and see which URLs the crawler finds. In case you’re worried about no output, you can add the following line to the very beginning of visitPage function:</p><pre><strong><em>process</em></strong>.stdout.write(crawledPages.length + ‘/’ + foundPages.length + ‘\n‘);</pre><p>This will keep you updated on how many pages were found and how many were already crawled.</p><blockquote><a href="https://medium.com/@babette.landmesser/how-to-build-a-sitemap-with-a-node-js-crawler-and-d3-js-part-2-2-44c425ef4871?source=friends_link&amp;sk=29222acb743185386b6497fbeb8acaba">Read Part 2</a>.</blockquote><p>You can check the complete code on this gist.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60cf9a646c1f15b8830da440b52a312e/href">https://medium.com/media/60cf9a646c1f15b8830da440b52a312e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f65f95268c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/create-code/how-to-build-a-sitemap-with-a-node-js-crawler-and-d3-js-part-1-2-3f65f95268c8">How to build a sitemap with a node.js crawler and D3.js (Part 1/2)</a> was originally published in <a href="https://medium.com/create-code">Create &amp; Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Install WordPress in AWS EC2 instance]]></title>
            <link>https://medium.com/@babettelandmesser/install-wordpress-in-aws-ec2-instance-ada5b2db06d2?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/ada5b2db06d2</guid>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[aws-ec2]]></category>
            <category><![CDATA[ec2]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Wed, 15 Apr 2020 12:00:00 GMT</pubDate>
            <atom:updated>2020-04-15T12:00:00.708Z</atom:updated>
            <content:encoded><![CDATA[<h4>When working with AWS, it’s super easy to setup an EC2 instance to run your WordPress installation. In this tutorial I am showing you how to set it up with services that are mainly available within the free tiers of AWS.</h4><blockquote>I assume you know how to use AWS in general.</blockquote><p>First, log in to your AWS and navigate to EC2. Launch a new instance.</p><h4>1. Choose an Amazon machine image</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nOybpNJol4fUBTVUs-bz9A.png" /></figure><p>Make sure you select the Amazon Linux 2 AMI as it is a better configuration compared to Amazon Linux and has several amazon configurations in comparison to a „normal Ubuntu“ AMI.</p><h4>2. Choose an Instance Type</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VZMZQM1O-voIkLRnMoIkJQ.png" /></figure><p>For a normal WordPress installation without loads of traffic, the <strong>t2.micro</strong> instance within the free tier should be enough. The other types may generate costs. For the next step, make sure you navigate to „Configure Instance Details“ and not directly to Launch.</p><h4>3. Configure Instance Details</h4><p>For now, you can skip this step and leave the values to its defaults.</p><h4>4. Add Storage</h4><p>Skip storage as well. The predefined 8 GiB should be enough so far.</p><h4>5. Add Tags</h4><p>Here, click the link to add a name tag and enter a meaningful name. This name will later appear in your instance overview. I will enter „WordPress Tutorial“ here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bMVQjKAJmdkqqC4RHGOO7A.png" /></figure><h4>6. Configure Security Group</h4><p>This step is the important one. AWS recommends to create a new security group for this instance and we’re going to do this. Apply the inbound rules as following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gfyQvxvzluq9E0KkCVdCg.png" /></figure><p>The value for My IP is added automatically. With this configuration we’re allowing to connect to this instance via ssh from our computer and to access the instance via HTTP/HTTPS from everywhere.<br>Now head to „Review and Launch”</p><h4>7. Review Instance Launch</h4><p>You can quickly scan through your values and then click „Launch“ to create this instance. Next, create a new private key and give it a name. Don’t forget to immediately download it. You’ll need it later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fEXcidiTAQoZsSKwImq5nw.png" /></figure><p>Press „Launch Instances“.</p><p>That’s it, you’re done and after the instance was successfully created we can connect to it via SSH.</p><h3>Connect to Instance</h3><p>In your terminal, navigate to the folder where your downloaded key pair is stored. In AWS select your initialized instance and click on „Connect“</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*94dYGkMwqIuj-iDMkORZCA.png" /></figure><p>In the upcoming overlay you’re getting instructions to change the permissions of the key file and copy the command to ssh into the instance.</p><pre>$ chmod 400 wordpress-tutorial-key.pem</pre><pre>$ ssh -i &quot;wordpress-tutorial-key.pem&quot; ec2-user@<strong><em>my-ec-2-instance.com</em></strong></pre><h3>Install PHP and Apache</h3><p>First we’ll check if there are any updates needed:</p><pre>$ sudo yum update -y</pre><p>Then we install PHP</p><pre>$ sudo amazon-linux-extras install -y php7.2</pre><p>Next, install Apache</p><pre>$ sudo yum install -y httpd</pre><p>Start the Apache Service</p><pre>$ sudo systemctl start httpd</pre><p>And make sure apache is always started when launching the instance</p><pre>$ sudo systemctl enable httpd</pre><h3>Configure permissions for ec2-user</h3><p>Add the ec2-user to the apache group:</p><pre>$ sudo usermod -a -G apache ec2-user</pre><p>Log out with <strong><em>$ exit</em></strong><em> </em>and log back in with the ssh command from above.</p><p>Next, the permissions for the group must be changed for <em>/var/www:</em></p><pre>$ sudo chown -R ec2-user:apache /var/www</pre><p>The write permissions and also all future directories must be set as well:</p><pre>$ sudo chmod 2775 /var/www &amp;&amp; find /var/www -type d -exec sudo chmod 2775 {} \;</pre><p>And finally the same for the files:</p><pre>$ find /var/www -type f -exec sudo chmod 0664 {} \;</pre><p>And that’s it.</p><h3>Install the WP CLI</h3><p>I just copied the commands to download the CLI from <a href="https://wp-cli.org/de/#installing">https://wp-cli.org/de/#installing</a>:</p><pre>$ curl -O <a href="https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar">https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar</a></pre><pre>$ php wp-cli.phar — info</pre><pre>$ chmod +x wp-cli.phar</pre><pre>$ sudo mv wp-cli.phar /usr/local/bin/wp</pre><p>Now, check if the cli is available:</p><pre>$ wp — info</pre><h3>WordPress Installation</h3><p>Navigate to <em>/var/www/html</em> and run</p><pre>$ wp core download.</pre><p>If you’re now typing your IP address of the instance in your browser, you should see the WordPress installation guide.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDxaOjVoekLLdeykOegCHQ.png" /></figure><h3>Create a database</h3><p>For the database setup you can easily follow the instructions of the AWS documentation here. <a href="https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html#CHAP_GettingStarted.Creating.MySQL">https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/CHAP_GettingStarted.CreatingConnecting.MySQL.html#CHAP_GettingStarted.Creating.MySQL</a></p><blockquote><em>⚠️</em> But be aware that you should add an initial database in the „Additional Configuration“ section which will not only create a database server but also an empty database.</blockquote><p>Create also an <em>wp-mysql</em> security group to control the access for this database with inbound rules to port 3306.</p><p>Now you’re done setting up WordPress in EC2. For completion, just follow the usual WordPress instructions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ada5b2db06d2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a custom block for WordPress Gutenberg Editor]]></title>
            <link>https://medium.com/@babettelandmesser/create-a-custom-block-for-wordpress-gutenberg-editor-9dd752c95dcd?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dd752c95dcd</guid>
            <category><![CDATA[custom-block]]></category>
            <category><![CDATA[esnext]]></category>
            <category><![CDATA[gutenberg]]></category>
            <category><![CDATA[wordpress]]></category>
            <category><![CDATA[gutenberg-editor]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Sat, 21 Mar 2020 17:53:28 GMT</pubDate>
            <atom:updated>2020-03-21T18:03:41.751Z</atom:updated>
            <content:encoded><![CDATA[<h4>Code a custom media-text block with a headline for your WordPress blog.</h4><p>After years of not really working with WordPress, I created a website for a friend — a photographer. Her requirement was an easy-to-use editor so I thought about that not-so-brand-new WordPress Editor Gutenberg and decided to give it a try.</p><p>After a pretty rough concept phase for the front page, I clicked around the Gutenberg Blocks just to find out: what I want isn’t available in standard blocks. I want a media-text block with a headline above. Why is it important to me that all three fields (headline, image and text) are bundled together? Because then I am able to style it as teaser and give my friend the maximum availability to fill it with custom content.</p><p>Okay so let’s start by adding new blocks in our functions.php of the active theme… outch! Lesson learned: Put it in a plugin to reuse it with new themes.</p><p>Next thing, I tried working with ES5. Pretty not so good because most of all tutorials and help pages are referring to the ESNext version of JavaScript. The only thing that blocked me from using ESNext was setting up webpack or babel or whatever.</p><p>Luckily I found <a href="https://github.com/ahmadawais/create-guten-block">create-guten-block</a>. This magic wand creates a plugin for your block, written in ESNext, already set up with webpack. Well nice! Thanks a lot!</p><h3>Okay let’s dive in.</h3><blockquote>Attention: If you’re not familiar with <strong>node</strong> and <strong>npm</strong>, please check that out first.</blockquote><p>Go to the plugins folder of your local WordPress installation and run</p><pre>$ npx create-guten-block BLOCKNAME</pre><p>This will install the necessary dependencies, set up webpack and the folder structure for your new block. You’re now ready to start coding the block.</p><p>Let’s quickly check the requirements again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LkLO-3rE_HJIrvfRwWeZmw.jpeg" /><figcaption>Display of the block in Gutenberg Editor</figcaption></figure><p>This is the view in our editor that defines our block. In addition we need to switch the text and image part around for aligning them left or right. Therefore we need this adjustment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*NnS5yPxSuEOZFLTT6rKbJQ.jpeg" /><figcaption>Custom block settings</figcaption></figure><p>The content area should be the typical WYSIWYG editor for content.</p><p>That’s it for the backend requirements. The frontend is simple: It shows the content for desktop devices in exactly the same styles as it did in the backend. Only on mobile the image should be the first element below the headline — no matter if the setting is „Show media on right“ or „Show media on left“.</p><p>Okay, that defines our base: our attributes are title, imageUrl, imageAlt and mediaPosition.</p><h3>Structure overview</h3><p>The create-guten-block script created a lot of files for us. For the most of them you don’t really need to know exactly what they do, its mainly the JS nerd stuff. In the root of your plugin there’s a <strong>plugin.php</strong> that is required by WordPress to recognize your plugin. It’s importing your <strong>src/init.php</strong> which holds the magic to register your scripts and styles. In addition it registers the new block type. Navigate to <strong>src/block</strong> folder and here you’re going to do the most of the work: in <strong>block.js</strong> — because I won’t go into details about scss.</p><p>When opening the <strong>src/block/block.js</strong> file of your generated block, you’ll see that it’s already prefilled. The registerBlockType function is keeping all our magic so far. It’s setting a title, description, keywords and some other stuff. Here you can first change these meta values and check for a nice <a href="https://developer.wordpress.org/resource/dashicons/">dashicon</a>.</p><h4>Attributes</h4><p>Next, customize the block. Below the keywords array, add an attribute section:</p><pre>attributes: {<br>   title: {<br>      type: &#39;string&#39;,<br>      source: &#39;text&#39;,<br>      selector: &#39;.teaser__title&#39;<br>   },<br>   imageAlt: {<br>      attribute: &#39;alt&#39;,<br>      selector: &#39;.teaser__image&#39;<br>   },<br>   imageUrl: {<br>      attribute: &#39;src&#39;,<br>      selector: &#39;.teaser__image&#39;<br>   },<br>   mediaPosition: {<br>      type: &#39;string&#39;,<br>      default: &#39;left&#39;,<br>   },<br>},</pre><p>This is defining the previous discussed attributes and their types. The very basic stuff is done now. Let’s change the edit function.</p><h4>Edit Function</h4><p>Currently, the edit area is just some div container with some text. As we need input areas and an upload, we need to change that.</p><p>First, prepare the image display and upload by adding the following function into the edit function:</p><pre>const toggleImagePlaceholder = (openEvent) =&gt; {<br>   if(attributes.imageUrl) {<br>      return (<br>         &lt;img<br>            src={ attributes.imageUrl }<br>            onClick={ openEvent }<br>            className=&quot;image&quot;<br>         /&gt;<br>      );<br>   }<br>   else {<br>      return (<br>         &lt;MediaPlaceholder<br>            onSelect = { media =&gt; { setAttributes({ imageAlt: media.alt, imageUrl: media.url }); } }<br>            allowedTypes = { [ &#39;image&#39; ] }<br>            multiple = { false }<br>            labels = { { title: &#39;Upload&#39; } }<br>         &gt;<br>         &lt;/MediaPlaceholder&gt;<br>      );<br>   }<br>};</pre><p>We do need that function to switch between an image display and the placeholder to upload an image. Also, this shows and hides the media overlay from WordPress and returns the image.</p><p>Then we’re going to need the block control icons to move the media container to either left or right hand side.</p><pre>const toolbarControls = [<br>   {<br>      icon: <strong><em>pullLeft</em></strong>,<br>      title: __( &#39;Show media on left&#39; ),<br>      isActive: attributes.mediaPosition === &#39;left&#39;,<br>      onClick: () =&gt; setAttributes( { mediaPosition: &#39;left&#39; } ),<br>   },<br>   {<br>      icon: <strong><em>pullRight</em></strong>,<br>      title: __( &#39;Show media on right&#39; ),<br>      isActive: attributes.mediaPosition === &#39;right&#39;,<br>      onClick: () =&gt; setAttributes( { mediaPosition: &#39;right&#39; } ),<br>   },<br>];</pre><p>The icons for pullLeft and pullRight are imported from local SVGs in the first lines of the file:</p><pre>import <strong><em>pullLeft </em></strong>from &#39;./assets/pull-left&#39;;<br>import <strong><em>pullRight </em></strong>from &#39;./assets/pull-right&#39;;</pre><p>Also, we define a property that changes the classname for our div to either left or right alignment:</p><pre>className += &#39; is-image-&#39; + attributes.mediaPosition;</pre><p>All this happens before we return anything. That’s next:</p><p>As we’re working with React components here, don’t forget to install and import React.</p><pre>import <strong><em>React</em></strong> from ‘react‘;</pre><p>React is only able to return one single element and that’s why we wrap all our content into a React.Fragment:</p><pre>return (<br>   &lt;React.Fragment&gt;<br>      &lt;BlockControls&gt;<br>         &lt;Toolbar controls={ toolbarControls } /&gt;<br>      &lt;/BlockControls&gt;<br>      &lt;div className={className}&gt;<br>         &lt;PlainText<br>            onChange={ content =&gt; setAttributes({ title: content }) }<br>            value={ attributes.title }<br>            placeholder={ __( &#39;Teaser Title&#39;) }<br>            className=&quot;heading&quot;<br>         /&gt;<br><br>         &lt;div className=&quot;col__2 col--image&quot;&gt;<br>            &lt;MediaUpload<br>               onSelect={ media =&gt; { setAttributes({ imageAlt: media.alt, imageUrl: media.url }); } }<br>               type=&quot;image&quot;<br>               value={ attributes.imageID }<br>               render={ ({ open }) =&gt; toggleImagePlaceholder(open) }<br>            /&gt;<br>         &lt;/div&gt;<br>         &lt;div className=&quot;col__2 col--text&quot;&gt;<br>            &lt;InnerBlocks template={ TEMPLATE } /&gt;<br>         &lt;/div&gt;<br>      &lt;/div&gt;<br>   &lt;/React.Fragment&gt;<br>);</pre><p>After this fragment, we start with the Block Controls and our Toolbar controls. Then we integrate the plain text element for the title of our block.</p><p>In the next following <em>div</em>-elements we create the two columns for media and the text. <em>MediaUpload</em> is the placeholder for our upload and image display in the editor. Here, we’re calling the function we created previously.</p><p>In the second column we use <em>InnerBlocks</em> to make it easy to simply add and remove different types of content. With the template attribute, it’s possible to restrict the content to special block types:</p><pre>const TEMPLATE = [<br>   [<br>      &#39;core/paragraph&#39;,<br>      {<br>         placeholder: _x( &#39;Content…&#39;, &#39;content placeholder&#39; ),<br>      },<br>   ],<br>];</pre><p>And that’s it. The edit function is finished.</p><h4>Save the block</h4><p>First we need a function to create the image tag. Here we need to verify that there is an image url and also an alternative text because this will require different HTML image tags.</p><pre>const cardImage = (src, alt) =&gt; {<br>   if(!src) return null;<br><br>   if(alt) {<br>      return (<br>         &lt;img<br>            className=&quot;teaser__image&quot;<br>            src={ src }<br>            alt={ alt }<br>         /&gt;<br>      );<br>   }<br><br>   // No alt set<br>   return (<br>      &lt;img<br>         className=&quot;teaser__image&quot;<br>         src={ src }<br>         alt=&quot;&quot;<br>      /&gt;<br>   );<br>};</pre><p>Before we return the structure, we’re going to define the classnames:</p><pre>const className = &#39;teaser is-&#39; + attributes.mediaPosition;</pre><p>Then the actual return value for the whole saved block is pretty easy:</p><pre>return (<br>   &lt;div className={ className }&gt;<br>      &lt;h3 className=&quot;teaser__title&quot;&gt;{ attributes.title }&lt;/h3&gt;<br>      &lt;div className=&quot;col__2&quot;&gt;<br>         { cardImage(attributes.imageUrl, attributes.imageAlt) }<br>      &lt;/div&gt;<br>      &lt;div className=&quot;col__2&quot;&gt;<br>         &lt;InnerBlocks.Content /&gt;<br>      &lt;/div&gt;<br>   &lt;/div&gt;<br>);</pre><p>This is simply a normal HTML structure and here it’s fetching the dynamic data for this block from the attributes that are passed to the save function. A special kind of element is the <em>InnerBlocks</em> here again because we don’t need to map it to block specific attributes and WordPress is able to store the content without our help.</p><p>The complete <strong>block.js</strong> file can be found in my gist:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c8270fd4cff2f5c2d7f9c50a714baa9/href">https://medium.com/media/0c8270fd4cff2f5c2d7f9c50a714baa9/href</a></iframe><h3>Next steps</h3><p>Within the already existing .scss files, feel free to not only style the frontend view of your block but also the view in Gutenberg Editor.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dd752c95dcd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[External SVG use in Storybook (Angular)]]></title>
            <link>https://medium.com/@babettelandmesser/external-svg-use-in-storybook-angular-738fc4dc4daa?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/738fc4dc4daa</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[svg4everybody]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Thu, 06 Feb 2020 06:10:37 GMT</pubDate>
            <atom:updated>2020-02-06T16:14:54.296Z</atom:updated>
            <content:encoded><![CDATA[<h4>Today I came across the issue to implement externally stored SVG icons in my Angular Storybook — here’s my solution.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fd50dkVdAU3QjDkvphDRdw.jpeg" /></figure><p>When working with Design Systems or Component Libraries it’s not uncommon to use SVG icons that are stored externally.</p><p>To use external SVG icons, the HTML code usually is:</p><pre>&lt;svg aria-hidden=”true”&gt;<br>    &lt;use xlink:href=”external-icons.svg#myIconID”&gt;&lt;/use&gt;<br>&lt;/svg&gt;</pre><p>When opening your HTML in the browser, the console might throw an error similar to this one:</p><blockquote>Unsafe attempt to load URL external-icons.svg from frame with URL http://localhost:9001. Domains, protocols and ports must match.</blockquote><h3>Storybook</h3><p>For Storybook there’s a different project setup: Stories are rendered inside an iframe which means that the external SVG url must be callable from the inside.</p><p>Stories for an Angular project usually consists of code like this:</p><pre><strong><em>storiesOf</em></strong>(&#39;Key Visual Component&#39;, module)<br>    .add(<br>        &#39;With Headline&#39;,<br>        () =&gt; ({<br>            component: KeyVisualComponent,<br>            props: {<br>                image: text(&#39;Images&#39;, &#39;myImage.png&#39;),<br>                headline: text(&#39;Headline&#39;, &#39;This is a headline&#39;),<br>            }<br>   });</pre><p>In the HTML there are now external SVGs used like the code snippet before. So, how to get rid of this error message?</p><h3>svg4everybody</h3><p>It’s a common workaround to use a kind of a polyfill to make the SVGs available. The most popular one might be <a href="https://github.com/jonathantneal/svg4everybody">svg4everybody</a>.</p><p>For this case here, the component should not implement the JavaScript to keep it clean. The surrounding app should implement polyfills like this.</p><h4>Where to put the polyfill now for Storybook?</h4><p>Within the storybook configuration there’s an option to create an html file called <em>preview-body.html</em>. All content from this file will be rendered into the iframe of your story. <br>So the svg4everybody JavaScript needs to be loaded (whether it’s from a CDN or local file it doesn’t matter).</p><pre>&lt;script src=&quot;https://unpkg.com/svg4everybody@2.1.9/dist/svg4everybody.min.js&quot;&gt;&lt;/script&gt;</pre><p>In the next line, the function should be called:</p><pre>&lt;script&gt;<br>    svg4everybody();<br>&lt;/script&gt;</pre><p>Restart Storybook and see the result. Well.. it’s not working!</p><h3>Solution</h3><p>This is because the plain function call does not enable the polyfill for external sources. Extend the code with the polyfill option and restart Storybook. Now, the SVGs should be loaded correctly.</p><pre>&lt;script&gt;<br>    svg4everybody({ polyfill: true });<br>&lt;/script&gt;</pre><p>And you’re done!</p><blockquote>By the way: The implementation in preview-body.html is not restricted to the Angular version of Storybook.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=738fc4dc4daa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular: Include Google Tag Manager with Analytics]]></title>
            <link>https://medium.com/swlh/angular-include-google-tag-manager-with-analytics-bd24fb74b4fc?source=rss-621c4a28ffcb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd24fb74b4fc</guid>
            <category><![CDATA[tag-manager]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[google-analytics]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[gdpr]]></category>
            <dc:creator><![CDATA[Babette Landmesser]]></dc:creator>
            <pubDate>Sun, 05 Jan 2020 14:37:20 GMT</pubDate>
            <atom:updated>2020-01-06T12:10:04.627Z</atom:updated>
            <content:encoded><![CDATA[<h4>This article is a step-by-step introduction for setting up Google Tag Manager with Analytics in Angular.</h4><blockquote>Important notice: I am not a lawyer and I don’t guarantee for legal correctness. <strong>Please advice a lawyer for your own safety regarding legal guidelines!</strong></blockquote><p>If you want to know about the basics of Google Tag Manager and it’s components, head to <a href="https://support.google.com/tagmanager/answer/6103657">this Google Page</a>.</p><h3><strong>Create a Google Tag Manager instance</strong></h3><p>First, go to <a href="https://tagmanager.google.com/">https://tagmanager.google.com/</a> and log in with your google account or sign up. You should then be directed to the <strong>“All Accounts”</strong> page. In the top right corner you find a button <strong>“Create Account”</strong>. Click it and start setting up Google Tag Manager.</p><p>Fill in the account details and for <strong>“Target Platform”</strong> choose <strong>Web</strong> as you will to implement the Tag Manager into an Angular web and mobile application. After that you’ll be shown a popup with instructions to paste code into your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Uj-FkXVQRxjiwfQ0mUkG5w.png" /><figcaption>Copy the codes and insert them into your index.html as described.</figcaption></figure><p>So head to your Angular project and find the <em>index.html</em> which is usually located under <em>src</em> folder.</p><h3><strong>Setup Google Analytics with Google Tag Manager</strong></h3><p>In Tag Manager, select <strong>“Variables”</strong> from the sidebar and add a new <strong>“User-Defined Variable”</strong>. From the list of Variable Configurations select <strong>“Google Analytics settings”</strong>. Now you should head to Google Analytics <a href="https://analytics.google.com/">https://analytics.google.com/</a> and add a new Analytics Property. After setting it up, copy the Tracking ID which usually starts with “UA-”. Go back to Tag Manager and paste this id into the variable configuration of Google Analytics settings.</p><h3>Configure Google Tag Manager</h3><p>An important setting to do is to anonymize the IP. Therefore expand the section <strong>“More Settings”</strong> and click on <strong>“Fields to set”</strong>. Add a new field and choose anonymizeIp and set the value to “true”. This is needed for the GDPR compliance in EU. Now, save your custom variable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6XVCBykDGyGZcaIU3MbZw.png" /><figcaption>Variable Configuration for Google Analytics in Tag Manager</figcaption></figure><p>Add a second <strong>“User-Defined Variable” </strong>to store the cookie name and select the variable type <strong>“1st-Party Cookie”</strong>.<strong> </strong>As a cookie name write something like “cookieconsent”. Set “Cookie Consent” as a name for the variable and save it.</p><p>Next, go to the page <strong>“Triggers” </strong>and create a new one. This prepares the trigger to enable Google Analytics only if the user accepted all cookies.</p><p>For <strong>“Trigger Configuration”</strong> select <strong>“Page View”</strong> as a trigger type. Here, it’s important to restrict it to <strong>“Some Page Views”</strong> and that opens a new line with trigger adjustments. Select<strong> “Cookie Consent” </strong>and <strong>“contains”</strong> as trigger conditions. Google Analytics should only trigger if the user allowed these cookies. Hence, paste “<em>allow</em>” as a value here and keep that value in mind. We’ll need it once we head back to our Angular project. Save this trigger with a meaningful name (such as cookie-consent-pages) and navigate to Tags.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHcx_0toKikWyV38OmoCqg.png" /></figure><h4>Create the Tag for Google Analytics</h4><p>Add a new tag and for <strong>“Tag Configuration”</strong> use <strong>“Google Analytics: Universal Analytics”</strong>. The <strong>“Track Type”</strong> is <strong>“Page View”</strong> and the <strong>“Settings”</strong> are to be selected from the previously added <strong>“Google Analytics Settings”</strong> Variable. As a trigger, select <strong>“cookie-consent-pages”</strong> because it’s important to restrict it to the dependency to the accepted cookies for the GDPR compliance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_xcqPQSTY33Wk4fujd86qA.png" /><figcaption>Final configuration for the Google Analytics Tag</figcaption></figure><p>And that’s it, save your Tag and submit your workspace changes in the upper right corner by pressing <strong>“Submit”</strong>. It opens an overlay to add publishing information. Again, add some meaningful title and description here.</p><p>Your Google Tag Manager is perfectly set up! Head back to your Angular Code now.</p><h3>Implement the Tag Manager on Angular code base</h3><p>As already mentioned in the first step, your JavaScript Code for the Tag Manager should be in the <em>index.html</em> of your Angular project. <br>Now the calls for the Tag Manager are added in case the user accepts the cookie and Google Analytics is allowed to track.</p><h4>What exactly is needed?</h4><p>1. Add some kind of cookie banner to show to the user when he first enters the page with some text.</p><p>2. The banner should have a button like “OKAY” to accept the cookie. This button has to trigger the Tag Manager and updates the value of the cookie-consent setting.</p><p>3. Add an option to opt-out from tracking on a privacy policy page.</p><p>Let’s jump into the code.</p><h4>Cookie Banner</h4><p>Create a new component from your terminal: $ npm run ng g c cookie-banner<br>Implement it in your <em>app.component.html </em>somewhere above your closing wrapper tag:</p><pre>&lt;app-cookie-banner&gt;&lt;/app-cookie-banner&gt;</pre><p>Add some HTML in <em>cookie-banner.component.html</em> with a text, a link to your privacy policy page and a button. For example:</p><pre>&lt;div <em>*ngIf</em>=&quot;showBanner&quot;&gt;<br>  &lt;p&gt;<br>    For continuous improvement of user experience this website uses  cookies for collecting your IP address and individual statistics.<br>    &lt;br&gt;<br>    See my &lt;a routerLink=&quot;/legal/dataprivacy&quot;&gt;data protection guideline&lt;/a&gt; for further information and opt-out.<br>    By clicking OK you agree to share your data.<br>  &lt;/p&gt;<br><br>  &lt;button (click)=&quot;agreeToShare()&quot;&gt;OK&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Heading to the <em>cookie-banner.component.ts,</em> the following functionalities are needed:<br>- some basic JavaScript code for checking and creating cookies<br>- a check for returning users to not show the banner again.</p><p>Prepare your app.module.ts for using the document and window. In <strong>provider</strong> section add:</p><pre>{<br>  provide: &#39;window&#39;,<br>  useValue: window,<br>},<br>{<br>  provide: &#39;document&#39;,<br>  useValue: document,<br>}</pre><p>Then, in the <em>cookie-banner.component.ts</em>, inject the window and document:</p><pre>public constructor(@Inject(&#39;document&#39;) private document,<br>            @Inject(&#39;window&#39;) private window) {<br>}</pre><p>The first function checks if the cookie with the passed name is present and the second function creates a cookie with the parameters for name, value and expiration days.</p><pre>private getCookie(cname) {<br>  const name = cname + &#39;=&#39;;<br>  const ca = document.cookie.split(&#39;;&#39;);<br>  for (let i = 0; i &lt; ca.length; i++) {<br>    let c = ca[i];<br>    while (c.charAt(0) === &#39; &#39;) {<br>      c = c.substring(1);<br>    }<br>    if (c.indexOf(name) === 0) {<br>      return c.substring(name.length, c.length);<br>    }<br>  }<br>  return &#39;&#39;;<br>}</pre><pre>private setCookie(cname, cvalue, exdays) {<br>  const d = new Date();<br>  d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));<br>  const expires = &#39;expires=&#39; + d.toUTCString();<br>  this.document.cookie = cname + &#39;=&#39; + cvalue + &#39;;&#39; + expires;<br>}</pre><p>You need to implement the check on component initialization if the user has already seen the banner. Add a new property to <em>cookie-banner.component.ts</em> public showBanner: boolean;</p><pre>public ngOnInit() {<br>  const consent = this.getCookie(&#39;cookieconsent&#39;);<br>  if (consent === &#39;allow&#39;) {<br>    this.showBanner = false;<br>  } else {<br>    this.showBanner = true;<br>  }<br>}</pre><h4>Button to agree on cookies</h4><p>To implement the logic (in <em>cookie-banner.component.ts</em>) for setting the cookie if the user clicks the button, the HTML is already prepared with a click function. It’s easy to just add the cookie now and reload the page. The page needs to reload to already track the current session. Otherwise it would only track when the user returns to the page.</p><pre>public agreeToShare() {<br>  this.setCookie(&#39;cookieconsent&#39;, &#39;allow&#39;, 365);<br>  this.window.location.reload();<br>}</pre><p>The passed name of the cookie now has to be the same as used in the Tag Manager in the Cookie Consent variable. In this tutorial I named it “cookieconsent”. As you can see, the function is called with the previously added value “allow” for the Tag Manager. Here, 365 days are set as an expiration date but feel free to set your own value.</p><p>Well, that’s it for the logic to set the cookies and values for the Tag Manager. Now, update your privacy policy to add an option for the user to opt-out. I won’t go into details about the whole privacy policy page.</p><h4>Opt-Out Option</h4><p>Somewhere on the privacy policy page (for example <em>privacy-policy.component.html</em>), a button is needed to create an opt-out option. I placed this below the paragraph about my usage of Google Analytics.</p><pre>&lt;button (click)=&quot;removeCookie()&quot;&gt;Revoke Analytics Cookie Usage&lt;/button&gt;</pre><p>Here again, inject the document and window:</p><pre>constructor(@Inject(&#39;document&#39;) private document,<br>            @Inject(&#39;window&#39;) private window) {<br>}</pre><p>The function in <em>privacy-policy.component.ts</em> for this button is super simple:</p><pre>public removeCookie() {<br>  this.document.cookie = &#39;cookieconsent= ; expires = Thu, 01 Jan 1970 00:00:00 GMT&#39;;<br>  this.window.location.reload();<br>}</pre><p>This basically sets the cookie for the consent to an empty value which then is not “allow” once the user comes back. And again, the page needs to reload to already stop tracking here.</p><h3>And that’s it!</h3><p>Once you click on the button of your cookie banner, inspect your page and navigate to <strong>Application &gt; Cookies</strong>. You should see your cookie with the value “allow.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*pwoFjUapoLB0sI32RMTKuw.jpeg" /></figure><p>Now you can start tracking your visitors. 👏</p><blockquote>In case you want to trigger all page views on sub routes, you need to add them manually as a typical Angular page is a single-page-application and cannot transmit route changes automatically.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd24fb74b4fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/angular-include-google-tag-manager-with-analytics-bd24fb74b4fc">Angular: Include Google Tag Manager with Analytics</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>