<?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[Akur8 - Medium]]></title>
        <description><![CDATA[Akur8 is building the new standard for insurance pricing, powered by transparent AI - Medium]]></description>
        <link>https://medium.com/akur8?source=rss----b90fc781dda5---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Akur8 - Medium</title>
            <link>https://medium.com/akur8?source=rss----b90fc781dda5---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:21:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/akur8" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Common pitfalls for RxJS in Angular]]></title>
            <link>https://medium.com/akur8/common-pitfalls-for-rxjs-in-angular-0311037fc670?source=rss----b90fc781dda5---4</link>
            <guid isPermaLink="false">https://medium.com/p/0311037fc670</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Stav Noy]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 09:24:14 GMT</pubDate>
            <atom:updated>2023-11-27T09:50:13.848Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-sa/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><a href="https://www.akur8.com/"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QeM-AGT872DNt9WLdkqWfA.png" /></a></figure><p>This article was originally written as an internal guide, therefore, it leans toward our code base.<br>It intends to point out common, simple mistakes, while briefly explaining and resolving them.</p><h3>1. Don’t set sync values with subscriptions</h3><h4>❌ Don’t:</h4><pre>service.getFoo$().subscribe(v =&gt; {<br>  this.foo = foo<br>});</pre><h4>✅ Do:</h4><pre>this.foo$ = service.getFoo$();</pre><h4>❓ Why:</h4><p>This mixes async and sync code, introducing race conditions.</p><p>Many times code like this happens to work when written because observable values can be emitted synchronously <em>or</em> asynchronously, even by the same observable.<br>For example, the NgRX store emits the <em>current</em> value synchronously, but subsequent values are async.</p><p>Additionally, Angular change detection will not monitor your manual subscriptions.<br>So if you are using that value in the HTML, you might not see the new value rendered.<br>This is a common enough problem that Angular throws that “<a href="https://angular.io/errors/NG0100">NG0100: Expression has changed after it was checked</a>” error</p><p><a href="https://angular.io/api/common/AsyncPipe">The AsyncPipe</a> <em>does</em> trigger change detection:</p><pre>&lt;div&gt;{{ foo$ | async}}&lt;/div&gt; </pre><h3>2. Always “manage” your subscriptions</h3><h4>❌ Don’t:</h4><pre>someObservable$.subscribe(...);</pre><h4>✅ Do:</h4><pre>subscriptions: Subscription[];<br><br>ngOnDestroy() {<br>  this.subscriptions.forEach(s =&gt; s.unsubsribe())<br>}<br><br>...<br>this.subscriptions.push(someObsevable$.subscribe(...));<br>// and/or cleanup another way, suchs as take/takeUntil/takeWhile etc.<br><br><br>// Or, angular 16+<br>someObservable.pipe(takeUntilDestroyed()).subscribe(...);</pre><h4>❓ Why:</h4><p>Memory leak.</p><p><strong>A subscription will not be garbage collected</strong> when you expect it to (i.e when the component is destroyed). That means subscriptions can stay <em>forever</em> (and prevent whatever it’s pointing at from being garbage collected).</p><p><strong>Even if you are sure</strong> there won’t be more values, the subscriber can’t know that — unless the observer is explicitly completed .<br>And if there <em>are</em> more values, the subscription will execute again even if you don’t mean it to.</p><p><strong>Edit</strong>: Angular 16’s <a href="https://angular.io/api/core/rxjs-interop/takeUntilDestroyed">takeUntilDestroyed</a> simplifies this process. <a href="https://ncjamieson.com/avoiding-takeuntil-leaks/">Remember to put it as the last (or second last) operator</a>. (thanks <a href="https://medium.com/u/21cf4f00d943">Christian Seifert</a> for pointing it out).</p><h4>Notes:</h4><ul><li>Frequently, you should even cleanup <em>before</em> the component is destroyed. See <a href="#8fd2">the section on limiting your observables</a>.</li><li>The subscriptions array isn’t the only method. It’s not even <a href="https://benlesh.medium.com/rxjs-dont-unsubscribe-6753ed4fda87">my favourite</a>. It’s just the most common way in our codebase currently. We even have a BaseComponent class that we simply inherit for it.<br>Edit: we are adopting the newer takeUntilDestroyed mentioned above.</li><li>Angular’s AsyncPipe will handle cleanup for itself. Another reason to prefer it over manual subscriptions.</li><li>Sometimes, you want to continue executing subscriptions even while the component is destroyed. In that case, <em>don’t</em> clean it on destroy. You almost always want to limit the observable in these cases.<br>For example, executing an HTTP call when closing a dialog:</li></ul><pre>submit() {<br> this.someService.doHttpRequest(this.form.value).pipe(take(1)).subscribe();<br> this.dialogRef.close();<br>}</pre><h4>📚 Further reading:</h4><p><a href="https://devzilla.io/manage-rxjs-subscriptions-in-angular">https://devzilla.io/manage-rxjs-subscriptions-in-angula</a>r</p><p><a href="https://benlesh.medium.com/rxjs-dont-unsubscribe-6753ed4fda87">RxJS: Don’t Unsubscribe</a></p><h3>3. Consider limiting your observables</h3><h4>✅ Do:</h4><p>Use <a href="https://rxjs-dev.firebaseapp.com/api/index/function/first">first</a>, <a href="https://rxjs-dev.firebaseapp.com/api/index/function/take">take</a>, <a href="https://rxjs-dev.firebaseapp.com/api/index/function/takeUntil">takeUntil</a>, <a href="https://rxjs-dev.firebaseapp.com/api/index/function/takeWhile">takeWhile</a>, and other “limiters”.</p><h4>❓ Why:</h4><p>Frequently, there is a limited number of times we want to execute a subscription.<br>Sometimes, it would be an error not to:</p><pre>// Infinite loop<br>store.select(getCurrentFoo)<br>  // Here there should be a `.pipe(take(1))`<br>  .subscribe((foo) =&gt; {<br>    const newFoo = createNewFoo(foo);<br>    // This will update `foo` in the store, which is what we&#39;re observing,<br>    // so we end up with an infinite loop<br>    store.dispatch(UpdateFoo(newFoo));<br>  });</pre><p>Sometimes, it’s simply an optimization — similar to above, but there will never be another value.<br>We can cleanup the subscription at some point (e.g on component destroy), but that could take a long time:</p><pre>ngOnInit() { <br>  this.subsriptions.push(<br>    store.select(getProjectId)<br>      // Here there should be a `.pipe(take(1))`<br>      .subscribe(projectId =&gt; {<br>        ...<br>      })<br>  );<br>}</pre><p>In the example above, <em>we</em> know that if the projectId changes there will be a redirect, and the component will destroy anyway, therefore we can manage this correctly.</p><p>However, RxJS doesn’t know this. The subscription will sit and wait for a new projectId that never comes, for as long as the component is open.</p><p>ℹ️ Some observables only have 1 emission, for example HTTP requests. take(1) is technically unnecessary in these cases, however it can be more robust in case changes occur, and “it doesn’t hurt”.</p><h4>📚 Further reading:</h4><p>I’ve already linked this one, but it’s relevant here too:</p><p><a href="https://benlesh.medium.com/rxjs-dont-unsubscribe-6753ed4fda87">RxJS: Don’t Unsubscribe</a></p><p>Don’t miss:</p><p><a href="https://ncjamieson.com/avoiding-takeuntil-leaks/">RxJS: Avoiding takeUntil Leaks</a></p><h3>4. Consider multicasting 🪄 but be careful 😨</h3><h4>tl;dr</h4><p>Multicasting is a bit confusing, so don’t just. share everything blindly.<br>Instead, use it when you have a concrete reason — typically repeated HTTP requests — like in the example below.<br>⚠️ When you do use shareReplay, it usually should be configured with refCount: true.</p><h4>❓ What:</h4><p>Multiple subscriptions = multiple executions; (And FYI: each AsyncPipe is a subscription). <br>If the observable logic is expensive (slow or resource intensive), that expense is multiplied.</p><p>Example:</p><pre>this.foo$ = fooHttpService.get(fooId);<br>this.subscriptions.push(<br>  this.foo$.subscribe(...), // 1st subscription<br>  bar$.pipe(withLatestFrom(foo$).subscribe(...), // 2nd subscription<br>);<br><br>...<br><br>&lt;div *ngIf=&quot;foo$ | async as foo&quot;&gt; // 3rd subscription</pre><p>Open your console. There are 3 http requests.</p><p>Solution: use <a href="https://rxjs-dev.firebaseapp.com/api/operators/shareReplay">shareReplay()</a>:</p><pre>this.foo$ = fooHttpService.get(fooId)<br>  .pipe(shareReplay({ bufferSize: 1, refCount: true }));</pre><h4>⚠️ shareReplay requires special management</h4><p>Notice it is specifically configured with refCount: true. This is because, otherwise you have an unmanaged subscription.</p><p>When you subscribe to shareReplay, it creates a single <em>internal</em> subscription to share between all clients.</p><p>With refCount, shareReplay will internally unsubscribe when all clients have unsubscribed. It’s conceptually similar to a Weak Reference, if you’re familiar with those.<br>The downside is that if the next subscription happens <em>after</em> the previous one has unsubscribed, the shareReplay will have already “reset” between them, so nothing would have been shared.</p><p>Without refCount, the internal subscription will linger, to avoid the computationally expensive work for any <em>future</em> subscriptions — like a cache that doesn’t clean.<br><strong>Unsubscribing</strong> from the resulting observable <strong>will not unsubscribe</strong> that internal subscription.<br><em>If</em> the “source” observable completes anyway (see <a href="#8fd2">limiting</a>), that’s OK, however it is tricky.<br>This is where our internal doc encourages seeking advice from other team members.</p><p>ℹ️ shareReplay is not the only multicasting operator, but it’s the one you most likely want.</p><p>ℹ️ In RxJS 7, <a href="https://rxjs.dev/deprecations/multicasting">multicasting operators were massively refactored</a>. At the time of writing this article, we are at v6.</p><p>ℹ️ Worth mentioning: sharing has a special relation with limiting. I’ll again point to <a href="https://ncjamieson.com/avoiding-takeuntil-leaks/">Nicholas Jamieson’s article</a>. The short version: do take(1), shareReplay(...) , Not shareReplay(...), take(1) .</p><h4>📚 Further reading:</h4><p>These were written before the RxJS 7 refactor, but the explanation holds:</p><ul><li><a href="https://benlesh.medium.com/hot-vs-cold-observables-f8094ed53339">Hot vs Cold Observables</a></li><li><a href="https://itnext.io/the-magic-of-rxjs-sharing-operators-and-their-differences-3a03d699d255">The magic of RXJS sharing operators and their differences</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0311037fc670" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akur8/common-pitfalls-for-rxjs-in-angular-0311037fc670">Common pitfalls for RxJS in Angular</a> was originally published in <a href="https://medium.com/akur8">Akur8</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Breaking down Angular forms]]></title>
            <link>https://medium.com/akur8/breaking-down-angular-forms-at-akur8-6a2ced2fef96?source=rss----b90fc781dda5---4</link>
            <guid isPermaLink="false">https://medium.com/p/6a2ced2fef96</guid>
            <category><![CDATA[angular-forms]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[controlvalueaccessor]]></category>
            <dc:creator><![CDATA[Stav Noy]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 07:52:16 GMT</pubDate>
            <atom:updated>2023-09-01T07:52:15.971Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBT1r_QbPG8kaWZmZTEhkw.jpeg" /></figure><p>This post is about breaking down large, monolithic Angular forms into smaller forms, spread across multiple components. <br>It assumes familiarity with <a href="https://angular.io/guide/reactive-forms">Angular Reactive forms.</a> <br>This is not a repeat of <a href="https://www.youtube.com/watch?v=CD_t3m2WMM8">the excellent presentation from Kara Erickson</a>, but an application of it.</p><p>While looking into a bug I had I ran into <a href="https://www.npmjs.com/package/ngx-sub-form">ngx-sub-form</a>.<br>At a glance it seemed very similar to my approach, but purpose built as a nice standard library.<br>I haven’t had time to check out its usability or security.</p><p>In this article I’m using Angular’s new TypedForms (since v14). <br>When we originally wrote the code, we were still on Angular 13. <br>Because of that, we declared custom types for typed forms ourselves. <br>Admittedly, our code is still using those, and I haven’t had many chances to use the new official ones yet, so you may find some inconsistencies. <br><a href="https://github.com/StavNoy/SubFormComponent-breaking-down-angular-forms/blob/main/typed-forms-for-angular-before-14/typed-forms.model.ts">You can find our type declaration here</a>.</p><h3>Background</h3><p>We have a feature in our application where a user can generate custom graphs from existing datasets. <br>The user defines which columns to show as Y values, what data to group it by as X values, and how to aggregate it (average, max, etc).<br>They can also add filters on the data, and select various visual formatting options (colors etc.).</p><p>For example, if the data is:</p><pre>| age | gender | year |<br>|-----|--------|------|<br>| 25  | M      | 2020 |<br>| 64  | F      | 2020 |<br>| 42  | F      | 2019 |<br>| 75  | -      | 2020 |<br>| ... |        |      |</pre><p>The user can request to see the average age (Y), grouped by gender (X), where year is 2020, as a bar chart.</p><p>As this feature was developed from a seed of an idea to an MVP, the form to define what the user wants grew, changed drastically and hurriedly, got partially refactored, grew and changed drastically again, was partially refactored again, had some hurried critical bug fixes patched here and there …</p><p>In the end, it was a mess of spaghetti code, riddled with bugs, where each small bug fix or feature adjustment required hours of logic tracing and large rewrites. Any two changes would almost always conflict with each other.</p><p>So we did what everyone who deals with such code dreams of doing: we took a step back and rewrote the whole thing. Not from scratch — we wanted to keep most of the backend business logic — but pretty close.</p><h3>The problem:</h3><p>The final data structure is very large.<br>There are many validation constraints, as well as behavioural constraints. Some of those were conditional, and some depended on other parts of the form.<br>A single Angular form was incredibly unwieldy, and hard to break over multiple components.</p><h3>Solution: break it down</h3><p>Based on <a href="https://www.youtube.com/watch?v=CD_t3m2WMM8">the talk by Kara Erickson</a>, we created custom form Components for different sections, roughly corresponding to the interface definitions: an AxisFormComponent, XSeriesFormComponent, etc., with the component “higher up the tree” using the “leaf” components. (i.e DataFormComponent uses YSeriesFormComponent, which itself uses OperationFormComponent, etc.)</p><h4>How</h4><p>Let’s first discuss what we <em>didn’t</em> do. We didn’t just pass the form controls as `@Inputs`. <br>We have a few components like that in our app. <br>It’s a perfectly okay solution for simple cases, like a name input with some specific styling and basic error messages.</p><pre>@Component({<br>  template: `<br>    &lt;div class=&quot;container&quot;&gt;<br>      &lt;label&gt;<br>        &lt;span class=&quot;label-text&quot;&gt;Name:&lt;/span&gt;<br>        &lt;input [formControl]=&quot;nameControl&quot;&gt;<br>      &lt;/label&gt;<br>      &lt;span class=&quot;error&quot; *ngIf=&quot;nameControl.hasError(&#39;required&#39;)&quot;&gt;Name cannot be empty&lt;/span&gt;<br>    &lt;/div&gt;<br>  `<br>  // ...<br>})<br>class NameFormComponent {<br>  @Input()<br>  nameControl!: FormControl&lt;string&gt;;<br>}</pre><p>The main drawback of form controls as inputs is that it keeps the task of creating the form controls in the “root” component. <br>That includes all the logic of initial values, validation, subscriptions to `control.valueChanges`, etc.<br>We wanted to split the logic as much as possible since having all the logic internal to the different components is the easiest to reason through.</p><p>We went with what Kara Erickson refers to as a “Composite ControlValueAccessor” <a href="https://www.youtube.com/watch?v=CD_t3m2WMM8&amp;t=1565">(https://www.youtube.com/watch?v=CD_t3m2WMM8t=1565</a>).</p><p>This is a bit tricky. Each sub form would have an internal form, separate from the one in the parent component. <br>It would then sync the 2 forms with `ControlValueAccessor`. <br>This will make more sense soon, I promise.</p><blockquote><a href="https://angular.io/api/forms/ControlValueAccessor"><em>ControlValueAccessor</em></a><em> is an interface for components.<br>With it, we define how a component can manage a FormControl given through the template.<br>For example, Angular Material’s MatSelect is a ControlValueAccessor, so we can give it a FormControl like so:</em></blockquote><blockquote><em>&lt;mat-select [formControl]=”myFormControl”&gt;...</em></blockquote><p>To make things easy, we created an AbstractSubFormComponent, so every new FormComponent will only need to define how its internal form is created.</p><pre>interface Address {<br>  city: string;<br>  street: string;<br>}<br><br>// ###########################<br><br>// This is the &quot;root&quot; form component.<br>// It is NOT a SubFormComponent, but just a regular Component that has a form<br>@Component({<br>  template: `<br>    &lt;form [formGroup]=&quot;form&quot;&gt;<br>      &lt;input formControlName=&quot;name&quot;&gt;<br>      &lt;app-address-form formControlName=&quot;foo&quot;&gt;&lt;/app-address-form&gt;<br>    &lt;/form&gt;<br>  `<br>})<br>class PersonFormComponent {<br>  form = new FormGroup({<br>    name: new FormControl(&quot;&quot;),<br>    // ! Attention: here it&#39;s a FormControl whose value is an object, NOT a FormGroup  <br>    address: new FormControl&lt;Address&gt;({<br>      city: &quot;Paris&quot;,<br>      street: &quot;rue fortuny&quot;,<br>    })<br>  });<br>}<br><br>// ###########################<br><br>@Component({<br>  selector: &quot;app-address-form&quot;,<br>  template: `<br>    &lt;div [formGroup]=&quot;form&quot;&gt;<br>      &lt;select formControlName=&quot;city&quot;&gt;<br>        &lt;option *ngFor=&quot;let city of cities&quot;&gt;{{ city }}&lt;/option&gt;<br>      &lt;/select&gt;<br>      &lt;input formControlName=&quot;street&quot;&gt;<br>    &lt;/div&gt;<br>  `<br>})<br>class AdressFormComponent extends AbstractSubFormComponent&lt;Address&gt; {<br> cities = [&quot;Paris&quot;, &quot;NewYork&quot;, &quot;London&quot;, &quot;Milan&quot;, &quot;Cologne&quot;, &quot;Tokyo&quot;];<br><br>  // `initialValue` is the value defined in the parent FormControl,<br>  // in this specific case: `{ city: &quot;Paris&quot;, street: &quot;rue fortuny&quot; }`<br>  protected setForm(initialValue: Partial&lt;Address&gt; | null): void {<br>    const { city = &quot;&quot;, street = &quot;&quot; } = initialValue ?? {};<br>    this.form = new FormGroup({<br>        city: new FormControl(city, Validators.required),<br>        street: new FormControl(street, Validators.required),<br>    });<br>  }<br>}</pre><p><strong>Notice:</strong> in PersonForm we only create a simple FormControl for address, and in AddressFormComponent we create a <em>separate</em> FormGroup. The validation and default values are in AddressFormComponent.</p><p>Changes to address are contained within its component.<br>If I want to refactor the cities to an enum, or add validation to the street based on city, I can do that fairly easily. At the same time another dev can add more fields to person (email, date of birth, etc.), without any conflict.<br>Clearly AdressFormComponent is easily reusable.</p><h3>Creating AbstractSubFormComponent</h3><p>AbstractSubFormComponent defines implementation for ControlValueAccessor, requiring an internal form is set. We&#39;ll make it generic, for more helpful typing.</p><p>Let’s start with the skeleton.</p><pre>export abstract class AbstractSubFormComponent&lt;T&gt; implements ControlValueAccessor {<br>    protected form: AbstractControl&lt;T&gt;;<br>}</pre><p>Great! Now let’s implement ControlValueAccessor, step-by-step. We will need to implement the following:</p><ul><li><a href="#a321">writeValue</a></li><li><a href="#aa38">registerOnChange</a></li><li><a href="#0386">registerOnTouched</a></li><li><a href="#33b6">setDisabledState</a></li></ul><h4>writeValue()</h4><p>writeValue() is called whenever the form control value changes in the <strong>parent</strong> component (PersonFormComponent), starting with the initial value.</p><p>So all we need to do is set the value on the form.</p><pre>writeValue(value: T): void {<br>  this.form.setValue(value);<br>}</pre><p><strong>Problem #1: lifecycle order</strong></p><p>writeValue() is called before ngOnInit(), but in our app we initialize forms in ngOnInit().<br>Okay, simple: until we initialize the form, we register any written values in a private field. We then need to ensure that when a subclass initializes the form&#39;s value, it uses this value as the default one.</p><p>One more thing: the parent is able to specify an initial value, but it shouldn’t have to.<br>The SubFormComponent should define defaults.<br>It should be possible for the parent to simply address: new FormControl&lt;Address&gt;().<br>That means we need to support Partial | null with patchValue()</p><p>We’re going to be strict and control the form initialization ourselves:</p><pre>abstract class AbstractSubFormComponent&lt;T&gt; implements ControlValueAccessor, OnInit {<br>  private initialValue: Partial&lt;T&gt; | null;<br>  <br>  protected abstract setForm(intialValue: T | null);<br><br>  writeValue(value: Parial&lt;T&gt; | null): void {<br>    if (this.form) {<br>      this.form.patchValue(value ?? {});<br>    } else {<br>      this.initialValue = this.initialValue;<br>    }<br>  }<br>  <br>  ngOnInit(): void {<br>    this.setForm(this.initialValue);<br>  }<br>}</pre><p>This is what you see in the Address example.</p><p><strong>Problem #2: ChangeDetectionStrategy.OnPush</strong></p><p>You might assume that writeValue() will trigger change detection. I did.<br>But it doesn&#39;t. <a href="https://github.com/angular/angular/issues/44976">https://github.com/angular/angular/issues/44976</a>.<br>Okay, easy enough, manually mark for check:</p><pre>constructor(private changeDetectorRef: ChangeDetectorRef);<br><br>writeValue(value: T | null): void {<br>  if (this.form) {<br>    this.form.setValue(value);<br>    this.changeDetectorRef.markForCheck();<br>  } else {<br>    this.initialValue = this.initialValue;<br>  }<br>}</pre><h4>registerOnChange()</h4><p>This method “Registers a callback function that is called when the control’s value changes in the UI.”<br>In other words, it gives us a callback. Whenever there’s a change in our internal form, call the callback with the new value.</p><pre>private onChange: (value: T) =&gt; void;<br><br>registerOnChange(fn: (value: T) =&gt; void): void {<br>  this.onChange = fn;<br>}<br><br>ngOnInit(): void {<br>  this.setForm();<br>  const subscription = this.form.valueChanges.subscribe(this.onChange);<br>}</pre><p>Of course, always manage your subscription, <a href="https://benlesh.medium.com/rxjs-dont-unsubscribe-6753ed4fda87">however you like</a>.</p><p><strong>Problem: infinite loop!</strong></p><p>Here’s what happens: the user changes something in the sub form, which calls the onChange callback, which updates the parent form, which calls writeValue, which calls the onChange callback ...</p><p>So we need to <em>not</em> trigger valueChanges when we setValue. This is what the emitEvent option is for.</p><p><em>Note: AbstractControl doesn’t document this option, but FormControl, FormGroup and FormArray all support it.</em></p><pre>writeValue(value: Partial&lt;T&gt; | null): void {<br>  if (this.form) {<br>    this.form.patchValue(value ?? {}, { emitEvent: false });<br>    this.changeDetectorRef.markForCheck();<br>  } else {<br>    this.initialValue = value;<br>  }<br>}</pre><h4>registerOnTouched()</h4><p>Similarly to before, we get a callback to decide when our form is considered touched. Presumably, this eventually calls <a href="https://angular.io/api/forms/AbstractControl#markastouched">markAsTouched()</a> on the parent’s control.</p><p>Sadly, there’s no observable for a form’s touched status.<br><a href="https://github.com/angular/angular/issues/10887#issuecomment-481729918">There&#39;s an open issue for it on Angular&#39;s GitHub, with some workaround suggestions</a>, but that&#39;s a bit much for us.</p><p>The methods’ documentation suggests simply listening to the components’ blur event.<br>That almost works for us, but we&#39;ll actually use <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element/focusout_event">focusout</a>, which is similar but also bubbles. What that means is, in AddressSubFormComponent, if I interact with the city input, blur and focusout event will emit. blur will stop at the input, but focusout will bubble up to where I&#39;m listening.<br>We&#39;ll use <a href="https://angular.io/api/core/HostListener">@HostListener</a>:</p><pre>@HostListener(&quot;focusout&quot;)<br>private onTouched = () =&gt; {};<br><br>registerOnTouched(fn: () =&gt; void): void {<br>    this.onTouched = fn;<br>}</pre><h4>setDisabledState()</h4><p>This one is optional, but fairly straightforward:</p><pre>setDisabledState(isDisabled: boolean): void {<br>  if (this.form) {<br>    isDisabled ? this.form.disable() : this.form.enable();<br>  } else {<br>    this.disabledOnInit = isDisabled;<br>  }<br>}<br><br>ngOnInit(): void {<br>  this.setForm();<br>  // Now adding:<br>  if (this.disabledOnInit) {<br>    this.form.disable();<br>  }<br>  // ...<br>}</pre><p>Great! We finished implementing ControlValueAccessor&#39;s methods.</p><h3>Registering as a NG_VALUE_ACCESSOR provider and validating the parent form</h3><p>Implementing an interface isn’t enough for Angular to know our component can be used, because <a href="https://angular.io/guide/dependency-injection-providers#interfaces-and-di">interfaces can’t be dependency injection tokens</a>.</p><p>We need to register our Component as a provider of ControlValueAccessor.<br>As mentioned in Kara’s presentation, the default way of going about this is to add { provide: NG_VALUE_ACCESSOR, ... } to the components&#39; providers[].<br>An alternative is to manually inject the applied NgControl directive (can be [formControl], [formControlName] or [(ngModel)]), and set its valueAccessor property.<br>We will go with the alternative, because we need the &quot;value accessed&quot; control anyway in order to apply the subcomponents&#39; validation on the parent control.</p><p>We’ll follow Kara’s instructions to inject the directive:</p><pre>constructor(<br>  private changeDetectorRef: ChangeDetectorRef,<br>  @Self() private ngControl: NgControl,<br>) {<br>  ngControl.valueAccessor = this;<br>}</pre><p>And here’s the tricky part — add a custom validator that checks our internal form for errors. We need it to be async in case we have async validators ourselves:</p><pre>const subscription = this.form.valueChanges.subscribe(this.onChange);<br>this.controlDir.control.addAsyncValidators(() =&gt; {<br> return this.form.statusChanges.pipe(<br>   startWith(this.form.status),<br>   filter((status) =&gt; status !== &quot;PENDING&quot;),<br>   take(1),<br>   map(status =&gt; status === &quot;INVALID&quot; ? { nestedError: true } : null)<br> );<br>});</pre><blockquote><em>I’m declaring a custom </em><em>nestedError instead of just &quot;bubbling&quot; the errors,<br>because in Angular the </em><em>errors object doesn&#39;t recursively contain the errors of child controls.<br>That is to say, for </em><em>myForm: FormGroup&lt;{ name: ... }&gt;, if </em><em>name is invalid, myForm will be invalid, but </em><em>myForm.errors will be an empty object.</em></blockquote><p>We also need to update the validity of the parent form for the default value.<br>The only way to do that is to call <a href="https://angular.io/api/forms/AbstractControl#updatevalueandvalidity">updateValueAndValidty()</a>, which of course also updates the value, triggering valueChanges, meaning we should call it <em>before</em> we subscribe to valueChanges with the onChange callback:</p><pre>ngOnInit(): void {<br>  // ...previous code<br>  this.controlDir.control.addAsyncValidators(() =&gt; {<br>      // ...<br>  });<br>  // Make sure the initial value is validated by this component<br>  this.controlDir.control.updateValueAndValidity();<br>  // handle subscription somehow<br>  const subscription = this.form.valueChanges.subscribe(this.onChange);<br>}</pre><p><strong>Issue: </strong><strong>ngChanges() and </strong><strong>dirty</strong></p><p>The ngChanges() callback we receive marks the FormControl in the parent as <a href="https://angular.io/api/forms/AbstractControl#dirty">dirty</a>, <em>always</em>.</p><p>This means that we can’t update the value without also marking the parent as dirty.<br>This is an issue because updateValueAndValidy() triggers valueChanges.</p><p>We tried a workaround to manually set the form as pristine again:</p><pre>this.form.valueChanges.subscribe(change =&gt; {<br>  this.onChange(change);<br><br>  if (this.form.pristine) {<br>    this.controlDir.control.markAsPristine();<br>  }<br>});</pre><p>But we quickly ran into edge cases when nesting several layers of SubFormComponents.<br>You could probably figure out a way to make it work, but sadly I don’t have an easy solution today.</p><p><strong>Why is this important?</strong> Well, in our use case, we reuse the form for editing existing graphs.<br>We want to disable form submission if there are no changes, for a) better UX and b) avoiding extra computation.</p><blockquote><em>While researching for this article, I found </em><a href="https://blog.richardhunter.co.uk/index.php/article/19"><em>this article by Richard Hunter</em></a><em>, which helpfully clarifies and even corrects some points on Kara’s presentation.<br>I now suspect a better approach than mine would be to register as a provider of </em><em>NG_VALUE_ACCESSOR and </em><em>NG_VALIDATORS. I&#39;ll have to clear time to test that, and check if it stays easily usable with an abstract base class.</em></blockquote><h4>Note on testing with @Self:</h4><p>To test SubFormComponents, we need to configure a provider for NgControl. Usually, you’d do it like this:</p><pre>TestBed.configureTestingModule({<br>  providers: [{<br>    provide: NgControl,<br>    useFactory: () =&gt; ({<br>      control: new UntypedFormControl()<br>    })<br>  }]<br>});</pre><p>But that would provide it in the testing module. We need to inject it in the component itself (@Self).<br>You can do so by using <a href="https://angular.io/api/core/testing/TestBed#overridecomponent">TestBed.overridecomponent()</a> to add the mock NgControl to the components&#39; providers.<br>In our code base, we made a helper for this:</p><pre>// provide-self-ngcontrol.mock.spec.ts<br>export function provideMockSelfNgControl(<br>  testBed: TestBed,<br>  component: Type&lt;unknown&gt;<br>): void {<br>  const provider: FactoryProvider = {<br>    provide: NgControl,<br>    useFactory: ()  =&gt; ({<br>      control: new UntypedFormControl(),<br>    }),<br>  };<br>  testBed.overrideComponent(component, {<br>    add: {<br>      providers: [provider],<br>    },<br>  });<br>}<br><br>// my-sub-form.component.spec.ts<br>const testBed = TestBed.configureTestingModule({<br>  declarations: [MySubFormComponent]<br>  // ...<br>});<br>provideMockSelfNgControl(testBed, MySubFormComponent);</pre><h3>Full example</h3><p>You can see a full example app <a href="https://github.com/StavNoy/SubFormComponent-breaking-down-angular-forms/tree/main/example-app">here</a>. Excuse the lack of design, I wanted to keep it simple.</p><h3>Conclusion</h3><p>This is just one possible solution to what I consider to be a fairly common problem: splitting a single form over multiple components, either because the form is complex or because parts of it can be reused. It has worked well enough in our use case, certainly much better than what we had before.<br>You may very well find alternatives that suit you better, or improvements to this solution. If you do, let me know. :)<br>Certainly, the research and implementation on this have given me a much better understanding of Angular, not just the forms, but also Dependency Injection and the lifecycle.<br>I hope this article gives you value as well.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a2ced2fef96" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akur8/breaking-down-angular-forms-at-akur8-6a2ced2fef96">Breaking down Angular forms</a> was originally published in <a href="https://medium.com/akur8">Akur8</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-demanding cloud computing using AWS Batch & ECS]]></title>
            <link>https://medium.com/akur8/high-demanding-cloud-computing-using-aws-batch-ecs-9cf39a2b292c?source=rss----b90fc781dda5---4</link>
            <guid isPermaLink="false">https://medium.com/p/9cf39a2b292c</guid>
            <category><![CDATA[ecs-fargate]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[aws-batch]]></category>
            <dc:creator><![CDATA[wlv]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 07:58:35 GMT</pubDate>
            <atom:updated>2023-11-15T12:59:59.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZWfHfZj6YdHck8L0mR8l7A.png" /></figure><h3>Introduction</h3><p>In this article, we will present how we at Akur8 solved a common task scheduling problem using AWS Batch and ECS Fargate.</p><h4>About AKUR8</h4><p><a href="https://akur8.com/">AKUR8</a> is revolutionizing insurance pricing with Transparent AI, boosting insurers’ pricing capabilities with unprecedented speed and accuracy across the pricing process without compromising on auditability or control.</p><p>Akur8&#39;s modular pricing platform automates technical and commercial premium modeling. It empowers insurers to compute adjusted and accurate rates in line with their commercial strategy while materially impacting their business and maintaining absolute control of the models created, as required by regulators worldwide.</p><h3>Use case</h3><p>Let’s start with a simplified diagram of the AKUR8 platform at its beginning:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1FLKrsuH1m9AkEj_84nD0Q.png" /></figure><p>The need to do relatively long computations quickly arose, therefore we didn’t want to use the API server for this task. This decision was made to ensure that users&#39; interactions with the platform would not be degraded with large, ongoing computations. Consequently , like many other software companies, we needed to run asynchronous jobs, which in our case was potentially 300+ in parallel.</p><p>These jobs can be relatively simple, but they can also be very complex and resource-demanding. For instance, depending on the context and the user database, a single job can consume up to 500 GB of memory and could require a few seconds to several hours to run.</p><p>We could not continue to keep large machines running because it would be far too expensive. Instead, we searched for a service that allows running machines on demand, while only paying for its actual use. At that time we were mainly based on AWS, so we decided to use AWS Batch.</p><h4>AWS Batch Definition:</h4><blockquote>AWS Batch helps you to run batch computing workloads on the AWS Cloud. Batch computing is a common way for developers, scientists, and engineers to access large amounts of compute resources. AWS Batch removes the undifferentiated heavy lifting of configuring and managing the required infrastructure, similar to traditional batch computing software. This service can efficiently provision resources in response to jobs submitted in order to eliminate capacity constraints, reduce compute costs, and deliver results quickly.</blockquote><p>Source: <a href="https://docs.aws.amazon.com/batch/latest/userguide/what-is-batch.html">What Is AWS Batch?</a></p><h3>Jobs definition</h3><p>Once we decided to use AWS Batch, we needed to define what will represent a job.<br>Each job is defined as a sequence of smaller unitary tasks, which is important for parallelization and code reuse.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/1*U4JgnCJ5Jku3mVi0ssfquQ.png" /></figure><p>Currently , we do not use multi-threading to speed up processing. Instead, when possible, we split a large task into parallelizable tasks, and utilize AWS Batch’s ability to spawn multiple machines to run them in parallel (cf. <em>Task 2</em> &amp; <em>Task 3</em>). One of the main advantages of this approach is gaining the ability to simplify the code base so that we don’t have to manage multi-threading constraints.<br>Also, if everything was on a single machine using multi-threading, the machine would have to be sized to the most resource-demanding task. If one of the tasks lasted a long period of time, this practice could become very costly.This AWS Batch approach helped optimize machine costs since each task has different CPU and memory needs. The code of each unitary task is packaged into a single docker image that is used by each job.</p><p>We modeled the job as a structure that holds the sequencing and state of each task. From there, a solution to schedule tasks 2 and 3 when task 1 terminates had to be found. We could have assumed that the responsibility of the task is to update its state and schedule the next tasks. However, since tasks are subject to multiple kinds of failures, such as “Out Of Memory” errors, it can quickly become troublesome if task 1 fails. (inconsistent job states.)<br>Therefore, we decided to add a new service to our architecture where we would centralize the scheduling logic and mutations of the job structure. We called it the task scheduler.</p><h3>Task scheduler</h3><p>The mission of the task scheduler is to track the status and schedule in the correct order each job task. Below is the previous diagram updated with the scheduler service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2c3haNeW4uk6VObtvcrplw.png" /></figure><p>The service databases are separated from the applicative databases.<br>We designed the service to be event-driven (<em>learn more about event-driven programming</em><a href="https://en.wikipedia.org/wiki/Event-driven_programming"><em> here</em></a>), and currently have 9 different events.</p><p>This pattern made debugging and concurrency handling easier (cf. following part on service redundancy). The only way to send an event to the task scheduler is through a single HTTP endpoint. The event would then be pushed to a Redis queue where one thread of the task scheduler is listening.</p><p>Below is an example of the events lifecycle of a job:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*Rc9p7ucGaP-0BMs2mn1wjw.png" /></figure><p>Each event has its own processing strategy, which mutates the job state and publishes the following events.</p><h3>Service redundancy</h3><p>Redundancy is a mandatory constraint when deploying a service in production.. It means at least two instances of the service must always be running, and therefore two services are concurrently dequeuing events. That concurrency factor has to be handled properly, otherwise it can quickly lead to job state corruption. This happens if two events related to the same job are being processed at the same time and write the job state simultaneously. To deal with that, we made use of <a href="https://redis.io/docs/manual/patterns/distributed-locks/">Redis distributed locks</a> — a distributed lock mechanism that includes the<a href="https://redis.io/docs/manual/patterns/distributed-locks/"> </a>incredible Java implementation<a href="https://github.com/redisson/redisson"> Redisson</a>. <br>With a distributed lock on the job identifier, we ensured that only one event related to that job would be processed at the same time, guaranteeing consistency of the job state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*7GDSYsIb8BqAl9qtp9LS5A.png" /></figure><p>However, we must be cautious as it has some caveats that are well explained in the Redis documentation. Make sure it suits your use case before using it.</p><h3>Problems we faced</h3><ol><li><em>AWS Batch was slow to start a task<br></em>We estimated that the time the AWS Batch took to start the task was 3 minutes. This included finding the machine, booting the machine if it was necessary, loading the docker image, and the time for the process to initialize. This is not a big deal if the task is part of a job that takes much longer to compute, but we had jobs we wanted to run in a few seconds. <br>Hence, to improve the starting time we reserved a machine on ECS that would only process fast, and low resource demanding tasks It is the responsibility of the task scheduler to submit the task to ECS or AWS Batch depending on the nature of the task.</li><li><em>Properly dimension the computing environment so the databases are not overloaded.<br></em>When using AWS Batch you must define at least one compute environment For each environment you must define the maximum amount of resources that can be used. <br>An issue we had was putting that value too high, hence we had too many jobs in parallel which killed our database. <br>So, we had to fine-tune the resources allocated to the compute environment to make sure to control the maximum amount of tasks running in parallel, and ensure the database would survive the load.</li><li><em>Unexpected failures<br></em>AWS Batch would fail to run the task with the following error: “<em>Essential container exited</em>” before the machine even gets started. <br>This was slightly problematic due to our design. The task scheduler had no way of knowing that the task had failed because failed events were received by the task itself.<br>So, we had to add a polling system within the task scheduler that would occasionally check the status of tasks that didn’t get updated for a certain period of time. <br>Today we’re working on a solution that would make use of AWS SNS/SQS to be able to react instantly to this kind of error. This was made easy by<a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-aws/2.0.0.RELEASE/multi/multi__messaging.html"> Spring Cloud</a>.</li></ol><h3>Conclusion</h3><p>AWS Batch is a great way to run jobs demanding large resources at a minimum cost, without having any machines to manage. <br>The only drawback is the starting time. Therefore our team is considering using native JVM to improve it, and potentially splitting our single docker image.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9cf39a2b292c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akur8/high-demanding-cloud-computing-using-aws-batch-ecs-9cf39a2b292c">High-demanding cloud computing using AWS Batch &amp; ECS</a> was originally published in <a href="https://medium.com/akur8">Akur8</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving the reliability of web applications with Storybook and Chromatic]]></title>
            <link>https://medium.com/akur8/improving-the-reliability-of-web-applications-with-storybook-and-chromatic-1e12d1250f97?source=rss----b90fc781dda5---4</link>
            <guid isPermaLink="false">https://medium.com/p/1e12d1250f97</guid>
            <category><![CDATA[storybook]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[web-applications]]></category>
            <category><![CDATA[chromatics]]></category>
            <category><![CDATA[documentation]]></category>
            <dc:creator><![CDATA[Evan Ollivier]]></dc:creator>
            <pubDate>Thu, 06 Apr 2023 08:22:02 GMT</pubDate>
            <atom:updated>2023-11-15T10:47:51.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nT1obXe91q2bR--P5jMx6w.png" /></figure><p>As a software company grows, maintaining the consistency of the UI of a web application can become difficult. The processes that used to work smoothly with 10 developers can become a struggle when the team is growing rapidly.</p><p>While it’s obvious for developers to provide integration and unit tests in their applications, testing user interfaces can be more difficult for many reasons:</p><ul><li>Our eye is not pixel-perfect, it’s easy to miss an<strong> inconsistent font size or color</strong> in your application, especially if it contains multiple screens, pop-ups, different states.</li><li>Unit testing can check to make sure the logic of your components functions properly, but it can’t ease the process of ensuring that your <strong>components always match their mockups</strong>.</li></ul><p>You might not have defined front-end guidelines or a design system when you started building your application, and <strong>there is no “one way” to build new components</strong>. Documentation could be nonexistent, fuzzy or difficult to maintain, which leads to error prone implementation.</p><h3>Why front-end component documentation matters</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*TeoUeoluiKTE9YRcS_AhhA.png" /><figcaption>Our criteria to document our code</figcaption></figure><p>Maybe you have used documentations tools such as confluence or a documentation shared folder.</p><p>While these tools can be handy for onboarding guides, technical articles or architectural documentation, they perform poorly when it comes to documenting code or UI components.</p><p>For example, when you edit part of your application, sometimes you may not be aware that it already has existing documentation, or you might forget to update the docs after editing the components.<br> <br><strong>How can I maintain a proper front-end code documentation ?</strong></p><p>Google provides an interesting example of how <a href="https://material.angular.io/components/icon">Material components should be used in Angular</a>. Creating the same kind of “technical design-system” documentation should allow for better collaboration and code-quality amongst your team.</p><p>Storybook is a “frontend workshop for building UI components and pages in isolation”.</p><p>Developed by Chromatic, this tool allows you to <strong>create an interactive playground for your components, and markdown documentation pages.</strong></p><p>Using Storybook as front-end code documentation will allow developers to set up the guidelines and best practices needed to build new components.</p><p>Having a complete and up-to-date component library also allows for faster onboarding with concrete examples displaying how your application’s components behave in response to specific inputs.</p><p>For experienced developers, this solution can help gain a quick overview of the base components their application relies on.</p><p>Sharing UI design guidelines and concrete usage examples on front-end components can help developers coordinate their coding process and improve their understanding of each other’s code.</p><h3>Storybook, a solution for testing and documenting your code</h3><p>Storybook is the tool we choose to document our components at Akur8. It includes many features, such as:</p><ul><li>Markdown documentation for components</li><li>Visual component testing with Chromatic</li><li>Integration with Figma to compare components to our design system</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JMFVAcgVrtuCwo8cPGbgMg.png" /><figcaption>An example of component documentation using Storybook.</figcaption></figure><p>The concept behind Storybook is that for every component you create, you can create a story with custom input parameters. You can hardcode them in the story or edit them yourself to see how the component behaves in your browser.</p><p>For example, in the screenshot above, component inputs (displayed under “controls”) are editable from Storybook’s UI. Changing the value of these inputs will instantly be reflected on the component preview.<br>This feature allows you to check for edge-cases that your components would rarely encounter; such as very long titles, specific theming,..</p><p>Storybook allows you to interact with components’ inputs, by providing use tools such as color pickers, date pickers, text and number inputs, checkboxes, radio inputs and more.</p><p>In addition to component documentation, Storybook allows you to write markdown documentation to help your team understand the structure of your shared component library, its setup and its usage.</p><h3>The issues we aimed to solve with Storybook</h3><p>We worked with the development team to conduct a survey about the major pain-points encountered in our daily work. The top responses were the following:</p><blockquote>• Low component reusability<br>• Relevant test writing<br>• UI inconsistencies<br>• Difficult icon management</blockquote><p>These 4 pain-points could be assessed by Storybook and related tools, so we decided to conduct a proof of concept with it.</p><p>In this first article, we will discuss the setup of the solution, handling of UI inconsistencies and icon management.</p><p>Test writing and component reusability will be discussed in an upcoming article.</p><p><strong>Why did we choose component testing ?</strong></p><p>A few month ago, we spotted an unusually high number of front-end bugs during several sprints. We tried to estimate the amount of time required to fix them all, and we concluded that on average two developers were working full-time to fix front-end bugs in our application.</p><p>Another issue is that we often discovered last minute bugs 48h before the release (we ship every 3 weeks).</p><p>Despite the efforts made to keep our unit test coverage and end-to-end test coverage as high performing as possible, there were some issues. This problems were often related to UI regressions that were not recognized by these tests and were noticed last minute.</p><p>Unit tests are there to make sure your logic works properly, and E2Es insure proper communication between the front-end and the back-end.<br>However, no tool could check the consistency of our designs, therefore we chose to experiment with Storybook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f9-Wukh1BU4YkliBdLb0vQ.png" /><figcaption>Our estimations from the inspection of the bug tickets we had open</figcaption></figure><h3>Hands-on Guide: set up and use Storybook in your Angular project</h3><p>You will find the official documentation explaining how to set up Storybook on Angular <a href="https://storybook.js.org/docs/angular/get-started/introduction">here</a>. Other guides are available for the most common web frameworks such as Vue or React.</p><pre># This guide is designed for storybook v7 beta,<br># When stable version will be published, just use :<br># npx storybook init<br><br>npx storybook@next init</pre><p>This command should generate a configuration directory for Storybook “.storybook” and add samples stories inside of /src/stories.</p><p>This command should also update your angular.json file with two new run configurations for storybook (serve) and storybook-build, useful for CI integration.</p><p>To launch Storybook, you can use :</p><pre>npm run storybook</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*swZeASoLEjUMaWeYSP0rug.png" /><figcaption>Storybook startup shell</figcaption></figure><p>When Storybook is ready, you should see the following in your console. Then you can open your web browser on the url indicated here: <a href="http://localhost:6006/">localhost:6006</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T2O7CVofYFuTNcozSdjzZw.png" /><figcaption>Storybook’s boilerplate introduction</figcaption></figure><h4>Writing down your first Story — Generating Tailwind’s theme documentation</h4><p>One of the benefits of using Storybook to document your application is that you can create dynamic documentation that will evolve with the code you are writing.</p><p>At Akur8, we are using <a href="http://tailwindcss.com/">Tailwind CSS</a> to style our application, and Storybook provides us with a way to document our extension of Tailwind’s default classes.</p><p>To import Tailwind’s styles into Storybook, we can create a new preview-head.html file inside of .storybook. This file will be loaded in the &lt;head&gt; of all your stories.</p><pre>&lt;!-- .storybook/preview-head.html --&gt;<br>&lt;link href=&quot;/assets/tailwind.css&quot; rel=&quot;stylesheet&quot; /&gt;</pre><p>Now, we can write our first story !</p><p>I just started by generating a new Angular component, you can find the full code here: <a href="https://github.com/bzh2610/Storybook-Tailwind">https://github.com/bzh2610/Storybook-Tailwind</a></p><p>This component retrieves the contents of tailwind.config.js and displays all of the colors of the extended theme inside of a new container in the HTML.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76f4b867e82b39fdcdb8f20233dfbc55/href">https://medium.com/media/76f4b867e82b39fdcdb8f20233dfbc55/href</a></iframe><p>Since Tailwind’s configuration is written in JavaScript it’s easy to import inside of Storybook to generate documentation from it.</p><p>Since Angular uses Typescript, you may have to update .storybook/tsconfig.json to allow loading of JS from a Typescript file:</p><pre>.storybook/tsconfig.json</pre><pre>{<br> ....<br> &quot;compilerOptions&quot;: { <br>  ...<br>  &quot;allowJs&quot;: true<br>  }<br>}</pre><p>The Story file is shown below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aac2756a742a6cf8c0515041e492b5f/href">https://medium.com/media/0aac2756a742a6cf8c0515041e492b5f/href</a></iframe><p>It exports a “Colors” story that displays the ColorsComponent. This is the most basic type of Story you can write with Storybook, but we could pass input parameters, custom documentation, and more.</p><p>Here is the output of this Story: an auto-generated Tailwind custom theme documentation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QmSa6VIvl9sPMGjT6H00fQ.png" /><figcaption><em>In this example, the colors are automatically retrieved from tailwind’s configuration and displayed in our documentation.</em></figcaption></figure><p>You can find documentation on how to add Tailwind to a Storybook project here: <a href="https://storybook.js.org/recipes/tailwindcss">https://storybook.js.org/recipes/tailwindcss</a></p><h4>Identifying the limits of your existing code</h4><p>When we started to documenting our shared module with Storybook, we noticed our components could technically reach a state that was not solicited in our application, and identify some of the possibilities of future bugs and bottlenecks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f1yhe3MJdDzMbujDpezD4Q.png" /><figcaption>Example of unreachable state in our application, the button in the dropdown was disabled but the icon linked to it was still using an ‘active’ color.</figcaption></figure><p>Noticing these issues with Storybook allowed us to expand the range of possibilities for our existing components, and share knowledge with our design team regarding which UI improvements were easy to implement from our existing code.</p><p>Using the Figma plugin, we were also able to do a side-by-side comparison of the components when looking at the screens created by our design team. We were then able to quickly identify missing colors or name discrepancies within our configuration.</p><h4>Generating dynamic font documentation</h4><p>Similar to how Google font allows for material icons, we were able to replicate Tailwind’s dynamic documentation with our icons-fonts, to create a searchable documentation.</p><figure><img alt="Webpage with search-bar looking up for icons" src="https://cdn-images-1.medium.com/max/1024/1*wOJ1jbTjtL3XuzgsKzW2zA.png" /><figcaption>Example of icon search with a Storybook component. The icon’s list is automatically retrieved from a CSS file.</figcaption></figure><h3>Chromatic: a UI testing solution</h3><p>Chromatic defines itself as a tool which <em>“automates gathering UI feedback, visual testing, and documentation, so developers can iterate faster with less manual work.</em>”</p><p>When we think about testing softwares, unit tests, integration tests and end-to-end tests often come to mind. Usually these tests are designed to ensure the non-regression in terms of features, however they rarely break when changes impact the design of the components.</p><p>Chromatic integrates with Storybook to allow for components’ UI testing.<br>This will ensure that all the elements of your web page will stay consistent over time.</p><p>If you want to try-out Chromatic locally, you can create an account at <a href="https://www.chromatic.com/">chromatic.com</a> and create a new project.</p><p>When you create a new project at Chromatic, you will be given a command to type in your project like below:</p><pre>npm install --save-dev chromatic<br>npx chromatic --project-token=YOUR_PROJECT_TOKEN</pre><p>This command will build a version of your storybook based on the last commit of your working branch. It will then push it to Chromatic so you can preview your storybook online.</p><p>Once the first build is complete and your story has been uploaded, make changes to the component in your story to watch Chromatic’s visual changes detection in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tNFW5UP6fgwq02bKhx50yA.png" /><figcaption>One visual change found !</figcaption></figure><p>You can notice the slightest change in terms of padding or margin, and ensure the consistency of all elements contained inside of HTML Canvas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MW0RywRHfibUILTocppdqw.png" /><figcaption>Padding / Margin change detection example using Chromatic</figcaption></figure><p>When your pull request affects one of the existing components snapshot, Chromatic will ask you to review it, you can then accept or decline the changes.</p><p>This will not prevent every UI bugs (e.g: scrollbars are not handled by Chromatic yet). However, it should allow you to merge code with more confidence regarding the impact it will have on component’s design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*AdHwDlwgkzW4jeH28e-Ngg.gif" /><figcaption><em>Here, you can see this change detection noticed the changes on the blue and orange colors, which I inverted, but not between the 3rd and 4th color, where it only noticed a change in HEX code representing the color.</em></figcaption></figure><p>According to whether the modifications you see are intended you can update the Storybook build status by clicking “Accept” or “Decline” in the updated components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M6y1xYexXUk490agf3zyLg.png" /><figcaption>An example of manually declined change to a component. Chromatic only displays the updated files in this list.</figcaption></figure><p>If you want to push the experiment further, Chromatic integrates well with most CIs. You can find instructions here: <a href="https://www.chromatic.com/docs/ci">https://www.chromatic.com/docs/ci</a></p><p>⚠️ When you generate tokens to use in 3rd party services, don’t forget to<strong> set the permissions of your token accordingly</strong>. Chromatic solely requires read access to the files of your repository.</p><p>For further security, you can choose to specify a commit hash corresponding to the version of the CI action you want to use, this will prevent potential harmful code injection inside of the action.</p><pre># Use<br>action@HASH_MATCHING_LATEST_VERSION<br># instead of<br>action@v1.</pre><p>ℹ️ If you choose this option, don’t forget to stay up to date with the latest news from the developers of the action to still be able to get the latest security updates.</p><p><strong>Cost of the solution</strong></p><p>Chromatic runs are a bit more expensive than standard unit test runs. You will find below the pricing estimates based on 100 commits/month.</p><p>The left graph displays the pricing for 1 run on each pull request. After merge, the right graph displays the pricing for 3 runs per pull request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*radooycDD0fKY8Croz0WPQ.png" /></figure><p>Chromatic pricing is based on the number of snapshots you take per month. For each story you declare in Storybook, there will be one screenshot. Because of this, it’s not unusual to have 3–4 snapshots per components, depending on their complexity.</p><p>💡To spend wisely on Chromatic, I would advise to wrap small components you want to test inside of a wrapper component, like we did for the icons page.</p><p>This will allow you to only have to take one screenshot, but have the ability to test the same component throughout various states.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7pH1iOJ8Y1yvUn178kbnQ.png" /><figcaption>E.g: Material’s button list. Testing each button separately will cost between 0,18$ — 0,30$/run once you max out the included snapshot tier of your plan.</figcaption></figure><h4>Pros and cons of using Storybook for development</h4><p><strong><em>Advantages of using Chromatic</em></strong></p><p>✅ A convenient way to document your code</p><p>✅ It is a visual and interactive tool that can improve collaboration between Design, Product and Development teams</p><p>✅ Quite easy to setup - component configuration is very similar to Jasmine’s / Jest’s unit tests</p><p>✅ MDX is a powerful documentation tool</p><p>✅ Play functions allow for testing inside of Storybook</p><p><strong><em>Limitations when using Chromatic</em></strong></p><p>❌ Color accuracy is limited</p><p>❌ Non-DOM elements (like the presence of a scrollbar) cannot be tested for</p><p>❌ No “offline mode” to use visual testing in local</p><p>❌ Chromatic pricing is difficult to estimate until you set up a first set of stories and a CI/CD pipeline</p><p><em>Useful links:</em></p><ul><li><a href="https://www.chromatic.com/docs/">Why Chromatic? * Chromatic docs</a></li><li><a href="https://storybook.js.org/docs/angular/writing-docs/docs-page">DocsPage</a></li><li><a href="https://tailwindcss.com/docs/installation">Installation - Tailwind CSS</a></li><li><a href="https://github.com/bzh2610/Storybook-Tailwind">GitHub - bzh2610/Storybook-Tailwind</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e12d1250f97" width="1" height="1" alt=""><hr><p><a href="https://medium.com/akur8/improving-the-reliability-of-web-applications-with-storybook-and-chromatic-1e12d1250f97">Improving the reliability of web applications with Storybook and Chromatic</a> was originally published in <a href="https://medium.com/akur8">Akur8</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>