<?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 Sam Selikoff on Medium]]></title>
        <description><![CDATA[Stories by Sam Selikoff on Medium]]></description>
        <link>https://medium.com/@sam.selikoff?source=rss-4bebdc004c4c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_wnCNx2Usa67BsSh7FYXHg.jpeg</url>
            <title>Stories by Sam Selikoff on Medium</title>
            <link>https://medium.com/@sam.selikoff?source=rss-4bebdc004c4c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 03:56:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sam.selikoff/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[Building a sticky chatbox]]></title>
            <link>https://medium.com/embermap/building-a-sticky-chatbox-3d50272c2e0c?source=rss-4bebdc004c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d50272c2e0c</guid>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sam Selikoff]]></dc:creator>
            <pubDate>Tue, 01 Nov 2016 15:36:13 GMT</pubDate>
            <atom:updated>2016-11-04T17:24:40.410Z</atom:updated>
            <content:encoded><![CDATA[<h4>Group learning at Ember NYC’s September project night</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMP7-glqw-Oh4OYnTXz8gw.png" /><figcaption>Sonja Langfordvia <a href="https://unsplash.com/photos/RQHzRELE2Ss">unsplash</a></figcaption></figure><p>Last month I hosted Ember NYC’s project night, and the audience and I built a sticky chatbox component together. My goal wasn’t to end up with a prefabricated solution for everyone to use; instead, I wanted to work through the problem as a group, discussing our thought process and opinions as we went along.</p><p>I built this component last summer as part of a client prototype and found it an interesting and fun challenge. It looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*rjMhcSv9QyjHrmK9vqN5Qw.gif" /><figcaption>A plain div on the left, and our sticky chatbox on the right</figcaption></figure><p>Normally, when a scrollable &lt;div&gt; gets new content, its scrollbar is unaffected. You can see on the left that to keep reading, the user must scroll the chatbox each time a new message comes in.</p><p>The sticky chatbox on the right is different. When the user is scrolled to the bottom, new messages appear and “push” the chat log up, so the user doesn’t have to keep scrolling. But, if the user scrolls back up to read through older messages, the chat box doesn’t snap to the bottom. The scrollbar stays in place, so the user isn’t interrupted while reading through the log. This is the behavior found in most modern chat apps like Slack and Twitch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*DDXiSnPRjWaL0nJqpwhB1Q.gif" /><figcaption>Twitch’s chat is sticky, which makes it easy to keep up with the Internet’s most mature audience</figcaption></figure><h3>My approach</h3><p>When writing complex components, I like to start by identifying the various states in which the component can exist. Identifying state can be tricky; sometimes I find it helpful to try to explain how the interface should behave as if I were talking to a non-technical business or product person. How might we talk about this component together?</p><blockquote>When the user is scrolled to the bottom, new messages should show up. If they scroll up to read old messages, the chat should stay still.</blockquote><p>From this plain-English description, the states of the component jump out at us:</p><ol><li>The user is scrolled to the bottom</li><li>The user is not scrolled to the bottom</li></ol><p>Of course, we can think of other states in which the component could exist — for example, if the user was scrolled to the top — but those states aren’t relevant here, since they don’t affect behavior. The only states that affect behavior are the two we’ve listed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1EHxfCgN8km-7WRZkUQnMw.png" /><figcaption>The two possible states of our component: scrolled to bottom (left) and not (right)</figcaption></figure><p>Given these possible states, I gave my component an isScrolledToBottom boolean property that I could use to adjust the component’s scrolling behavior. I then needed to update this property every time the state of the component changed.</p><p>How might I achieve this? The first thing that came to mind was an addon I had used in previous projects: DockYard’s <a href="https://github.com/dockyard/ember-in-viewport"><em>Ember In Viewport</em></a>. This addon lets you render a component to the screen that fires an action whenever that component enters or exits the viewport.</p><p>Sounds like just what I needed. If I rendered this component at the end of the chat list, I‘d then be able to know whenever the user reached the bottom, and set the state accordingly. If they started scrolling up to read old messages, the component would leave the viewport, and I’d be able to use another action to update the state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Z-1zRILm1wGAYkZskr-GA.gif" /><figcaption>The {{in-viewport}} component in action, at the end of the messages list</figcaption></figure><p>So, I wrote a simple {{in-viewport}} component using the mixin from the addon. You can see the full implementation of that component in the Twiddle below. I then used it in my component’s template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c8ab795af0fb1e1be0e607e7b93c2e6/href">https://medium.com/media/9c8ab795af0fb1e1be0e607e7b93c2e6/href</a></iframe><p>All that remained was to write the component’s behavior. If the user was scrolled to the bottom, the component’s &lt;ul&gt; should scroll down each time a new message was rendered. The scrolling should happen after the new message was appended to the DOM — sounds like a perfect use case for the <a href="http://emberjs.com/api/classes/Ember.Component.html#method_didRender">didRender</a> hook:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e4b8bdae6d78e39ca8debd4b392f9af/href">https://medium.com/media/2e4b8bdae6d78e39ca8debd4b392f9af/href</a></iframe><p>Et voilà! Our chat box lets the user read through the backlog, and then autoscrolls when they’re all caught up.</p><p>Check out this Twiddle for a full working example:</p><p><a href="https://ember-twiddle.com/92b9e154ed4b8dc554727bf794da88f6?openFiles=templates.components.chat-box.hbs%2C">Ember Twiddle</a></p><h3>The group’s approach</h3><p>To my delight, several members of the group from the project night suggested a completely different strategy. The idea was simple: check the state of the scrollbar the moment a new message arrives. If the scrollbar was at the bottom, autoscroll the chatbox; otherwise, leave it alone.</p><p>We still needed to store the state of the scrollbar, so we kept the isScrolledToBottom property; but now, we needed to set this property whenever the component was about to re-render.</p><p>It took a bit of experimentation. We started out by trying to calculate the scroll position at the beginning of the didRender hook. The problem here is that in didRender, the chatbox had already been updated — so even if the user <em>had</em> been scrolled to the bottom, the fact that the new message had already been appended meant they no longer were.</p><p>Eventually we realized that we needed to calculate the scroll position just <em>before</em> the new message was added to the DOM. We pulled up the guides for a component’s <a href="https://guides.emberjs.com/v2.9.0/components/the-component-lifecycle/#toc_on-re-render">re-render lifecycle hooks</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*knXK5_N3-3-4MElfHvOqCA.png" /><figcaption>Component initial and re-render lifecycle hooks</figcaption></figure><p>Both willUpdate and willRender seemed like good candidates. Looking at the documentation for each, we found that <a href="http://emberjs.com/api/classes/Ember.Component.html#method_willRender">willRender</a> is called on both initial render and re-renders, while <a href="http://emberjs.com/api/classes/Ember.Component.html#method_willUpdate">willUpdate</a> is only called on re-renders. Since we only cared about new messages, we went with willUpdate.</p><p>After a little more experimentation, we were able to write a formula to calculate the state of the scrollbar. We then used this formula to set the component’s state in willUpdate:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/666c9b43d187c12a002acec4b243fd51/href">https://medium.com/media/666c9b43d187c12a002acec4b243fd51/href</a></iframe><p>Now the state would be correct even after the new messages were appended, so the code in didRender worked just as before. Cool!</p><p>Here’s the Twiddle:</p><p><a href="https://ember-twiddle.com/bfca7855e100560b62651f0cb7673963?openFiles=components.chat-box.js%2C">Ember Twiddle</a></p><h3>Tradeoffs</h3><p>After going through both solutions, Luke Melia pointed out that spying on scroll behavior is quite expensive (which is why the Ember In Viewport addon makes you explicitly opt-in to this behavior). He said that using the first approach could significantly affect performance, especially on mobile. In many cases, then, the willUpdate solution would be the superior choice.</p><p>For our demo app, the willUpdate solution was sufficient — the only time we used the isScrolledToBottom property was when re-rendering the list. If you open the Twiddle, however, you’ll notice that the state of our component can “lie”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*A2GnvE97x1Xa40Xazm4NVA.gif" /></figure><p>If you scroll the chatbox after a new message has been rendered, you‘ll notice that the isScrolledToBottom property won’t change right away; in fact, it won’t update to reflect the “true” state of the scrollbar until the next message arrives.</p><p>If we were to add additional behavior to this component that relied on isScrolledToBottom being accurate, we could run into some issues. How might this happen? You could imagine updating the interface to show an indicator that new messages had arrived. You’d want that indicator to clear once the user had read through all the messages. In this case, there could be a long time between when the user had caught up and when the next message arrived, so the interface could fall “out of sync” with the actual state of the user’s behavior.</p><p>This is just one example of something that could affect your decision. Different approaches often favor competing goals, like performance versus accuracy. It’s up to you to decide which strategy is most appropriate based on the unique priorities and needs of your application.</p><h3>Conclusion</h3><p>Building the sticky chatbox as a group helped us all see the problem with a bit more clarity. We learned</p><ul><li>Spying on viewport scrolling is expensive, and should only be done when necessary.</li><li>The willRender and willUpdate hooks are a great place to take measurements or perform visual calculations on a component’s DOM before Ember re-renders it.</li><li>The didRender hook is useful if you need to update a component’s DOM in response to a re-render, for example after the component receives new attrs.</li><li>Nearly all design decisions have tradeoffs.</li></ul><p>So reference the API docs often, keep pairing, and if you’re in New York be sure to join us at <a href="https://www.meetup.com/EmberJS-NYC/">Ember NYC’s</a> next Project Night!</p><p><em>Hungry for more? Check out </em><a href="https://embermap.com/"><em>embermap.com</em></a><em> for our latest thoughts, blog posts and videos on Ember.js.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d50272c2e0c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/embermap/building-a-sticky-chatbox-3d50272c2e0c">Building a sticky chatbox</a> was originally published in <a href="https://medium.com/embermap">EmberMap</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lowest Common Ancestor]]></title>
            <link>https://medium.com/embermap/lowest-common-ancestor-fbf5d5313a1?source=rss-4bebdc004c4c------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbf5d5313a1</guid>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Sam Selikoff]]></dc:creator>
            <pubDate>Tue, 08 Dec 2015 18:54:43 GMT</pubDate>
            <atom:updated>2016-01-16T15:03:09.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vEfg-DhKH0A-YMZBjnIQ_w.png" /></figure><p>One of the biggest challenges when writing a JavaScript application is keeping multiple parts of the interface in sync. A user interaction in one part of the interface often affects data in another. If not managed well, this data can end up in multiple places, but with inconsistent values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iWOpHOULxmsJlsiO.gif" /><figcaption>Email 1 being unread is a piece of application state that affects multiple parts of the interface. After the email is read, the title should no longer be bold, and the Inbox unread count should decrease by one.</figcaption></figure><p>In the past few years, the JavaScript community has learned a lot about how to deal with this problem. The solution involves the principle of the <strong>Lowest Common Ancestor</strong>. To explain this principle, let’s look at some interface elements you might build while working on a real-world application.</p><p>These examples use Ember, but the principles are high-level and apply to any technology used for building long-lived JavaScript applications.</p><h3>A collapsible panel (a single view of app state)</h3><p>Let’s say we’re building an app with a collapsible panel:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/0*zG2-KZSkGIQJo7C4.gif" /><figcaption>A collapsible panel, an element that opens and closes when the user clicks on it.</figcaption></figure><p>Here’s the component’s template:</p><pre>&lt;a {{action &#39;toggleIsOpen&#39;}}&gt;Panel Title&lt;/a&gt;</pre><pre>{{#if isOpen}}<br>  &lt;div&gt;Anim pariatur cliche...&lt;/div&gt;<br>{{/if}}</pre><p>If the panel <em>isOpen</em>, we’ll show the body. Clicking the title triggers the <em>toggleIsOpen</em> action.</p><p>Here’s the component’s JavaScript:</p><pre>export default Ember.Component.extend({</pre><pre>  isOpen: true,</pre><pre>  actions: {<br>    toggleIsOpen() {<br>      this.toggleProperty(&#39;isOpen&#39;);<br>    }<br>  }</pre><pre>});</pre><p>The default value of <em>isOpen</em> is true, so the panel starts out open. Whenever a user clicks the title, <em>isOpen</em> toggles between true and false.</p><p>Currently, our application looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ROzRbyfqYv8zfc2-.png" /></figure><p><em>isOpen</em> is the only piece of state in our application that changes. Further, the collapsible panel is the only part of the interface that needs to know about it. Because of this, it makes sense for the panel itself to “own” this piece of application state. So, we’ll leave <em>isOpen</em> right where it is — as a simple property on the component.</p><h3>Adding a button (multiple views of app state)</h3><p>We have a new feature request: adding a separate button which can also toggle the panel. The button should also say “Expand” or “Collapse”, depending on the state of the panel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/0*UQ8MiTHYLB3Mw_WL.gif" /><figcaption>A collapsible panel and a button, which both depend on the same state.</figcaption></figure><p>We now have two elements in our application whose view depends on the same piece of state. What should we do?</p><p>One option is to add an <em>isOpen</em> property to our &lt;button&gt; component, and try to keep both properties in sync:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lPQB6k7JF6vyxps3.png" /></figure><p>But, duplicating state like this is not a good solution, because it can easily lead to an inconsistent interface.</p><p>A better solution is to move the state up a level to &lt;app&gt;, and have &lt;app&gt; pass down <em>isOpen</em> to both &lt;collapsible-panel&gt; and &lt;button&gt;:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CWMDAkQMt9JmkWew.png" /></figure><p>Think of the <em>isOpen</em> properties on the two children as read-only pointers to the <em>isOpen</em> property on &lt;app&gt;. Now, both &lt;collapsible-panel&gt; and &lt;button&gt; are guaranteed to stay in sync, since they’re rendered from the same state.</p><p>Here’s the template for &lt;app&gt;:</p><pre>{{collapsible-panel isOpen=isOpen onClick=(action &#39;toggleIsOpen&#39;)}}</pre><pre>{{button isOpen=isOpen onClick=(action &#39;toggleIsOpen&#39;)}}</pre><p>And here’s the JS, which looks exactly the same as &lt;collapsible-panel&gt; did in the first example:</p><pre>export default Ember.Component.extend({</pre><pre>  isOpen: true,</pre><pre>  actions: {<br>    toggleIsOpen() {<br>      this.toggleProperty(&#39;isOpen&#39;);<br>    }<br>  }</pre><pre>});</pre><p>When the user clicks either the &lt;collapsible-panel&gt; or the &lt;button&gt;, we’ll send an action up to &lt;app&gt;, which will then change its <em>isOpen</em> property. The new value of <em>isOpen</em> propagates throughout the rest of the app, and the problem of inconsistent interface elements goes away.</p><p>Crucially, we’ve made sure that only the owner of the state — &lt;app&gt;, in this case — is able to change that state. The children delegate their actions up to the owner.</p><p>By moving the state up to &lt;app&gt; and giving <em>isOpen</em> a single source of truth, we were able to ensure that &lt;collapsible-panel&gt; and &lt;button&gt; would never fall out of sync.</p><p>In the example above, &lt;app&gt; was the <em>only</em> ancestor of both components in our component tree. Say we had a larger app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_QbQBOIqNw16Q06G.png" /></figure><p>In this case, it would be sufficient to move <em>isOpen</em> to &lt;main&gt; to ensure <em>isOpen</em> had a single source of truth.</p><p>Now, a definition. Given a set of components, the <em>Lowest Common Ancestor</em> of this set is the component that’s deepest in the UI tree but still above each component in that set.</p><p>This definition along with the discussion above leads us to the following general principle:</p><blockquote>When dealing with changing application state that lives in your UI hierarchy, store that state in the <strong>Lowest Common Ancestor</strong> of all components that need it.</blockquote><p>Storing shared state on the LCA, and then having that common ancestor pass its state to the relevant children, ensures that the state will have a single source of truth, and that every component that renders from that state will stay in sync.</p><p>Note that it can sometimes be convenient to create a new common ancestor component, just for the sake of owning and managing the shared state.</p><h3>Adding a logout button (pulling app state out of the UI)</h3><p>In many situations, the principle of LCA is sufficient. State has a single source of truth, and is passed down to all children who need it. The problem you can run into, however, is when the LCA is very far away in your component hierarchy from the relevant children.</p><p>In this case, you can end up with many components acting as middlemen. These components must know about and pass along various pieces of shared state to leaf components, making your UI difficult to refactor. There’s even a <a href="https://sourcemaking.com/refactoring/smells/middle-man">code smell of the same name</a> in object-oriented design, suggesting that this is indeed a concern.</p><p>An example of how this could happen is if many components in your app needed to know about the current user:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*Eu_TM5olOlymLJNK.png" /><figcaption>In this app, data from the current user affects many components.</figcaption></figure><p>Assuming this many nodes need to know about the current user, the LCA would be &lt;app&gt;, and every component would need to pass along <em>currentUser</em> to every other component. This definitely smells like Middle Man.</p><p>The solution to this problem is to <em>pull the state out of the UI hierarchy</em>. The idea here is that, while <em>isOpen</em> in our earlier example corresponded directly to a particular onscreen UI element (whether the panel was open), <em>currentUser</em> does not. So, it doesn’t really make sense for &lt;app&gt; (or any other UI element) to “own” <em>currentUser</em>.</p><p>In Ember, we can use a Service to solve this problem (in React, you might use a Flux store). A Service is a long-lived data container that exists independent of the UI tree. After we set it up, components can use <em>dependency injection</em> to ask for the data in the Service. Importantly, their parent components are none the wiser.</p><pre>// app/services/current-user.js<br>export default Ember.Service.extend({<br>  name: &#39;Bob&#39;,<br>  email: &#39;bob@acme.com&#39;<br>});</pre><pre>// app/components/sidebar.js<br>export default Ember.Component.extend({<br>  currentUser: Ember.inject.service(&#39;current-user&#39;)<br>});</pre><p>Now, &lt;sidebar&gt; can access <em>currentUser</em> in its template:</p><pre>&lt;h2&gt;{{currentUser.name}}&lt;/h2&gt;</pre><p>&lt;sidebar&gt; has become more self-contained, making it easier to move around in the UI in later refactorings.</p><h3>Conclusion</h3><p>So, when should application state exist in the UI hierarchy, and when should it be pulled out? As in most areas of software design, there is no black and white answer. Instead, we must understand the tradeoffs involved, and make decisions on a case-by-case basis.</p><p>State that’s stored directly in the UI hierarchy is often easier to understand and requires less boilerplate; but, the more components that need a particular piece of state, the more brittle your UI hierarchy becomes. Eventually, it makes sense to move “popular state” into a UI-independent data container, an identity map which other components can read from.</p><p>The key insight is that <em>all changing application state should have a single owner</em>, and thus a single source of truth. Further, only the owner should be allowed to mutate that state. If the state lives in the UI hierarchy, the single owner should be the Lowest Common Ancestor of all components that need that state.</p><p>In closing,</p><ol><li>Start by storing state on local component instances</li><li>Once a piece of application state is needed by more than one component, move that state up to the LCA</li><li>Once there are many components acting as middlemen, or it feels wrong for any particular component to own some state, pull that state out of the UI hierarchy and into a data container (an Ember Service, a Flux store, etc.)</li></ol><p>While our example above might seem simple enough, this pattern goes a long way in keeping your application’s architecture consistent and easy to reason about.</p><p><em>Originally published at </em><a href="http://www.samselikoff.com/blog/lowest-common-ancestor/"><em>www.samselikoff.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbf5d5313a1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/embermap/lowest-common-ancestor-fbf5d5313a1">Lowest Common Ancestor</a> was originally published in <a href="https://medium.com/embermap">EmberMap</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>