<?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 Ewan McDougall on Medium]]></title>
        <description><![CDATA[Stories by Ewan McDougall on Medium]]></description>
        <link>https://medium.com/@mr.loop?source=rss-54bfaf694826------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Ve7wSnSUXxKfr9p_.png</url>
            <title>Stories by Ewan McDougall on Medium</title>
            <link>https://medium.com/@mr.loop?source=rss-54bfaf694826------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:49:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mr.loop/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[Scoped CSS in Ruby]]></title>
            <link>https://medium.com/@mr.loop/scoped-css-in-ruby-14cb75cf370d?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/14cb75cf370d</guid>
            <category><![CDATA[viewcomponents]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Sat, 07 Jun 2025 00:00:17 GMT</pubDate>
            <atom:updated>2025-06-17T05:55:52.182Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zTkV_KfJV1p393Se_bZM1g.png" /></figure><h3>The Component-Based CSS Challenge in Rails</h3><p>After years of working with JavaScript frameworks like Ember and React, I recently returned to Ruby on Rails for full-stack development. Modern JavaScript frameworks have spoiled us with elegant component-based CSS solutions, but what about Rails?</p><p>When I started building UI components with the <a href="https://github.com/viewcomponent/view_component">ViewComponent</a> library, I was faced a familiar challenge: <strong>how do I scope CSS to individual components without leaks or conflicts?</strong></p><p>While the official ViewComponent docs <a href="https://github.com/ViewComponent/view_component/blob/eba4c1424e58ceadc51d6f948c6ec8eb1b5a982e/docs/guide/javascript_and_css.md">previously offered some guidance</a> on CSS scoping, these approaches were complex and have since been removed. I also found Julik Tarkhanov’s interesting post on <a href="https://blog.julik.nl/2025/04/template-scoped-css-in-rails">Template Scoped CSS in Rails</a>, but it only scopes CSS to top-level templates — not granular enough for component-based development.</p><p>I needed something that would:</p><ol><li>Scope styles to individual ViewComponents</li><li>Prevent CSS class name collisions</li><li>Allow component reuse without duplicating styles</li><li>Maintain the simplicity and developer experience Rails is known for</li></ol><p>In this post, I’ll walk through the solution I developed and eventually extracted into a gem called <a href="https://github.com/mrloop/scoped_css">scoped_css</a>.</p><h3>What We’re Building: Component-Scoped CSS in Rails</h3><p>Ideally, we want to write component templates with encapsulated styles like this:</p><pre>&lt;style scoped-to-element-below&gt;<br>  .section {<br>    border: none;<br>    scroll-snap-align: center;<br>    color: purple;<br>  }<br>  .heading {<br>    font-size: 2rem;<br>  }<br>&lt;/style&gt;<br><br>&lt;section class=&quot;section&quot;&gt;<br>  &lt;h2 class=&quot;heading&quot;&gt;Section Title&lt;/h2&gt;<br>&lt;/section&gt;</pre><p>And when the component is rendered multiple times, we want the CSS to be included just once:</p><pre>&lt;style scoped-to-elements-below&gt;<br>  .section {<br>    border: none;<br>    scroll-snap-align: center;<br>    color: purple;<br>  }<br>  .heading {<br>    font-size: 2rem;<br>  }<br>&lt;/style&gt;<br><br>&lt;section class=&quot;section&quot;&gt;<br>  &lt;h2 class=&quot;heading&quot;&gt;Section Title&lt;/h2&gt;<br>&lt;/section&gt;<br><br>&lt;section class=&quot;section&quot;&gt;<br>  &lt;h2 class=&quot;heading&quot;&gt;Another Section&lt;/h2&gt;<br>&lt;/section&gt;</pre><p>But for this to work properly in Rails, we need a mechanism to transform this into uniquely prefixed CSS selectors.</p><h3>The scoped_css Helper: How It Works</h3><p>Here’s the helper function that makes component-scoped CSS possible:</p><pre>def scoped_css(&amp;css_block)<br>  @per_template_outputs ||= Hash.new<br><br>  # Capture the CSS content from the block<br>  css_block_content = &quot;&quot;<br>  if block_given?<br>    css_block_content = capture(&amp;css_block)<br>  end<br><br>  # Generate a unique prefix based on the CSS content<br>  prefix = &quot;a#{Digest::SHA1.hexdigest(css_block_content)}&quot;[0,8]<br><br>  styles = Hash.new<br>  prefixed_css_block_content = Rails.env.local? ? &#39; &lt;!-- previously output --&gt; &#39; : &#39;&#39;<br><br>  # Check if we&#39;ve already processed this CSS block<br>  if @per_template_outputs.has_key?(prefix)<br>    # Reuse the existing styles mapping but don&#39;t output the CSS again<br>    styles = @per_template_outputs[prefix]<br>  else<br>    # Process the CSS block, prefix all class selectors<br>    prefixed_css_block_content, styles = prefix_css_classes(css_block_content, prefix)<br>    # Cache the styles mapping for future renders of this component<br>    @per_template_outputs[prefix] = styles<br>  end<br><br>  result = prefixed_css_block_content.respond_to?(:html_safe) ? prefixed_css_block_content.html_safe : prefixed_css_block_content<br>  return [result, styles, prefix]<br>end</pre><p>Lets walk through what’s happening:</p><ol><li><strong>Content Capture</strong>: We grab the CSS content from the provided block.</li><li><strong>Prefix Generation</strong>: We create a unique prefix by hashing the CSS content with SHA1. Why SHA1? It gives us a consistent, unique identifier for identical CSS blocks, allowing us to detect duplicates.</li><li><strong>CSS Caching</strong>: The @per_template_outputs hash serves as our CSS cache. We check if we&#39;ve already processed this CSS block (based on its prefix) to avoid duplicating styles.</li><li><strong>Prefixing CSS Classes</strong>: For new CSS blocks, we transform each CSS class by adding our unique prefix (handled in the prefix_css_classes method, not shown here).</li><li><strong>Result</strong>: We return three things:</li></ol><ul><li>The prefixed CSS (or empty string if already rendered)</li><li>A mapping of original class names to prefixed ones</li><li>The unique prefix for this CSS block</li></ul><p>The result is CSS that looks like this:</p><pre>&lt;style&gt;<br>  .agkd94j4-section {<br>    border: none;<br>    scroll-snap-align: center;<br>    color: purple;<br>  }<br>  .agkd94j4-heading {<br>    font-size: 2rem;<br>  }<br>&lt;/style&gt;<br><br>&lt;section class=&quot;agkd94j4-section&quot;&gt;<br>  &lt;h2 class=&quot;agkd94j4-heading&quot;&gt;Section Title&lt;/h2&gt;<br>&lt;/section&gt;<br><br>&lt;section class=&quot;agkd94j4-section&quot;&gt;<br>  &lt;h2 class=&quot;agkd94j4-heading&quot;&gt;Another Section&lt;/h2&gt;<br>&lt;/section&gt;</pre><p>Our CSS is effectively scoped to the component while ensuring styles are only included once, no matter how many times we render the component.</p><h3>Putting It All Together: Complete Example</h3><p>Let’s see how this works in a real Rails application with ViewComponents:</p><p><strong>In your main template (app/views/home/index.html.erb):</strong></p><pre>&lt;% style_string, styles = scoped_css do %&gt;<br>&lt;style&gt;<br>  .heading {<br>    font-size: 3rem;<br>  }<br>&lt;/style&gt;<br>&lt;% end %&gt;<br><br>&lt;h1 class=&quot;&lt;%= styles[:heading] %&gt;&quot;&gt;Title&lt;/h1&gt;<br>&lt;%= render SectionComponent.new do %&gt;<br>  Section 1<br>&lt;% end %&gt;<br><br>&lt;%= render SectionComponent.new do %&gt;<br>  Section 2<br>&lt;% end %&gt;<br><br>&lt;%= style_string %&gt;</pre><p><strong>In your component class (app/components/section_component.rb):</strong></p><pre>class SectionComponent &lt; ViewComponent::Base<br>end</pre><p><strong>In your component template (app/components/section_component.html.erb):</strong></p><pre>&lt;% style_string, styles = helpers.scoped_css do %&gt;<br>&lt;style&gt;<br>  .section {<br>    border: none;<br>    scroll-snap-align: center;<br>    color: purple;<br>  }<br>  .heading {<br>    font-size: 2rem;<br>  }<br>&lt;/style&gt;<br>&lt;% end %&gt;<br><br>&lt;section class=&quot;&lt;%= styles[:section] %&gt;&quot;&gt;<br>  &lt;h2 class=&quot;&lt;%= styles[:heading] %&gt;&quot;&gt;Section&lt;/h2&gt;<br>  &lt;%= content %&gt;<br>&lt;/section&gt;<br><br>&lt;%= style_string %&gt;</pre><p>This generates HTML with properly scoped CSS:</p><pre>&lt;!-- app/views/home/index.html.erb --&gt;<br><br>&lt;h1 class=&quot;atge5q2e-heading&quot;&gt;Title&lt;/h1&gt;<br><br>&lt;!-- app/components/section_component.html.erb --&gt;<br><br>&lt;section class=&quot;agkd94j4-section&quot;&gt;<br>  &lt;h2 class=&quot;agkd94j4-heading&quot;&gt;Section&lt;/h2&gt;<br>  Section 1<br>&lt;/section&gt;<br><br>&lt;section class=&quot;agkd94j4-section&quot;&gt;<br>  &lt;h2 class=&quot;agkd94j4-heading&quot;&gt;Section&lt;/h2&gt;<br>  Section 2<br>&lt;/section&gt;<br><br>&lt;style&gt;<br>  .agkd94j4-section {<br>    border: none;<br>    scroll-snap-align: center;<br>    color: purple;<br>  }<br>  .agkd94j4-heading {<br>    font-size: 2rem;<br>  }<br>&lt;/style&gt;<br><br>&lt;!-- app/views/home/index.html.erb --&gt;<br><br>&lt;style&gt;<br>  .atge5q2e-heading {<br>    font-size: 3rem;<br>  }<br>&lt;/style&gt;</pre><h3>Advanced Usage: Attribute Splatting</h3><p>Sometimes you need to apply HTML attributes to a component from the parent template. Let’s enhance our solution to handle this common pattern:</p><p><strong>In your main template (app/views/home/index.html.erb):</strong></p><pre>&lt;% style_string, styles = scoped_css do %&gt;<br>&lt;style&gt;<br>  .section {<br>    margin: 10px;<br>  }<br>  .heading {<br>    font-size: 3rem;<br>  }<br>&lt;/style&gt;<br>&lt;% end %&gt;<br><br>&lt;h1 class=&quot;&lt;%= styles[:heading] %&gt;&quot;&gt;Title&lt;/h1&gt;<br>&lt;%= render SectionComponent.new(attributes: { id: &quot;important-section&quot;, class: styles[:section] }) do %&gt;<br>  &lt;p&gt;Section 1&lt;/p&gt;<br>&lt;% end %&gt;<br><br>&lt;%= style_string %&gt;</pre><p><strong>In your component class (app/components/section_component.rb):</strong></p><pre>class SectionComponent &lt; ViewComponent::Base<br>  def initialize(attributes: {})<br>    @attributes = attributes<br>  end<br>end</pre><p><strong>In your component template (app/components/section_component.html.erb):</strong></p><pre>&lt;% style_string, styles = helpers.scoped_css do %&gt;<br>&lt;style&gt;<br>  .section {<br>    border: none;<br>    scroll-snap-align: center;<br>    color: purple;<br>  }<br>  .heading {<br>    font-size: 2rem;<br>  }<br>&lt;/style&gt;<br>&lt;% end %&gt;<br><br>&lt;section &lt;%= helpers.splat_attributes(@attributes, styles[:section]) %&gt;&gt;<br>  &lt;h2 class=&quot;&lt;%= styles[:heading] %&gt;&quot;&gt;Section&lt;/h2&gt;<br>  &lt;%= content %&gt;<br>&lt;/section&gt;<br><br>&lt;%= style_string %&gt;</pre><p>The splat_attributes helper combines the component&#39;s internal class with any external classes passed from the parent:</p><pre>&lt;section class=&quot;agkd94j4-section atge5q2e-section&quot; id=&quot;important-section&quot;&gt;<br>  &lt;h2 class=&quot;agkd94j4-heading&quot;&gt;Section&lt;/h2&gt;<br>  &lt;p&gt;Section 1&lt;/p&gt;<br>&lt;/section&gt;</pre><blockquote><strong><em>Note:</em></strong><em> Rather than using something like </em><em>&lt;section class=&quot;&lt;%= styles[:heading] %&gt;&quot; &lt;%= helpers.splat_attributes(@attributes, styles[:section]) %&gt;&gt;, we use the </em><em>splat_attributes helper to handle both the component&#39;s internal classes and any additional attributes passed from the parent.</em></blockquote><h3>CSS Specificity and Customization</h3><p>What if you want to customize the appearance of a specific component instance? The CSS cascade works in our favor here:</p><p><strong>In your main template (app/views/home/index.html.erb):</strong></p><pre>&lt;% style_string, styles = scoped_css do %&gt;<br>&lt;style&gt;<br>  .section {<br>    margin: 10px;<br>    color: darkgreen;  /* This will override the component&#39;s purple color */<br>  }<br>  .heading {<br>    font-size: 3rem;<br>  }<br>&lt;/style&gt;<br>&lt;% end %&gt;<br><br>&lt;h1 class=&quot;&lt;%= styles[:heading] %&gt;&quot;&gt;Title&lt;/h1&gt;<br>&lt;%= render SectionComponent.new(attributes: { class: styles[:section] }) do %&gt;<br>  &lt;p&gt;Section 1 (Dark Green)&lt;/p&gt;<br>&lt;% end %&gt;<br><br>&lt;%= render SectionComponent.new() do %&gt;<br>  &lt;p&gt;Section 2 (Purple)&lt;/p&gt;<br>&lt;% end %&gt;<br><br>&lt;%= style_string %&gt;</pre><p>Since we render style tags at the bottom of each template, CSS specificity works as expected:</p><ol><li>The component’s internal styles are rendered first</li><li>The parent template styles are rendered later</li><li>The last declared selector with the same specificity takes precedence</li></ol><p>For the first section with the parent’s class applied, the color will be dark green (overriding the component’s purple). The second section, without the parent’s class, will remain purple.</p><p>This scoped CSS solution offers several key benefits:</p><ol><li><strong>True Encapsulation</strong>: Component styles don’t leak or conflict, even with identical class names</li><li><strong>Performance</strong>: CSS is only included once per unique component, not per instance</li><li><strong>Maintainability</strong>: Components remain self-contained with their styles</li><li><strong>Customization</strong>: The CSS cascade still works as expected for intentional overrides</li><li><strong>Simplicity</strong>: No additional build steps or preprocessors required</li></ol><h3>Conclusion: Component-Based CSS in Rails</h3><p>By implementing this scoped CSS solution, we’ve bridged the gap between modern component-based frontend frameworks and Rails ViewComponents. We get the best of both worlds: Rails’ simplicity and productivity with the style encapsulation we’ve come to expect from JavaScript frameworks.</p><p>For a drop-in solution, check out the <a href="https://github.com/mrloop/scoped_css">scoped_css gem</a> I’ve extracted from this approach. It includes the helpers demonstrated.</p><p><em>Originally published at </em><a href="https://blog.mrloop.com/ruby/rails/css/viewcomponent/2025/06/07/scoped-css-in-ruby"><em>https://blog.mrloop.com</em></a><em> on June 7, 2025.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14cb75cf370d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring LLMs: A Blind Trial for Code Completions]]></title>
            <link>https://medium.com/@mr.loop/exploring-llms-a-blind-trial-for-code-completions-26da54a36d32?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/26da54a36d32</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[autocomplete]]></category>
            <category><![CDATA[neovim]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 18:42:44 GMT</pubDate>
            <atom:updated>2025-03-09T18:42:44.888Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong><em>Abstract:</em></strong><em> This article presents findings from a four-month blind trial of LLM code completions in a professional development environment. By tracking over 94,000 code suggestions across three leading AI assistants, I found that GitHub Copilot delivers the highest quality suggestions (3.4% acceptance rate) while Supermaven provides the greatest volume of useful completions. Codeium performed significantly worse (0.5% acceptance rate) and was discontinued after seven days. This data-driven approach reveals meaningful differences in LLM performance for practical coding assistance.</em></blockquote><p>Large language models (LLMs) have transformed the coding experience with capabilities ranging from auto-completion to chat interfaces and agentic file editing. In this post, I’ll share results from a systematic evaluation of three popular AI code completion tools in a professional development environment.</p><p>Rather than relying on subjective impressions, I conducted a rigorous blind trial to determine which model genuinely performs best in day-to-day coding work. This methodology eliminates the confirmation bias that often affects tool selection (“I think this one feels better”) and provides concrete data about which assistant actually delivers the most value.</p><p>To conduct a randomized blind trial of large language model code completions, I established four key requirements:</p><ol><li>Configure multiple LLMs for code completions in my development environment</li><li>Display completion suggestions without revealing which LLM generated them</li><li>Randomize the presentation order to eliminate selection bias</li><li>Collect comprehensive usage data over an extended period</li></ol><h3>LLMs Under Evaluation</h3><p>I selected three popular AI code assistants for this experiment:</p><ul><li><strong>GitHub Copilot</strong>: Microsoft and GitHub’s AI pair programmer, built on OpenAI technology, trained on public code repositories and avialbe as a paid subscription service ($10/month or $100/year).</li><li><strong>Codeium</strong>: A free AI coding assistant from Exafunction that promises high-quality completions with low latency.</li><li><strong>Supermaven</strong>: AI code completion tool that claims to offer deeper contextual understanding and multi-line completions. Available as both free and paid tiers. The free tier was used for this trial.</li></ul><p>By comparing these different systems, I aimed to determine which would be most effective for my daily development workflow.</p><h3>Implementation</h3><p>In this section, I’ll explain the technical approach used to create a fair testing environment for these AI auto completions. If you’re primarily interested in the findings rather than the methodology, feel free to skip directly to the <a href="https://blog.mrloop.com/neovim/llm/ai/2025/02/28/code-completions.html#results">results</a> section.</p><p>I use Neovim daily; it is highly customizable and can be configured to meet my needs. The configuration samples shown use <a href="https://github.com/folke/lazy.nvim">Lazy.nvim</a>.</p><h3>LLM Configurations</h3><p>Codeium, GitHub Copilot, and Supermaven are used for code completions.</p><pre>{<br>  &quot;Exafunction/codeium.nvim&quot;,<br>  enabled = os.getenv(&quot;CODEIUM&quot;) == &quot;true&quot;,<br>  dependencies = {<br>    &quot;nvim-lua/plenary.nvim&quot;,<br>    &quot;hrsh7th/nvim-cmp&quot;,<br>  },<br>  config = true,<br>},<br>{<br>  &quot;zbirenbaum/copilot.lua&quot;,<br>  enabled = os.getenv(&quot;COPILOT&quot;) == &quot;true&quot;,<br>  cmd = &quot;Copilot&quot;,<br>  event = &quot;InsertEnter&quot;,<br>  opts = {<br>    suggestion = { enabled = false },<br>    panel = { enabled = false },<br>  }<br>},<br>{<br>  &quot;zbirenbaum/copilot-cmp&quot;,<br>  enabled = os.getenv(&quot;COPILOT&quot;) == &quot;true&quot;,<br>  dependencies = { &quot;copilot.lua&quot;, &quot;lspkind.nvim&quot; },<br>  config = true,<br>  init = function()<br>    vim.api.nvim_set_hl(0, &quot;CmpItemKindCopilot&quot;, { fg = &quot;#6CC644&quot; })<br>  end,<br>},<br>{<br>  &quot;supermaven-inc/supermaven-nvim&quot;,<br>  enabled = os.getenv(&quot;SUPERMAVEN&quot;) == &quot;true&quot;,<br>  opts = {<br>    disable_inline_completion = true,<br>  },<br>  init = function ()<br>    vim.api.nvim_set_hl(0, &quot;CmpItemKindSupermaven&quot;, { fg = &quot;#6CC644&quot; })<br>  end,<br>}</pre><h3>UI Configuration</h3><p>For each LLM source, only a symbol is shown in the UI, and the same symbol is used for all LLM completions.</p><pre>cmp.setup({<br>  -- only showing formatting option for brevity<br>  formatting = {<br>    fields = {&#39;menu&#39;, &#39;abbr&#39;, &#39;kind&#39;},<br>    format = require(&#39;lspkind&#39;).cmp_format({<br>      mode = &quot;symbol&quot;,<br>      maxwidth = 50,<br>      show_labelDetails = true,<br>      ellipsis_char = &#39;...&#39;,<br>      symbol_map = {<br>        Supermaven = &quot;&quot;,<br>        Codeium = &quot;&quot;,<br>        Copilot = &quot;&quot;,<br>      },<br>    })<br>  },<br>})</pre><h3>Randomize the Order of Completion Suggestions</h3><p>To eliminate position bias (the tendency to select the first suggestion), I implemented a system to randomize the order in which completion suggestions appear. Rather than defining a fixed order of completion sources in the setup function, I dynamically shuffle them each time a new buffer is loaded:</p><pre>cmp.setup({<br>  -- only showing sources option for brevity<br>-  sources = cmp.config.sources({<br>-    { name = &#39;nvim_lsp&#39; },<br>-    { name = &#39;luasnip&#39; },<br>-    { name = &#39;path&#39; },<br>-  }, {<br>-    { name = &#39;nvim-cmp-ts-tag-close&#39; },<br>-    { name = &quot;codeium&quot; },<br>-    { name = &#39;copilot&#39;},<br>-    { name = &#39;supermaven&#39;},<br>-    { name = &#39;nvim_lua&#39; },<br>-    { name = &#39;spell&#39; },<br>-  }, {<br>-    { name = &#39;buffer&#39; },<br>-  }),<br>-<br> })</pre><p>This approach ensures that no AI completion source consistently appears first in the suggestion list, which is crucial for unbiased evaluation:</p><pre>-- Fisher-Yates shuffle algorithm to randomize suggestion order<br>-- This is critical for reducing selection bias - if suggestions always appeared<br>-- in the same order, I might unconsciously favor the first option<br>local function shuffle(t)<br>  local n = #t<br>  for i = n, 2, -1 do<br>    local j = math.random(1, i)<br>    t[i], t[j] = t[j], t[i]<br>  end<br>  return t;<br>end<br><br>vim.api.nvim_create_autocmd(&#39;BufReadPre&#39;, {<br>  callback = function(t)<br>    local sources = cmp.config.sources({<br>      { name = &#39;nvim_lsp&#39; },<br>      { name = &#39;luasnip&#39; },<br>      { name = &#39;path&#39; },<br>    }, shuffle({<br>      { name = &#39;nvim-cmp-ts-tag-close&#39; },<br>      { name = &quot;codeium&quot; },<br>      { name = &#39;copilot&#39;},<br>      { name = &#39;supermaven&#39;},<br>      { name = &#39;nvim_lua&#39; },<br>      { name = &#39;spell&#39; },<br>    }), {<br>      { name = &#39;buffer&#39; },<br>    });<br>    cmp.setup.buffer { sources = sources }<br>  end<br>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*FYXrOnReOb8QhZGA.png" /></figure><p>Fig 1: Example of the auto completion UI showing showing suggestions for this.objectUrl</p><h3>Data Collection System</h3><p>To objectively measure each LLM’s performance, I built a comprehensive data collection system using SQLite. This system silently recorded every completion suggestion and user acceptance decision during my normal development activities:</p><pre>-- Setup lsqlite3<br>-- Run `luarocks install lsqlite3` if needed<br>local status, sqlite3 = pcall(require, &#39;lsqlite3&#39;)<br><br>if status then<br>  local db_path = vim.fn.stdpath(&#39;data&#39;) .. &#39;/completion-log.sqlite3&#39;<br>  local db = sqlite3.open(db_path)<br><br>  -- Create a log table if it doesn&#39;t exist<br>  db:exec[[<br>    CREATE TABLE IF NOT EXISTS cmp_log (<br>      id INTEGER PRIMARY KEY,<br>      timestamp TEXT,<br>      event TEXT,<br>      multiline INTEGER,<br>      source_name TEXT,<br>      filetype TEXT<br>    )<br>  ]]<br><br>  print(&quot;Logging completions to &quot; .. db_path)<br><br>  -- Prepare the insert statement<br>  local stmt = db:prepare(&quot;INSERT INTO cmp_log (timestamp, event, multiline, source_name, filetype) VALUES (?, ?, ?, ?, ?)&quot;)<br>  -- Close the database connection when Neovim exits<br>  vim.api.nvim_create_autocmd(&quot;VimLeavePre&quot;, {<br>    callback = function()<br>      stmt:finalize()<br>      db:close()<br>    end,<br>  })<br><br>  -- Table of source names to log<br>  local log_sources = {<br>    supermaven = true,<br>    codeium = true,<br>    copilot = true,<br>    cmp_ai = true<br>  }<br><br>  -- Function to log completion events<br>  local function log_completion(event, item, source_name, filetype)<br>    local multiline = item.textEdit and item.textEdit.newText and item.textEdit.newText:find(&quot;\n&quot;) and 1 or 0<br>    if log_sources[source_name] then<br>      stmt:reset()<br>      stmt:bind_values(os.date(&#39;%Y-%m-%d %H:%M:%S&#39;), event, multiline, source_name, filetype)<br>      stmt:step()<br>    end<br>  end<br><br><br>  -- Register event listeners<br>  cmp.event:on(&#39;menu_opened&#39;, function(evt)<br>    for _, entry in ipairs(evt.window.entries) do<br>      local source_name = entry.source.name<br>      log_completion(&quot;completion_suggested&quot;, entry:get_completion_item(), source_name, entry.context.filetype)<br>    end<br>  end)<br><br>  cmp.event:on(&#39;confirm_done&#39;, function(evt)<br>    log_completion(&quot;completion_used&quot;, evt.entry:get_completion_item(), evt.entry.source.name, evt.entry.context.filetype)<br>  end)<br>else<br>  print(sqlite3)<br>end</pre><p><a href="https://www.sqlite.org/whentouse.html">SQLite is used</a> because it’s lightweight, requires no server setup, and provides a self-contained database solution ideal for this type of data collection. Additionally, <a href="https://datasette.io/">Datasette</a> can be used to easily query, visualize, and publish the data for later analysis.</p><p>The database schema tracked five key data points for each completion event:</p><pre>CREATE TABLE IF NOT EXISTS cmp_log (<br>  id INTEGER PRIMARY KEY,<br>  timestamp TEXT,<br>  event TEXT,<br>  multiline INTEGER,<br>  source_name TEXT,<br>  filetype TEXT<br>)</pre><p>The timestamp is the date and time the event was logged and is useful to see if the effectiveness of the LLMs changes over time. The event is the name of the nvim-cmp event that was fired. The multiline is a boolean value that is true if the completion is multiline. The source_name is the name of the source that provided the completion, for example, Copilot. The filetype is the filetype of the buffer that the completion was provided in.</p><p>The system tracked two primary event types:</p><ol><li><strong>completion_suggested</strong>: Recorded whenever a completion was offered</li><li><strong>completion_used</strong>: Recorded when I accepted a completion</li></ol><p>This approach allowed me to calculate the critical acceptance rate metric (accepted completions ÷ suggested completions) that forms the foundation of this analysis.</p><h3>Results</h3><p>After collecting data for approximately four months across real-world development projects, clear patterns emerged in how these AI assistants performed in day-to-day coding scenarios.</p><p>The most immediate finding was Codeium’s poor performance. It achieved only a 0.5% acceptance rate (meaning I accepted only 1 out of every 200 suggestions). This led me to discontinue it after seven days of evaluation.</p><h3>Quantitative Results</h3><p><strong>Summary Statistics</strong></p><pre>┌────────────┬────────────────────┬────────────────────────┬──────────────────┬────────────────────────┬────────────────────────┐<br>│ LLM        │ Total Suggestions  │ Accepted Completions   │ Acceptance Rate  │ Avg Daily Suggestions  │ Avg Daily Acceptances  │<br>├────────────┼────────────────────┼────────────────────────┼──────────────────┼────────────────────────┼────────────────────────┤<br>│ Supermaven │ 60,508             │ 1,171                  │ 1.9%             │ 293.3                  │ 5.7                    │<br>│ Copilot    │ 27,395             │ 921                    │ 3.4%             │ 133.5                  │ 4.5                    │<br>│ Codeium    │ 7, 091             │ 32                     │ 0.5%             │ 745.4                  │ 3.4                    │<br>└────────────┴────────────────────┴────────────────────────┴──────────────────┴────────────────────────┴────────────────────────┘</pre><p><a href="https://completion-log-281060383488.europe-west1.run.app/completion-log?sql=WITH+daily_stats+AS+%28%0D%0A++SELECT+%0D%0A++++source_name+AS+LLM%2C%0D%0A++++COUNT%28*%29+AS+total_suggestions%2C%0D%0A++++SUM%28CASE+WHEN+event+%3D+%27completion_used%27+THEN+1+ELSE+0+END%29+AS+accepted_completions%2C%0D%0A++++%28JULIANDAY%28MAX%28timestamp%29%29+-+JULIANDAY%28MIN%28timestamp%29%29+%2B+1%29+AS+total_days%0D%0A++FROM+cmp_log%0D%0A++WHERE+event+IN+%28%27completion_suggested%27%2C+%27completion_used%27%29%0D%0A++GROUP+BY+source_name%0D%0A%29%0D%0ASELECT+%0D%0A++LLM%2C%0D%0A++total_suggestions+AS+%22Total+Suggestions%22%2C%0D%0A++accepted_completions+AS+%22Accepted+Completions%22%2C%0D%0A++ROUND%28%28accepted_completions+*+100.0%29+%2F+total_suggestions%2C+1%29+%7C%7C+%27%25%27+AS+%22Acceptance+Rate%22%2C%0D%0A++ROUND%28total_suggestions+%2F+total_days%2C+1%29+AS+%22Avg+Daily+Suggestions%22%2C%0D%0A++ROUND%28accepted_completions+%2F+total_days%2C+1%29+AS+%22Avg+Daily+Acceptances%22%2C%0D%0A++total_days%0D%0AFROM+daily_stats%0D%0AORDER+BY+total_suggestions+DESC%3B%0D%0A">Summery Statistics Data here</a></p><p>These statistics reveal two distinct AI assistant strategies:</p><ul><li><strong>Copilot</strong>: Offers fewer but higher quality suggestions (3.4% acceptance)</li><li><strong>Supermaven</strong>: Provides more aggressive suggestions with lower precision (1.9% acceptance)</li></ul><p><strong>Daily Used Count</strong></p><figure><img alt="daily used count chart" src="https://cdn-images-1.medium.com/max/1024/1*tOgqhYEvHqbA_JtwUTYoyw.png" /></figure><p><em>Fig 1: Daily count of accepted completions by LLM. Note Supermaven’s consistently higher daily usage (average: 5.7 completions) compared to Copilot (average: 4.5 completions).</em></p><p><strong>Daily Suggested Count</strong></p><figure><img alt="daily suggested count chart" src="https://cdn-images-1.medium.com/max/1024/1*Q97VC0PTEelisSM3IGRcHQ.png" /></figure><p><em>Fig 2: Daily count of suggested completions by LLM. Supermaven offers significantly more suggestions (an average of 293 per day) than Copilot (134 per day).</em></p><p><strong>Daily Acceptance Ratio</strong></p><figure><img alt="daily used over suggested ratio chart" src="https://cdn-images-1.medium.com/max/1024/1*lNQN6kz-V1iLoO_C2vgYhw.png" /></figure><p><em>Fig 3: Daily acceptance ratio (accepted/suggested) by LLM. Copilot consistently maintains higher suggested to accepted completion ratios (3.4%), while Supermaven typically ranges between 0.1.5–0.2% of suggestions accepted.</em></p><p><a href="https://completion-log-281060383488.europe-west1.run.app/completion-log?sql=WITH+daily_counts+AS+%28%0D%0A++++SELECT+%0D%0A++++++++DATE%28timestamp%29+AS+day%2C+%0D%0A++++++++source_name%2C+%0D%0A++++++++COUNT%28CASE+WHEN+event+%3D+%27completion_used%27+THEN+1+END%29+AS+daily_used_count%2C%0D%0A++++++++COUNT%28CASE+WHEN+event+%3D+%27completion_suggested%27+THEN+1+END%29+AS+daily_suggested_count%0D%0A++++FROM+cmp_log%0D%0A++++WHERE+source_name+%21%3D+%27cmp_ai%27%0D%0A++++GROUP+BY+day%2C+source_name%0D%0A%29%0D%0ASELECT+%0D%0A++++day%2C%0D%0A++++source_name%2C%0D%0A++++daily_used_count%2C%0D%0A++++daily_suggested_count%2C%0D%0A++++ROUND%28%0D%0A++++++++CAST%28daily_used_count+AS+FLOAT%29+%2F+NULLIF%28daily_suggested_count%2C+0%29%2C+%0D%0A++++++++5%0D%0A++++%29+AS+daily_used_suggested_ratio%2C%0D%0A++++SUM%28daily_used_count%29+OVER+%28%0D%0A++++++++PARTITION+BY+source_name+%0D%0A++++++++ORDER+BY+day+%0D%0A++++++++ROWS+BETWEEN+UNBOUNDED+PRECEDING+AND+CURRENT+ROW%0D%0A++++%29+AS+cumulative_used_count%2C%0D%0A++++SUM%28daily_suggested_count%29+OVER+%28%0D%0A++++++++PARTITION+BY+source_name+%0D%0A++++++++ORDER+BY+day+%0D%0A++++++++ROWS+BETWEEN+UNBOUNDED+PRECEDING+AND+CURRENT+ROW%0D%0A++++%29+AS+cumulative_suggested_count%2C%0D%0A++++ROUND%28%0D%0A++++++++CAST%28%0D%0A++++++++++++SUM%28daily_used_count%29+OVER+%28%0D%0A++++++++++++++++PARTITION+BY+source_name+%0D%0A++++++++++++++++ORDER+BY+day+%0D%0A++++++++++++++++ROWS+BETWEEN+UNBOUNDED+PRECEDING+AND+CURRENT+ROW%0D%0A++++++++++++%29+AS+FLOAT%0D%0A++++++++%29+%2F+NULLIF%28%0D%0A++++++++++++SUM%28daily_suggested_count%29+OVER+%28%0D%0A++++++++++++++++PARTITION+BY+source_name+%0D%0A++++++++++++++++ORDER+BY+day+%0D%0A++++++++++++++++ROWS+BETWEEN+UNBOUNDED+PRECEDING+AND+CURRENT+ROW%0D%0A++++++++++++%29%2C+0%0D%0A++++++++%29%2C+%0D%0A++++++++5%0D%0A++++%29+AS+cumulative_used_suggested_ratio%0D%0AFROM+daily_counts%0D%0AORDER+BY+day%2C+source_name%3B%0D%0A#g.mark=bar&amp;g.x_column=day&amp;g.x_type=ordinal&amp;g.y_column=daily_suggested_count&amp;g.y_type=quantitative&amp;g.color_column=source_name">View raw data here</a></p><h3>Performance by Language</h3><p>Analysis of completions by file type revealed interesting patterns:</p><pre>┌───────────────────────┬───────────────────┬──────────────────┐<br>│ Language              │ Most Accurate LLM │ Acceptance Rate  │<br>├───────────────────────┼───────────────────┼──────────────────┤<br>│ http                  │ copilot           │ 8.3%             │<br>│ zsh                   │ copilot           │ 5.9%             │<br>│ typescriptreact       │ copilot           │ 5.8%             │<br>│ css                   │ copilot           │ 5.6%             │<br>│ handlebars            │ copilot           │ 5.0%             │<br>│ jsonc                 │ copilot           │ 5.0%             │<br>│ lua                   │ copilot           │ 4.4%             │<br>│ make                  │ copilot           │ 3.9%             │<br>│ javascript.glimmer    │ copilot           │ 3.6%             │<br>│ JavaScript/TypeScript │ copilot           │ 2.8%             │<br>│ conf                  │ copilot           │ 2.4%             │<br>│ yaml                  │ supermaven        │ 1.4%             │<br>│ git*                  │ supermaven        │ 1.0%             │<br>│ markdown              │ supermaven        │ 0.9%             │<br>└───────────────────────┴───────────────────┴──────────────────┘</pre><p><a href="https://completion-log-281060383488.europe-west1.run.app/completion-log?sql=WITH+llm_stats+AS+%28%0D%0A++SELECT+%0D%0A++++CASE+%0D%0A++++++WHEN+filetype+IN+%28%27javascript%27%2C+%27typescript%27%2C+%27javascriptreact%27%29+THEN+%27JavaScript%2FTypeScript%27%0D%0A++++++WHEN+filetype+LIKE+%27git%25%27+THEN+%27Git%27%0D%0A++++++ELSE+filetype%0D%0A++++END+AS+Language%2C%0D%0A++++source_name+AS+LLM%2C%0D%0A++++COUNT%28*%29+AS+total_suggestions%2C%0D%0A++++SUM%28CASE+WHEN+event+%3D+%27completion_used%27+THEN+1+ELSE+0+END%29+AS+accepted_completions%0D%0A++FROM+cmp_log%0D%0A++WHERE+event+IN+%28%27completion_suggested%27%2C+%27completion_used%27%29%0D%0A++AND+source_name+%21%3D+%27cmp_ai%27++--+Exclude+cmp_ai%0D%0A++GROUP+BY+Language%2C+source_name%0D%0A%29%2C%0D%0Aranked_llms+AS+%28%0D%0A++SELECT+%0D%0A++++Language%2C%0D%0A++++LLM+AS+%22Most+Accurate+LLM%22%2C%0D%0A++++ROUND%28%28accepted_completions+*+100.0%29+%2F+total_suggestions%2C+1%29+AS+acceptance_rate%2C%0D%0A++++RANK%28%29+OVER+%28PARTITION+BY+Language+ORDER+BY+%28accepted_completions+*+100.0%29+%2F+total_suggestions+DESC%29+AS+rnk%0D%0A++FROM+llm_stats%0D%0A%29%0D%0ASELECT+Language%2C+%22Most+Accurate+LLM%22%2C+acceptance_rate+%7C%7C+%27%25%27+AS+%22Acceptance+Rate%22%0D%0AFROM+ranked_llms%0D%0AWHERE+rnk+%3D+1+AND+acceptance_rate+%3E+0++--+Ignore+0.0%25+acceptance+rates%0D%0AORDER+BY+acceptance_rate+DESC%3B%0D%0A">Data here</a></p><h3>Conclusion</h3><p>Out of Codeium, Copilot, and Supermaven, Codeium is the clear loser the lowest acceptance rate (0.5%).</p><p>Supermaven provided the highest volume of useful completions (1,171 accepted suggestions) but at the cost of efficiency — it generated 60508 total suggestions, meaning 98.1% of its completions were rejected.</p><p>Copilot demonstrated the best balance of quality and quantity — with 921 accepted completions from just 27395 suggestions, achieving a 3.4% acceptance rate. More than twice the acceptance rate of Supermaven.</p><h3>Limitations and Future Work</h3><p>While this study provides valuable insights, several limitations should be acknowledged:</p><ol><li><strong>Single-user perspective</strong> — Results primarily reflect my personal coding style, projects, and preferences</li><li><strong>Project-specific patterns</strong> — Performance likely varies across different codebases and domains</li><li><strong>Temporal factors</strong> — AI models are continuously improving; results may not reflect current capabilities</li><li><strong>Commercial focus</strong> — Only commercial LLMs were tested; promising open-source models weren’t evaluated</li><li><strong>Data collection gaps</strong> — There were two notable gaps in data collection:</li></ol><ul><li>Eight days in July with no Copilot data (likely due to authentication expiration)</li><li>A period between October and December when I transitioned to a new development machine</li></ul><p>Based on these findings and limitations, I’ve identified several opportunities for future work:</p><ol><li><strong>Expanded model comparison</strong>: Integrate additional code completion tools, particularly open-source models via plugins like <a href="https://github.com/tzachar/cmp-ai">cmp-ai</a> or <a href="https://github.com/milanglacier/minuet-ai.nvim">minuet-ai.nvim</a>.</li><li><strong>Methodological refinements</strong>: Switch from the menu_opened event to menu_closed for asynchronous completions to ensure all displayed suggestions are properly captured. This would provide a more accurate picture of what completions were actually seen and evaluated.</li><li><strong>Multi-user study</strong>: Expand data collection to include other developers to better understand how these tools perform across different coding styles and domains.</li></ol><h3>Summary</h3><p>This blind trial of LLM code completions revealed significant differences between the three tested models:</p><ul><li><strong>Codeium</strong>: Discontinued after 7 days due to poor performance (0.5% acceptance rate)</li><li><strong>GitHub Copilot</strong>: Highest quality suggestions (3.4% acceptance rate)</li><li><strong>Supermaven</strong>: Highest volume of accepted suggestions but lower efficiency (1.9% acceptance rate)</li></ul><p>The findings demonstrate that different LLMs have distinct strengths — Copilot excels at providing precise, focused suggestions that are more likely to be accepted, while Supermaven offers more aggressive suggestions covering a wider range of possibilities.</p><p>The quantitative approach revealed patterns that wouldn’t be obvious from casual usage, such as the significant difference in acceptance rates between the tools (Copilot’s 3.4% vs. Supermaven’s 1.9%).</p><p>Based on these results, I’ve adopted a hybrid approach in my development workflow:</p><ol><li>Continue using Copilot for auto complete.</li><li>Trial paid for Supermaven to see if this improves the acceptance rate.</li><li>Test new models to ensure I’m using the most effective tools</li></ol><p>This experiment demonstrates the value of data-driven decision making when selecting developer tools, and I look forward to expanding this methodology to evaluate additional LLM-based coding assistants in the future.</p><p><em>Originally published at </em><a href="https://blog.mrloop.com/neovim/llm/ai/2025/02/28/code-completions.html"><em>https://blog.mrloop.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26da54a36d32" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[useSuspenseQuery]]></title>
            <link>https://medium.com/@mr.loop/usesuspensequery-61773f767df9?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/61773f767df9</guid>
            <category><![CDATA[tanstack-query]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Sun, 16 Jun 2024 13:53:11 GMT</pubDate>
            <atom:updated>2024-06-16T13:54:54.488Z</atom:updated>
            <content:encoded><![CDATA[<p>I was interested in how nested React <a href="https://react.dev/reference/react/Suspense">&lt;Suspense/&gt;</a> and <a href="https://tanstack.com/query/">TanStack </a><a href="https://tanstack.com/query/">useSuspenseQuery</a> worked together. The small app below is a visualization of various combinations of <a href="https://react.dev/reference/react/Suspense">&lt;Suspense/&gt;</a> and <a href="https://tanstack.com/query/">TanStack Query</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmrloop-use-suspense-query%3Fembed%3D1%26file%3Dsrc%252FApp.tsx&amp;display_name=StackBlitz&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fmrloop-use-suspense-query%3Fembed%3D1%26file%3Dsrc%252FApp.tsx&amp;image=https%3A%2F%2Fsocial-img.staticblitz.com%2Fprojects%2Fmrloop-use-suspense-query%2Fe26dbdd9a33623bfb630d622dedec6a0&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/41086a1f8a4decc97efd3eb620e15a9f/href">https://medium.com/media/41086a1f8a4decc97efd3eb620e15a9f/href</a></iframe><p>The source code is available at <a href="https://github.com/mrloop/use-suspense-query">GitHub</a>. Using the custom &lt;DelayedQuery/&gt; component it is easy to compose different loading scenarios to see how they behave. Give it a try, edit and run the code at <a href="https://stackblitz.com/~/github.com/mrloop/use-suspense-query">StackBlitz</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*al1UAx_JUAlXHn9gI2Ro4Q.png" /></figure><p><strong>Nested</strong> shows 3 nested &lt;Suspense/&gt;, and within each &lt;Suspense/&gt; a useSuspenseQuery is run. The fetches run in serial. The loading state for the first query is shown, then when that is loaded the loading state for the second query and then when that is loaded the loading state for the third query is shown.</p><p><strong>Parallel</strong> shows a &lt;Suspense/&gt; containing 3 useSuspenseQuery, with 2 fetches taking 1 second and 1 fetch taking 2 seconds. A single loading state is shown until the last query finishes after 2 seconds.</p><p><strong>Cached</strong> shows two variations. The first variation <strong>Fast load first</strong> show a &lt;Suspense/&gt; containing 3 useSuspenseQuery as in the <strong>Parallel</strong> example but in this case all the queries use the same cache key. They are making the same request and can make use of the cache. The first request will take 4 seconds, the second will take 10 seconds and the third will take 10 seconds. A single loading state is shown until the first 4 second request completes, the other queries don&#39;t attempt to make a query but instead wait for the first query to run that has the same cache key and use the cached result. All results are displayed after 4 seconds.</p><p>The second variation <strong>Slow load first</strong> is the same as <strong>Fast load first</strong> but the order of the queries is changed, in this case the first request will take 10 seconds, the second request will take 4 seconds and the third request will take 10 seconds. A single loading state is shown until the first 10 second request completes, the other queries don’t attempt to make a query but instead wait for the first query to run that has the same cache key and use the cached result. All results are displayed after 10 seconds.</p><p><em>Originally published at </em><a href="https://blog.mrloop.com/javascript/react/tanstack/2024/06/01/use-suspense-query"><em>https://blog.mrloop.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61773f767df9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick full-stack app deployment using AWS and Ember.js]]></title>
            <link>https://awstip.com/quick-full-stack-app-deployment-using-aws-and-ember-js-f11fa0fdb761?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11fa0fdb761</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[full-stack]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Mon, 01 May 2023 13:25:42 GMT</pubDate>
            <atom:updated>2023-05-06T17:10:33.942Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HQ2IfBBvsHxG-bhtA3ImzA.png" /></figure><p>I’ve been working on a small side project, more on that later, and wanted a straight forward way to deploy a serverless full-stack app. I’m using <a href="https://emberjs.com/">Ember.js</a> as the front-end framework and the back-end is <a href="https://aws.amazon.com/">AWS</a>, Amazon Web Services, <a href="https://aws.amazon.com/lambda/">Lambda</a> and other AWS services. This post describes the minimal setup to deploy a full-stack app with <a href="https://emberjs.com/">Ember.js</a> and a <a href="https://aws.amazon.com/lambda/">Lambda</a> API endpoint.</p><p>We’re going to create a simple hello world <a href="https://emberjs.com/">Ember.js</a> app that is deployed to AWS with Serverless Stack, <a href="https://sst.dev/">SST</a>, and uses a hello API endpoint. There are lots of good docs on SST at <a href="https://docs.sst.dev/">https://docs.sst.dev</a>. We&#39;ll use the <a href="https://docs.sst.dev/start/standalone">&#39;Get Started&#39;</a> instructions to create the SST project and then add our <a href="https://emberjs.com/">Ember.js</a> app to it.</p><p>You’ll need an AWS account and <a href="https://docs.sst.dev/advanced/iam-credentials#loading-from-a-file">AWS credentials configured locally</a>. We’ll use <a href="https://pnpm.io/">pnpm</a> but you could also use <a href="https://docs.npmjs.com/cli">npm</a> or <a href="https://yarnpkg.com/getting-started">yarn</a>. The finished app is available <a href="https://github.com/mrloop/ember-sst-example">on github</a>.</p><h3>Create a new app</h3><pre>pnpm create sst ember-sst-example</pre><h3>Start you local dev environment.</h3><pre>pnpm install &amp;&amp; pnpm sst dev</pre><p>This will print the URL of your API endpoint to the console similar to <a href="https://random-string.execute-api.us-east-1.amazonaws.com./">https://random-string.execute-api.us-east-1.amazonaws.com.</a></p><h3>Add an Ember.js app.</h3><pre>cd packages<br>pnpx ember-cli new web --lang en --skip-npm --skip-git<br>pnpm install</pre><p>We’ll remove the ember-cli-sri package from the ember app as it&#39;s not working with the SST cloudfront deployment. In future ember releases, ember-cli &gt; 5, it&#39;s likely the following step won&#39;t be needed. If it fails don&#39;t worry.</p><pre>cd web &amp;&amp; pnpm remove ember-cli-sri</pre><h3>Add the web app to your stacks and link the API to it.</h3><p><em>stacks/MyStack.tsc</em></p><pre>-import { StackContext, Api } from &quot;sst/constructs&quot;;<br>+import { StaticSite, StackContext, Api } from &quot;sst/constructs&quot;;<br><br>export function API({ stack }: StackContext) {<br>  const api = new Api(stack, &quot;api&quot;, {<br>    routes: {<br>      &quot;GET /&quot;: &quot;packages/functions/src/lambda.handler&quot;,<br>    },<br>  });<br><br>+ const web = new StaticSite(stack, &quot;web&quot;, {<br>+   path: &quot;packages/web&quot;,<br>+   buildOutput: &quot;dist&quot;,<br>+   buildCommand: &quot;pnpm build&quot;,<br>+   environment: {<br>+     EMBER_APP_API_URL: api.url,<br>+   }<br>+ });<br>+<br>  stack.addOutputs({<br>    ApiEndpoint: api.url,<br>+   Website: web.url,<br>  });<br>}</pre><h3>Config the Ember.js app to use the API.</h3><p><em>packages/web/config/environment.js</em></p><pre>const ENV = {<br>+  apiUrl: process.env.EMBER_APP_API_URL,</pre><p><em>packages/web/ember-cli-build.js</em></p><pre>const app = new EmberApp(defaults, {<br>- // Add options here<br>+ storeConfigInMeta: false,<br>});</pre><h3>Start the ember app locally and bind SST to it.</h3><pre>cd packages/web<br>pnpm sst bind ember s</pre><h3>Remove the Ember.js welcome page and fetch the welcome from the hello endpoint.</h3><p><em>packages/web/app/routes/application.js</em></p><pre>import Route from &#39;@ember/routing/route&#39;;<br>import config from &#39;web/config/environment&#39;;<br><br>export default class ApplicationRoute extends Route {<br>  async model() {<br>    let response = await fetch(config.apiUrl);<br>    return response.json();<br>  }<br>}</pre><p><em>packages/web/app/templates/application.hbs</em></p><pre>{{page-title &quot;Web&quot;}}<br><br>{{this.model.body}}<br><br>{{outlet}}</pre><p>You should see the API hello message rendered by the Ember.js app.</p><h3>Deploy to production.</h3><pre>pnpm sst deploy --stage prod</pre><p>Congratulations you just deployed your app! The Website URL will be printed to the console.</p><h3>Clean up</h3><p>To cleanup your AWS resources you can remove the development environment and the production environment.</p><pre>pnpm sst remove<br>pnpm sst remove --stage prod</pre><p><em>Originally published at </em><a href="https://blog.mrloop.com/javascript/ember/typescript/aws/sst/2023/04/19/ember-sst.html"><em>https://blog.mrloop.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11fa0fdb761" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/quick-full-stack-app-deployment-using-aws-and-ember-js-f11fa0fdb761">Quick full-stack app deployment using AWS and Ember.js</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing ember-prismic-dom]]></title>
            <link>https://medium.com/qonto-way/introducing-ember-prismic-dom-c362647037d7?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/c362647037d7</guid>
            <category><![CDATA[emberjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[integration]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[prismic]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 10:03:42 GMT</pubDate>
            <atom:updated>2021-03-19T10:05:28.045Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Prismic to Qonto to Display Article Image" src="https://cdn-images-1.medium.com/max/1024/1*j3ikSqb6MQW_WWTndsoKVQ.png" /></figure><h3>Seamless integration of Prismic with Ember.js</h3><p>We are happy to announce <a href="https://github.com/qonto/ember-prismic-dom/">ember-prismic-dom</a>, a new open source package that provides developers with easy <a href="https://prismic.io/">Prismic</a> rendering in <a href="https://emberjs.com/">Ember.js</a>.</p><pre>&lt;Prismic::Dom @nodes={{@prismicData}} /&gt;</pre><p><a href="https://prismic.io/">Prismic</a> is a headless content management system used in numerous features and across multiple platforms at <a href="https://qonto.com/">Qonto</a>. It allows us to easily separate content creation from our application development workflow. For instance Prismic is used to manage frequently asked questions or FAQ’s, for mobile and web apps. It allows Product Managers to update FAQs without involving any developers. Thanks to <a href="https://prismic.io/">Prismic</a> they can be autonomous. A good example of how Prismic can be used is our <a href="https://app.qonto.com/">web app</a> which is written in <a href="https://emberjs.com/">Ember.js</a>.</p><p>In this article we’ll look at simple usage of ember-prismic-dom, how it can replace prismic-dom, how ember-prismic-dom can be used to write custom elements using Ember.js template based rendering and how to leverage existing addons when writing custom elements.</p><h3>Basic Usage</h3><p>The initial pipeline to render the FAQ used <a href="https://prismic.io/">Prismics</a> library <a href="https://www.npmjs.com/package/prismic-dom">prismic-dom</a>.</p><figure><img alt="Diagram of prismic-dom HTML rendering pipeline: web app loads, fetch FAQ json flat, prismic-javascript, json tree / DOM like, prismic-dom, escaped HTML string, Ember.js, add HTML string to DOM unescaped, FAQ displayed." src="https://cdn-images-1.medium.com/max/1024/1*Yrqu9GdleykHg95RSn3tlA.png" /></figure><p>The example below shows how FAQ data retrieved from <a href="http://prismic.io/">prismic.io</a> would be rendered using <a href="https://github.com/prismicio/prismic-dom">prismic-dom</a>.</p><p><em>my-component.js:</em></p><pre>import Component from &#39;@glimmer/component&#39;;<br>import PrismicDOM from &#39;prismic-dom&#39;;</pre><pre>export default class MyComponent extends Component {<br>  get html() {<br>    return PrismicDOM.RichText.asHtml(this.args.myFaq);<br>  }<br>}</pre><p><em>my-component.hbs:</em></p><pre>{{{this.html}}}</pre><p>We wrote <a href="https://github.com/qonto/ember-prismic-dom">ember-prismic-dom</a> to replace <a href="https://github.com/prismicio/prismic-dom">prismic-dom</a> in our application. Using ember-prismic-dom, we can rewrite the previous example.</p><pre>&lt;Prismic::Dom @nodes={{@myFaq}} /&gt;</pre><h3>Motivation</h3><p>We wanted to easily integrate Ember.js components and addons when rendering Prismic data. We also wanted to make auditing our code simpler.</p><h3>Simpler code auditing</h3><p><a href="https://emberjs.com/">Ember.js</a> is a template centric JavaScript framework which uses <a href="https://github.com/handlebars-lang/handlebars.js">Handlebars.js</a> as its default templating language. Handlebars.js escapes values returned by a <a href="https://handlebarsjs.com/guide/expressions.html#basic-usage">‘double-stash’ </a><a href="https://handlebarsjs.com/guide/expressions.html#basic-usage">{{expression}}</a>. To render an unescaped HTML string, in this instance the output of prismic-dom the <a href="https://handlebarsjs.com/guide/#html-escaping">&#39;triple-stash&#39;</a> is used {{{this.html}}}. Internally, prismic-dom will attempt to escape potentially dangerous input so that {{{this.html}}} is safe to use.</p><p>If we use prismic-dom we double the mechanisms in our app being used to escape possibly harmful content which could potentially lead to <a href="https://owasp.org/www-community/attacks/xss/">cross-site scripting vulnerabilities</a>, XSS. Instead of relying on a single method, Handlebar.js, to correctly escape content, we are relying on Hanldebars.js and prismic-dom correctly escaping content which increases the risk of XSS.</p><figure><img alt="Diagram of ember-prismic-dom HTML rendering pipeline: web app loads, fetch FAQ json flat, prismic-javascript, json tree / DOM like, ember-prismic-dom, add HTML string to DOM escaped, FAQ displayed." src="https://cdn-images-1.medium.com/max/1024/1*B9uMT-71CjeaA7gMr-wKig.png" /></figure><p>Take this example</p><p><em>my-component.js:</em></p><pre>export default class MyComponent extends Component {<br>  get html () {<br>    return `&lt;img src=&quot;${element.url}&quot;&gt;`;<br>  }<br>}</pre><p><em>my-component.hbs:</em></p><pre>{{{this.html}}}</pre><p>The {{{this.html}}} is unescaped. We are placing trust in element.url. If that comes from a third party, we are trusting their systems are secure, all content correctly escaped, and anybody with access to updating the image URL is trusted. If element.url=&#39;cats.png&quot; onload=alert(document.cookie);&quot;&#39; when the image is loaded, an alert with the user’s cookie visible will pop up. Instead of alerting the user, the onload could send the cookie to the attacker, giving them access to the user’s account.</p><p>We have a high confidence that Ember.js protects us from XSS and want to rely on a single escape mechanism when rendering HTML. By writing ember-prismic-dom and removing the need for the &#39;triple-stash&#39;, we reduce the amount of code to audit, we only have to trust Ember.js to protect us against XSS.</p><h3>Easily integrate custom components</h3><p>The <a href="https://emberjs.com/">Ember.js</a> template approach doesn’t integrate with prismic-dom. We cannot use custom components when rendering custom prismic elements with prismic-dom.</p><p>prismic-dom provides a mechanism to override element rendering for specific tags using a <a href="https://prismic.io/docs/technologies/html-serializer-javascript#adding-the-html-serializer-function">HTML Serializer function</a>. For example custom element rendering of image and list tags:</p><p><em>my-component.js:</em></p><pre>import Component from &#39;@glimmer/component&#39;;<br>import PrismicDOM from &#39;prismic-dom&#39;;</pre><pre>export default class MyComponent extends Component {<br>  get html () {<br>    return PrismicDOM.RichText.asHtml(this.args.myFaq, this.args.linkResolver, this.htmlSerializer);<br>  }</pre><pre>  get htmlSerializer (type, element, content, children) {<br>    switch(type) {<br>      case Elements.list: return `&lt;ul&gt;${children.join(&#39;&#39;)}&lt;/ul&gt;`;<br>      case Elements.image: return `&lt;img src=&quot;${element.url}&quot;&gt;`;<br>      default: return null;<br>    }<br>  }<br>}</pre><p><em>my-component.hbs:</em></p><pre>{{{this.html}}}</pre><p>Replacing this with <a href="https://github.com/prismicio/prismic-dom">ember-prismic-dom</a> is straightforward and allows for Ember.js template based HTML rendering.</p><pre>&lt;Prismic::Dom @nodes={{@nodes}} @image=&#39;image&#39; @list=&#39;list&#39;&gt;</pre><p><em>image.hbs:</em></p><pre>&lt;img src={{@node.element.url}}/&gt;</pre><p><em>list.hbs:</em></p><pre>&lt;ul&gt;{{yield}}&lt;/ul&gt;</pre><p>More importantly it lets you leverage the existing ember-addon ecosystem. For example you want to use <a href="https://github.com/html-next/ember-async-image">ember-async-image</a></p><p><em>image.hbs:</em></p><pre>&lt;AsyncImage src={{@node.element.url}}/&gt;</pre><h3>Conclusion</h3><p>In this article, we looked at rendering Prismic data using ember-prismic-dom and how it can be used to render custom elements and integrate with ember-addons. We also examined how it helps make code easier to audit. ember-prismic-dom allows us to write idiomatic Ember.js which results in a better developer experience. It makes merge requests to our codebase easier to review and our codebase more readable.</p><p>At <a href="https://qonto.com/">Qonto</a> we love using <a href="https://prismic.io/">Prismic</a>. It enables us to seperate content creation and management from software development. Creating <a href="https://github.com/qonto/ember-prismic-dom">ember-prismic-dom</a> helps us secure, implement, review and ship features built on top of it. If you’re writing an app in Ember.js and are using Prismic I encourage you to try <a href="https://github.com/qonto/ember-prismic-dom/">ember-prismic-dom</a>.</p><h3>About Qonto</h3><p><a href="https://qonto.com/en">Qonto</a> is a neobank for SMEs and freelancers founded in 2016 by Steve Anavi and Alexandre Prot. Since the launch in July 2017, Qonto has made business banking easy for more than 150,000 companies. Thanks to Qonto, business owners save time (streamlined account opening before a day-to-day user experience with unlimited history, accounting exports, expense management feature), have more control while giving their teams autonomy (real-time notifications, user right management system) and have improved visibility on cash-flows (smart dashboards, transactions auto-tagging, and cash-flow monitoring). They also enjoy stellar customer support, at a fair and transparent price.</p><p>Interested in joining a challenging and game changer company? Consult our <a href="https://qonto.com/en/careers">job offers</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c362647037d7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/qonto-way/introducing-ember-prismic-dom-c362647037d7">Introducing ember-prismic-dom</a> was originally published in <a href="https://medium.com/qonto-way">The Qonto Way</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving Ember.js serve and testing performance]]></title>
            <link>https://medium.com/@mr.loop/improving-ember-js-serve-and-testing-performance-8f32bed9cc11?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f32bed9cc11</guid>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webdev]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 07:33:58 GMT</pubDate>
            <atom:updated>2020-10-11T07:33:58.849Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post </em><a href="https://blog.mrloop.com/javascript/ember/typescript/2020/09/18/ember-serve.html"><em>originally appeared on my personal blog.</em></a></p><p>I use the cli command `ember serve` or the abbreviated form `ember s` everyday, to build and serve locally ember apps for development. I noticed that `ember s — path dist` and `ember t — path dist` were taking a long time to start. The ` — path` flag lets you reuse an existing build at the given path</p><pre>➜ ~ ember help | grep — “ — path\|^\w” | grep -B1 — “ — path”<br>ember serve &lt;options…&gt;<br> — path (Path) Reuse an existing build at given path.<br>ember test &lt;options…&gt;<br> — path (Path) Reuse an existing build at given path.</pre><h3>Slow Continuous Integration</h3><p>This long start time also significantly increased the total run time of the continuous integration, CI, test run of the project I was working on. The CI build was split into a compile stage and a test stage. The compile stage fetches dependencies and compiles the app using `ember b` and prepares the server side API for our full stack smoke tests. The app uses ember-cli-typescript, and the build can take around 2 minutes compiling typescript on the CI. The test stage consists of 7 concurrent jobs which all use the compiled assets from the compile stage. By having a single compile stage and 7 test stages the start time to end time will be quicker. The total run time will be slightly longer due to multiple 7 extra test environment boot steps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*XoyQkrBcs96q7KmBdankMQ.png" /><figcaption>Continuous Integration setup</figcaption></figure><p>However the total run time for the CI test run increased more than could be accounted for by the extra boot steps, that is the total time for all the jobs to complete took around 14 minutes more than expected. Due to using concurrent jobs the time from starting the build and the build finishing reduces, there was a decrease in time to feedback but not what was expected and the total run time increased more than expected.</p><h3>What happens when you run `ember t`?</h3><p>`ember` is the <a href="https://cli.ember.com/">command line interface for Ember.js</a> `whereis ember` will tell you where the executable is, in my case `~/.yarn/bin/ember`. Opening `~/yarn/bin/ember` the first line is `#!/usr/bin/env node` telling us its a node app, which creates a ember-cli `<a href="https://github.com/ember-cli/ember-cli/blob/f1d58c22bb70b2c83626abff1e361e860661580d/lib/cli/index.js#L123">CLI</a>` and `<a href="https://github.com/ember-cli/ember-cli/blob/f1d58c22bb70b2c83626abff1e361e860661580d/lib/cli/index.js#L145">run</a>`s it. Parsing the command line args and creating a Command object with in turn creates the appropriate Task object and runs it. In this case it’s the <a href="https://github.com/ember-cli/ember-cli/blob/069dbf3353daad643fc6bd46840b7d1435e41c2f/lib/tasks/test.js">TestTask</a>, which when run invokes <a href="https://github.com/testem/testem">testem</a>, the JS test runner used by Ember.js. The TestTask also allows ember addons to <a href="https://github.com/ember-cli/ember-cli/blob/069dbf3353daad643fc6bd46840b7d1435e41c2f/lib/tasks/test.js#L30">inject middleware</a> into testem. This is very similar to the ServerTask, run when using `ember s`, with also allows ember addons to <a href="https://github.com/ember-cli/ember-cli/blob/836e89b4f26577cc9e492973048b9293b375c914/lib/tasks/server/express-server.js#L100">inject middleware</a> into the development server.</p><h3>Identifying slow build stage</h3><p>There’s some useful documentation describing how to track down <a href="https://github.com/ember-cli/ember-cli/blob/c9320aeb9fb521887bd8fec8f722bef0608c9fe5/docs/perf-guide.md#debug-logging">build performance issues here</a> and in the <a href="https://cli.emberjs.com/release/advanced-use/debugging/">ember-cli docs</a>. Using one of the techniques described, I add a `DEBUG` environment variable before `ember s`</p><pre>$ DEBUG==ember-cli:* ember s — path dist<br> ember-cli:test-server isForTests: false +10s<br> ember-cli:broccoli-watcher serving: /admin/index.html +37s<br> ember-cli:broccoli-watcher serving: (prefix stripped) /index.html, was: /admin/index.html +1ms</pre><p>Why does it take 10s for isForTests, and what is broccoli-watcher doing, I thought we were serving precompiled assets? To dig down a bit more, and produce a lot more debug info ran `DEBUG=*:* ember s — path dist`</p><pre>$ DEBUG=*:* ember s — path dist<br>…<br>– Serving on <a href="http://localhost:4200/admin/">http://localhost:4200/admin/</a><br>…<br>ember-cli-typescript:typecheck-worker Typecheck complete (0 diagnostics) +49s<br>…</pre><p>It’s not `ember-cli:broccoli-watcher` but `ember-cli-typescript:typecheck-worker` taking up all the time. The real culprit is ember-cli-typescript middleware. Type checking is being performed even when the code is already transpiled, the case when using the ` — path` flag.</p><h3>Improving performance</h3><p>The code change to improve performance was <a href="https://github.com/typed-ember/ember-cli-typescript/pull/1148/commits/df022189ffd144fe70ba7bb5551cc3fdde565f0c#diff-287bcabd2443a8d80ebe0fb212241315">small</a>. When adding server middleware or testem middleware check the options passed to ember-cli and if they contain the path flag then don’t run typechecking. A small <a href="https://github.com/ember-cli/ember-cli/pull/9205">`ember-cli` update</a> was also required. ember-cli would pass all the CLI flags to the server middleware, but not to the testem middleware. Without the ember-cli update, ember-cli-typechecking would not of been able to perform the check when testem middleware was added. Interesting to note that for each PR I spent a lot more time figuring out how to effectively test the changes than implement them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/551/1*3ZNTqxZyUYcnWiGbsLpCxA.png" /><figcaption>Decreased CI test time after performance improvement</figcaption></figure><p>These updates significantly sped up the CI build times, and more noticeably, improved my work flow by drastically reducing execution time of the ember commands when using the ` — path` flag.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f32bed9cc11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ReactJS WebExtensions]]></title>
            <link>https://medium.com/@mr.loop/reactjs-webextensions-3c6bfedf03dd?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c6bfedf03dd</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[webextensions]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Fri, 04 Sep 2020 08:38:07 GMT</pubDate>
            <atom:updated>2020-09-07T18:14:42.118Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This post </em><a href="https://blog.mrloop.com/javascript/reactjs/2020/08/21/web-ext-react.html"><em>originally appeared on my personal blog.</em></a></p><p>I wanted to write a <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions">WebExtension</a> for Firefox and Chrome in <a href="https://reactjs.org/">ReactJS</a>, with little configuration in the simplest possible manner, using <a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">create-react-app</a> and <a href="https://github.com/mozilla/web-ext">web-ext</a>, I couldn’t find any guides or instructions online so this is the setup I used. <a href="https://reactjs.org/docs/create-a-new-react-app.html#create-react-app">create-react-app</a> is the recommended tool for creating new single page applications in React.</p><p>Lets create an app, first make sure you’ve got <a href="https://nodejs.org/en/">Node.js</a> installed then:</p><pre>npx create-react-app web-ext-react-hello                       <br>cd web-ext-react-hello                       <br>npm start</pre><p>We have a basic react app running. The next step is to bundle it as a web extension. For this we will use <a href="https://github.com/mrloop/web-ext-react">web-ext-react</a>, the library I extracted from <a href="https://github.com/mrloop/race-ext-react">race-ext-react</a> to help bundle react apps as web extensions.</p><pre>yarn add -D web-ext web-ext-react</pre><p>A web extension can have multiple different javascripts, HTML and CSS for different parts. For example your web extension may have a sidebar or a popup, each with its own javascripts, HTML and CSS. As create-react-app is designed to output a single app and not multiple, we need to conditionally invoke different components of our single react app depending on the context, be it the sidebar, popup, content script or background script. In this case we&#39;ll add a browser action popup. The App component will be conditionally rendered if invoked from the browser action context.</p><h4>src/index.js</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17013bf1d0221073b284044015a7e38e/href">https://medium.com/media/17013bf1d0221073b284044015a7e38e/href</a></iframe><p>The extension needs a manifest.json, create extension/manifest.json and copy the logo to the extension directory cp public/logo192.png extension</p><h4>extension/manifest.json</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff79919dba197cd7b033d1d00cdb1b63/href">https://medium.com/media/ff79919dba197cd7b033d1d00cdb1b63/href</a></iframe><p>This manifest declares a browser action with the react logo. This will appear in the browser toolbar when the extension is run. Clicking the icon and you’ll see the popup running the App component.</p><p>To start the extension scripts can be added to package.json</p><h4>package.json</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d35e3a252f6945131c0368abb6079402/href">https://medium.com/media/d35e3a252f6945131c0368abb6079402/href</a></iframe><p>Tweak the styling, add padding and changing min-height.</p><h4>src/App.css</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43bb858fdff4c36509b274b6b963f4d6/href">https://medium.com/media/43bb858fdff4c36509b274b6b963f4d6/href</a></iframe><p>Now run yarn start:firefox</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*TWXqwwjtgWUTbqPg6GxyJA.png" /></figure><p>We now have the default create-react-app running as a web extension! Try editing the app and live reload still works.</p><p>For complete source code please visit <a href="https://github.com/mrloop/web-ext-react-hello">https://github.com/mrloop/web-ext-react-hello</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c6bfedf03dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Know the competition]]></title>
            <link>https://medium.com/@mr.loop/know-the-competition-998e0dcd612f?source=rss-54bfaf694826------2</link>
            <guid isPermaLink="false">https://medium.com/p/998e0dcd612f</guid>
            <category><![CDATA[ember]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[competition]]></category>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[cycling]]></category>
            <dc:creator><![CDATA[Ewan McDougall]]></dc:creator>
            <pubDate>Wed, 01 Nov 2017 00:00:00 GMT</pubDate>
            <atom:updated>2018-01-29T14:39:07.775Z</atom:updated>
            <content:encoded><![CDATA[<p>I do quite a bit of cycling, and have been thinking about racing in some competitive events again. A lot of the races are organized by British Cycling and for many of the competitive events lists of entrants are published. You can view entrants and their national and regional rankings based on points they’ve won for good placings in previous races. But there is no collated view of entrants and their points. What I want is a list of entrants ordered by there national and regional rankings to quickly see who to watch in a race.</p><p>My original notion was to build a simple API endpoint using <a href="https://serverless.com/">serverless</a>, the single endpoint, GET /competition/{id} would take the id of a race, scrape the relevant British Cycling webpages, cache them where possible and return a list of entrants ordered by ranking. A quick prototype confirmed this was possible but had a pretty dismal user experience. You had to go the britishcycling.org.uk find the race and then copy and paste the id into a web form and then get the returned results.</p><p>Ideally I want to list and search races and then select the race I’m interested in from the same user interface. There were two ways I thought would work well.</p><ul><li>A simple command line interface.</li><li>A web extension which inserts a button into britishcycling.org.uk against each event listing which when pressed lists the entrants. Also will have a larger audience.</li></ul><h3><a href="https://github.com/mrloop/race-lib">race-lib</a></h3><p>The first step was to extract scraping logic from prototype it should be</p><ul><li>isomorphic, that is code will run in browser and in node</li><li>injectable dependencies for fetching web pages and querying them.</li><li>packaged for easy reuse</li><li>include tests</li></ul><p>As part of <a href="https://emberjs.com/blog/2017/07/06/ember-2-14-released.html">Ember.js</a> I’ve been using <a href="https://rollupjs.org/">Rollup</a>, but haven’t configured and used outwith of Ember.js. Rollup will give me a ES6 standardized module I can use in other projects. Re usability of lib is further increased by using injectable dependencies for fetching URLs and for querying html. For example in node <a href="https://www.npmjs.com/package/cheerio">Cheerio</a> is used for parsing and querying html. <a href="https://www.npmjs.com/package/node-fetch">node-fetch</a> a small library which brings the window.fetch API to node is used.</p><h4>Inject</h4><pre>import { Event } from &#39;race-lib&#39;; <br>import cheerio from &#39;cheerio&#39;; <br>import fetch from &#39;node-fetch&#39;; </pre><pre>Event.inject(&#39;fetch&#39;, fetch); <br>Event.inject(&#39;cheerio&#39;, cheerio); </pre><pre>Event.upcomming().then((events) =&gt; { <br>  events.forEach( evt =&gt; console.log(evt.name)); <br>});</pre><p>In the browser window.fetch is used and jQuery used for query the html.</p><pre>$.load = function(htmlString: string) { <br>  const o = $($.parseHTML(htmlString)); <br>  return function (selector) { <br>    return o.find(selector); <br>  } <br>} </pre><pre>Event.inject(&#39;fetch&#39;, window.fetch); <br>Event.inject(&#39;cheerio&#39;, $); </pre><pre>Event.upcomming().then((events) =&gt; { <br>  events.forEach( evt =&gt; console.log(evt.name)); <br>});</pre><h4>Throttle</h4><p>While developing and testing race-lib it became apparent that requests to britishcycling.org.uk is rate limited and a 429 is returned if you exceed 1 request per 4 seconds over about a minute. The throttling of requests in the lib is dumb at the moment, requests are serialized and a 4 second wait between them added. The library allows you to register for notifications about progress so you can notify the user about the progress of fetching rankings.</p><pre>race.addEventListener(&#39;entrantLoaded&#39;, (data) =&gt; { <br>  displayEntrants(data.detail.users, status);<br>  let status = `Entrants loading ${data.detail.loaded}/${data.detail.total}`; <br>});</pre><h3><a href="https://www.npmjs.com/package/race-cli">race-cli</a></h3><p>A simple command interface for retrieving data about entrants to British Cycling races. It is a wrapper around <a href="https://github.com/mrloop/race-lib">race-lib</a> which provides a command line prompt with which to search races and list entrants.</p><p>To install and run use the following commands:</p><pre>npm install -g race-cli <br>race</pre><p>It allows you to search for events and browse them. Upon selecting a race it displays a table of entrants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ihvo4Vup5WYTbeDdmZLi2g.gif" /></figure><h3><a href="https://addons.mozilla.org/en-US/firefox/addon/know-the-competition/">Know the competition</a></h3><p><a href="https://github.com/mrloop/race-ext">Source code here</a></p><p>Next was to write a web extension running <a href="https://github.com/mrloop/race-lib">race-lib</a> and doing some web scraping in browser. I’ve been using <a href="https://emberjs.com/">EmberJS</a> a lot recently. For the web extension a lot of the functionality in <a href="https://emberjs.com/">EmberJS</a> is not needed, and would add unneeded bloat. <a href="https://glimmerjs.com/">GlimmerJS</a> has recently been released and I wanted to try it out for something other than a hello app and this seemed a good excuse.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FzWoRZ70A13M%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DzWoRZ70A13M&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FzWoRZ70A13M%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9db278cccd3f2d79f80e7a7bb8307339/href">https://medium.com/media/9db278cccd3f2d79f80e7a7bb8307339/href</a></iframe><p>Each Entrants button is a <a href="https://glimmerjs.com/">GlimmerJS</a> component inserted into the existing web pages DOM, the modal window is another <a href="https://glimmerjs.com/">GlimmerJS</a> component which is triggered to via window.postMessage. <a href="https://glimmerjs.com/">GlimmerJS</a> handles the presentation layer while <a href="https://github.com/mrloop/race-lib">race-lib</a> fetches and queries the race data. <a href="https://github.com/mrloop/race-lib">race-lib</a> has window.fetch injected to handle fetching other web pages for scraping while jQuery is injected to handle the html querying of these pages to extract the relevant data.</p><h3>Future improvements</h3><p>To reduce the delay caused by throttling, caching British Cycling requests would be desirable. This could be done at the <a href="https://github.com/mrloop/race-lib">race-lib</a> level, the <a href="https://github.com/mrloop/race-lib">race-lib</a> could take an injectable cache-store that could be changed depending on the environment. Or could move the web scraping to a web service which handles the scraping / caching server side, the cache would be shared between users, more likely to hit the cache and it would reduce the amount of requests to British Cycling.</p><p>To increase the possible audience for the web extension could release a web extension for Edge and Chrome. With a unified <a href="https://developer.mozilla.org/en-US/Add-ons/WebExtensions">WebExtension</a> API this should be simple right?</p><p><em>Originally published at </em><a href="https://blog.mrloop.com/javascript/glimmerjs/2017/11/01/know-the-competition.html"><em>blog.mrloop.com</em></a><em> on November 1, 2017.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=998e0dcd612f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>