thingsinjars

  • 6 Jun 2020

    Line-by-line: Flat Cube Web Component

    Line-by-Line breakdowns go into excessive – and sometimes unnecessary – detail about a specific, small project. Be prepared for minutiae.

    Here, I'll go through the FlatCube web component line-by-line. It is a single web component that draws a flattened-out representation of a Rubik's Cube (or other 3x3 twisty puzzle) based on a string passed in that describes the positions of the pieces. A cube contains six faces. A face contains nine pieces.

    You'll probably want to have the full code open in another window to see this in context.

    The component

    Usage

    <flat-cube facelet="UUUUUUUUURRRRRRRRRFFFFFFFFFDDDDDDDDDLLLLLLLLLBBBBBBBBB" />

    Line-by-line

    First, all WebComponents must extend the HTMLElement class. If you're building with a library such as LitElement, you might extend a different class but that class will ultimately extend HTMLElement.

    class FlatCube extends HTMLElement {

    The constructor is called every time a FlatCube element is created, not just once per page load.

      constructor() {

    We have to call the constructor on HTMLElement so that all the behind-the-scenes plumbing is taken care of.

    NOTE: If we don't do this, we can't use this.

        super();

    Now set up some internal variables for the FlatCube itself. this.faces becomes an array representing the order of faces in the facelet string.

        this.faces = 'URFDLB'.split('');
    
        this.facelet = false;

    We attach the shadow DOM to this element so that we can access it easily during the render phase.

        this._shadowRoot = this.attachShadow({ mode: 'open' });

    Then we create the template (see below) and trigger the first render to actually show the element on screen.

        this.template = this.createTemplate();
        this.render();
     }

    Style

    It isn't essential to separate the component's CSS into another method but I like to do it to keep everything nice and tidy.

    style() {

    By using template literals, we can write a block of plain CSS.

        return `

    The :host CSS selector references the element itself. It's kinda like this but in CSS.

    NOTE: It can only be used from inside the Shadow DOM

    :host {

    I want this component to be able to be used inline or as a block item so I'm specifying inline-block. If the context it ends up being used in requires it to be block, it's possible to wrap it in another element.

      display: inline-block;

    Skinning and scaling

    In this web component, one of the main goals of the implementation was the ability to easily change the size of the component and the colours of the faces.

    Luckily, CSS variables make it super easy to make components skinnable and the calc function is very useful for scaling.

    The base measurement

    All the dimensions – the full component width, the faces, the individual pieces – are multiples of the --flat-cube-face-width value. This is passed in from the containing CSS by specifying a value for --flat-cube-face but if it is not specified, we want a fallback of 100px.

      --flat-cube-face-width: var(--flat-cube-face, 100px);
    }

    Now the styles for the complete element. Set position to be relative so that we can absolutely position the individual faces.

    .flat-cube {
      position: relative;

    And specify the element to be the height of 3 faces and the width of 4. This is where the calc function comes in handy, especially in a web component intended to be reusable and seamlessly scalable.

      height: calc(3 * var(--flat-cube-face-width));
      width: calc(4 * var(--flat-cube-face-width));

    I'm using outline rather than border for the lines between the pieces so I want to add a 1px margin around the outside to prevent clipping.

      margin: 1px;
    }

    Each individual face shares the same class

    .face {

    Use the value passed in as the base measurement.

      height: var(--flat-cube-face-width);
      width: var(--flat-cube-face-width);

    Each face is absolutely positioned inside the containing .flat-cube element.

      position: absolute;

    But rather than specify exact positions for each individual piece in a face, we use flexbox to lay them out automatically. We draw the pieces in order then let them wrap onto the next line,

      display: flex;
      flex-wrap: wrap;

    I wanted to specify the width of each piece as a simple ⅓ of the face width. In order to do that, I used outline rather than border as border actually takes space in the element where outline doesn't.

      outline: 1px solid var(--flat-cube-outer, black);
    }
    

    These are simply the top and left positions of the individual faces. We don't really need to go line-by-line here.

    .U-face {
      top: 0;
      left: var(--flat-cube-face-width);
    }
    .L-face {
      top: var(--flat-cube-face-width);
      left: 0;
    }
    .F-face {
      top: var(--flat-cube-face-width);
      left: var(--flat-cube-face-width);
    }
    .R-face {
      top: var(--flat-cube-face-width);
      left: calc(2 * var(--flat-cube-face-width));
    }
    .B-face {
      top: var(--flat-cube-face-width);
      left: calc(3 * var(--flat-cube-face-width));
    }
    .D-face {
      top: calc(2 * var(--flat-cube-face-width));
      left: var(--flat-cube-face-width);
    }
    

    Using the child selector to access the pieces inside the face.

    .face > div {

    As I mentioned above, we want to calculate the width of the pieces simply as ⅓ of a face so we use outline. The alternative would be to calculate the pieces as (⅓ of (the face width minus 2 * the internal border width)). That sounds mistake-prone.

      width: calc(var(--flat-cube-face-width)/3);
      height: calc(var(--flat-cube-face-width)/3);
      outline: 1px solid var(--flat-cube-inner, black);
    }

    Again, this is just colours. We don't need to go line-by-line. The only thing to note is that each piece has a fallback colour specified in case the containing application doesn't pass one in.

    .U-piece {
      background-color: var(--flat-cube-up, #ebed2b);
    }
    .L-piece {
      background-color: var(--flat-cube-left, #ff6b16);
    }
    .F-piece {
      background-color: var(--flat-cube-front, #6cfe3b);
    }
    .R-piece {
      background-color: var(--flat-cube-right, #ec1d35);
    }
    .B-piece {
      background-color: var(--flat-cube-back, #4db4d7);
    }
    .D-piece {
      background-color: var(--flat-cube-down, #fffbf8);
    }

    And finally, we close off our template literal and end the style method.

    `;
      }

    Template

    Now we build up the actual DOM of the element. We've done a lot of styling so far but, technically, we've nothing to apply the styles to. For that, we're going to build up the structure of faces and pieces then attach the styles.

      structure() {

    At this point, we have a couple of choices. We can either build this structure once and update it or build it fresh every time we need to make a change. The latter is easier to write but the former has better performance. So let's do that.

    This is the createTemplate method we called in the constructor. It is called only once for each instance of the component so we don't need to go through the whole building process every time.

    createTemplate() {

    First, create a new template. Templates are designed for exactly this case – building a structure once and reuse it several times.

        const template = document.createElement('template');

    Then we attach the styles we defined earlier:

        template.innerHTML = `<style>${this.style()}</style>`;

    And, finally, actually create the first element that actually appears in the component. This is the div that contains everything. We also add the .flat-cube class to it.

        const cubeElement = document.createElement('div');
        cubeElement.classList.add('flat-cube');

    The this.faces array we defined in the constructor comes back here. We loop over each face we require and create the DOM for it.

        this.faces.forEach((face, i) => {

    A div to contain the face with the shared .face class for the size and the specific class for the position and colour – .U-face, .B-face, etc.

          const faceElement = document.createElement('div');
          faceElement.classList.add('face');
          faceElement.classList.add(`${face}-face`);

    Now we create the individual pieces. If we wanted to make this component customisable so that it could represent cubes with a different number of pieces(2x2, 4x4, 17x17, etc.), we'd use a variable here instead of 9.

          for (let j=0; j < 9; j++) {

    Now we call out to the preparePiece method (see below) without an element to make sure the piece has the right class assigned to it before we append the piece to the face.

            faceElement.appendChild(this.preparePiece(i, j));
          }

    By the time we get here, we have a face div with 9 piece divs appended. Now we can add that to the cube.

          cubeElement.appendChild(faceElement);
        });

    Do that for each face and we have a div containing a completed flat-cube which we can append to the template.

        template.content.appendChild(cubeElement);

    And return the template to the constructor.

        return template;
      }

    Updating

    Now we have the structure in a template, we can grab a copy of it any time we need to update the cube.

      updateTemplate() {

    Passing true to cloneNode means we get a deep clone (containing all the nested faces and pieces) rather than a shallow clone (just the top-level element).

        const update = this.template.content.cloneNode(true);

    We loop over each face and then each piece (div) in each face to update it.

        update.querySelectorAll('.face').forEach((face, i) => {
          face.querySelectorAll('div').forEach((piece, j) => {

    We're using the same method here as we did to create the individual pieces (code reuse is A Good Thing) but this time we're passing in the piece we already have rather than asking the method to create a new one.

            this.preparePiece(i, j, piece);

    The update variable now contains an updated DOM representing the current facelet string.

          });
        });
        return update;
      }

    This method takes the i (index of the face) and j (index of the piece) we need to figure out which colour this piece needs to be. It also takes an optional argument of piece. If we don't provide that – the way we do in the initial createTemplate call – piece will be a newly created div. If we do provide that argument, we'll update whatever is passed in instead.

      preparePiece(i, j, piece = document.createElement('div')) {

    We have to map the facelet string – default: "UUUUUUUUU...etc" – into the two-dimensional structure of faces and pieces. Okay, technically, it's a one-dimensional mapping of a two-dimensional mapping of a three-dimensional structure. But... let's just not.

        const start = (i * 9) + j;
        const end = (i * 9) + j + 1;
    

    This means "If we don't have a facelet string, just colour the piece according to what face it is in, otherwise, colour it according to the i,j position in the facelet string".

        piece.className = !this.facelet ? `${this.faces[i]}-piece` : `${this.facelet.slice(start, end)}-piece`;

    Once we've updated the piece, return it so it can be included in the content.

        return piece;
      }

    We call this method in the constructor and every time we want to update.

      render() {

    Empty out the element content

        this._shadowRoot.innerHTML = '';

    And replace it immediately with the content we generate with the update method from above.

        this._shadowRoot.appendChild(this.updateTemplate());
      }

    This is how we register the component to listen for changes. This getter returns an array listing the attributes we want to listen for.

      static get observedAttributes() {

    There's only one attribute we care about listening to. Any change to the facelet attribute will cause us to re-render.

        return ['facelet'];
      }

    The other part of registering for changes to the attributes. This is the handler that is invoked with the name of the changed attribute (useful when you're listening to a lot of attributes), the oldValue (before the change) and the newValue (after the change).

      attributeChangedCallback(name, oldValue, newValue) {

    We only care about the newValue because we've only registered a single listener and we don't need the oldValue.

        this.facelet = newValue;

    Then we trigger a new render to update the state of the element.

        this.render();
      }

    And we close out our FlatCube class.

    }

    Listening for events

    The final part of the puzzle is to register our new element with the browser so that it knows what to do when it sees our element. We do this by passing our new element to the CustomElementRegistry.

    I like to check if my element has already been registered. Without this, including the script twice by accident will trigger an error that the user of the component isn't necessarily going to recognise.

    if (!window.customElements.get('flat-cube')) {

    To register, you pass the tag name you want to use and the element class.

    NOTE: tag names for custom components must contain a hyphen.

      customElements.define('flat-cube', FlatCube);
    }

    And that's it. Every line looked at and, hopefully, explained.

    Let me know what you would have done differently or if there are any (ideally small) projects you'd like me to look at line-by-line.

    Geek, Development, Javascript, CSS

  • 19 Jul 2019

    Web Components vs Vue Components

    I've been doing a lot of work in Vue recently so when I was asked to evaluate using Web Components on an upcoming project, I approached it with a Vue-ish mindset.

    I've not really kept my eye on Web Components for the last couple of years beyond seeing original proposals being superceded and import specs being replaced. Just seeing those things on the periphery were enough to make me think "Meh... I'll have a look later when it's all died down".

    Now, I know that Web Components !== Vue. But, I was interested in what knowledge could be migrated from one technology to the other. If I were building an actual web app, I'd definitely use Vue. Building a boxful of reusable, shareable UI elements, though... let's find out.


    I'm not going to build anything too complex to start with. How about an "Planet Summary" panel? A simple panel that renders summary information about a planet given a JSON object.

    I have an API that returns JSON information about where in the sky to find planets when given your latitude and longitude. For example, if you're standing slightly south of the centre of Berlin and want to know where Venus is, you'd make this request:

    https://planets-api.awsm.st/venus/52.5/13.4

    And the response would be:

    
    {
      "name": "Venus",
      "number": 1,
      "colour": 1,
      "colleft": 24,
      "colright": 25,
      "alt": 13.043427032890424,
      "az": 290.3495756869397,
      "dec": 22.661411404345362,
      "ra": 110.21545618074397,
      "H": 98.18491228623316,
      "eclon": 108.59563862950628,
      "eclat": 0.5200939814134588,
      "illum": 0.9918628383385676,
      "r": 0.7192422869900328,
      "dist": 1.7155717469739922,
      "mag": -3.909377586961354,
      "elong": 0,
      "pa": 0,
      "p": 1,
      "description": {
        "altitude": "Barely above the horizon",
        "azimuth": "West"
      },
      "visible": false
    }
    

    In this case, it determines Venus isn't visible because, even though it's above the horizon, it's not bright enough given the time of day (about 6pm).

    We want to make a little UI card that displays this information.

    Planet panel

    Mapping Vue features to Web Components

    VueWeb ComponentNotes
    nameclass name
    datainstance properties
    propsattributesthese are not reactive by default. Attributes have to be specifically observed (see watch).
    watchattributeChangedCallbackfirst, register your watched attributes with `observedAttributes` then process them in attributeChangedCallback
    computedgetters
    methodsclass methods
    mountedconnectedCallbackcalled async so the component may not be fully ready or may have been detached. Use Node.isConnected to protect against calling a dead node
    componentWillUnmountdisconnectedCallback
    style blockstyle block inside templatestyles are scoped by default
    template blockliteral templateJS literal templates (backtick strings) are nowhere near as powerful for templating as an actual template library. Vue template features such as `v-for` can be replicated with vanilla JS but a single-purpose template library (such as `lit-html`) is a good idea.

    NOTE: I am deliberately not using Webpack. I realise that actual applications would be using additional tooling but I want to see what we can do without it.


    The first thing that clicked with me was when I realised that computed properties and getters are identical. Nice.

    Here's Vue code to return the planet name or a default string:

    
    computed: {
      name() {
        return this.planet.name || '';
      },
    }
    

    And Web Component:

    
    get name() {
      return this.planet.name || '';
    }
    

    Well, that was easy (and trivial).

    The same goes for defining the custom element for use in the DOM

    Vue:

    
    components: { 
      "planet-summary": PlanetSummary
    }
    

    Web Components:

    
    customElements.define("planet-summary", PlanetSummary);
    

    The only real difference at this level is the data binding. In Vue, props passed from a parent element to a child are automatically updated. If you change the data passed in, the child updates by default. With Web Components, you need to explicitly say you want to be notified of changes.

    This is basically the same as setting a watch in Vue. Data that changes in a slightly less tightly-bound fashion can be watched and the changes trigger updates further down.

    Watches

    Watches in Vue:

    
    watch: {
      altitude(newValue, oldValue) {
        ...
      }
    }
    

    With Web Components, registering a watch and reacting to changes are separate:

    
    static get observedAttributes() {
      return ['altitude'];
    }
    
    attributeChangedCallback(name, oldValue, newValue) {
      if(name === 'altitude') {
        ...
      }
    }
    

    Templating

    Vue contains full templating support – for loops, conditional rendering, seamless passing around of data. Natively, you have literal templates and that's about it.

    To create a list of planets, you'd use the v-for directive and loop over your planets array.

    Vue:

    
    <ul>
      <li v-for="planet in planets">
        <planet-summary :planet="planet"></planet-summary>
      </li>
    </ul>
    

    Web Component

    
    <ul>
      ${this.planets.map(planet => `
      <li>
        <planet-summary planet='${JSON.stringify(planet)}'></planet-summary>
      </li>
      `).join('')}
    </ul>
    

    The join is there because we're creating an HTML string out of an array of list items. You could also accomplish this with a reduce.

    Boilerplate

    With Web Components, your component lives in the Shadow DOM so you are responsible for updating it yourself. Vue handles DOM updates for you.

    Here is a basic render setup:

    
      constructor() {
        super();
        this._shadowRoot = this.attachShadow({ mode: "open" });
        this.render();
      }
      render() {
        this._shadowRoot.innerHTML = '';
        this._shadowRoot.appendChild(this.template().content.cloneNode(true));
      }
    

    This needs to be explicitly included in every component as they are standalone whereas Vue automatically handles DOM updates.

    CSS

    Due to the fact that Web Components live in a separate document fragment, There are complications around sharing styles between the host page and the component which are nicely explained on CSS Tricks. The biggest benefit, on the other hand, is that all styles are scoped by default.

    Vue without Webpack (or other tooling) also has its own complications around styles (specifically scoping styles) but if you're building a Vue application, it is much more straightforward to specify which styles are global and which are scoped.

    Summary

    Here is the Vue Planet Summary and the source of planet-summary-vue.js.

    Here is the Web Component Planet Summary and the source of planet-summary.js.

    Bonus: here's a Planet List Web Component which includes the Planet Summary component. And the source of planet-list.js

    All in all, pretty much everything between basic Vue Components and Web Components can be mapped one-to-one. The differences are all the stuff around the basic construction of the components.

    I'd say that if you're looking to build completely standalone, framework-free reusable components, you'll be able to accomplish it with the Web Components standard. You just might have a bit of extra lifting and boilerplate to deal with.

    On the other hand, if you're already planning on building a full web application with data management and reactive components, use the tools available to you.

    Geek, Development, CSS, Javascript

  • 15 Sep 2013

    Hardy, meet Travis

    While developing the website for Hardy, it seemed obvious that I should be writing Hardy-based tests for it. What better way to figure out how to simplify testing than see what bits of the process were the hardest?

    The site is hosted on GitHub using the gh-pages branch of the hardy.io project. I've played with various toolchains in GitHub pages in the past - csste.st uses Wintersmith, for example - but wanted to follow my own best practice suggestions and automate the process of getting an idea from inside my head, through the text editor, through a bunch of tests and out onto production as much as possible. The main Hardy project uses Travis CI to run unit and acceptance tests on every commit so it seemed obvious to use it for this. What I've ended up with is what I think is a nice, simple process. This is designed for sites hosted on GitHub Pages but is applicable to other sites run through Travis,

    The manual steps of the process are:

    • Make change in your website master branch
    • Preview changes locally
    • Commit changes and push to GitHub

    After this, the automation takes over:

    • Travis pulls latest commit
    • Builds website project to dist folder in master branch
    • Launch web server on Travis
    • Run Hardy tests against local web server
    • On successful test run, push (via git) to gh-pages branch

    The full process is used to build hardy.io. Have a look at the .travis.yml, package.json and post_build.sh files mostly.

    CSS, Development, Javascript

  • 22 Aug 2013

    Hardy - Rigorous Testing

    When GhostStory first came out, it grabbed a fair bit of interest. Unfortunately, despite the number of downloads, I got the impression actual usage was low. There were quite a few stars on the project, a couple of forks and no issues. That's not a good sign. If your project has no issues, it doesn't mean your codes are perfect, it means nobody's using them.

    After asking on Twitter and generally 'around', it emerged that, although people liked the idea,

    1. initial setup was too tricky
    2. test maintenance was a hassle
    3. it’s not WebKit that needs tested most

    Number 3 might seem odd but it has become a fact that, due to the excellent tooling, most web developers use a WebKit variant (chrome, chromium, safari, etc) as their main browser when building. This means they do generally see the problems there where they might miss the ones in IE. This isn't to say WebKit shouldn't also be tested, but GhostStory was built on PhantomJS - a WebKit variant - and therefore only picked up problems that occurred there.

    I've been working evenings and weekends for the last couple of several months to improve the CSS testing setup on here.com and I think we've gotten somewhere. For a start, the name has changed...

    Hardy

    A.K.A. GhostStory 2 - The Ghostening

    This is the bulk of the original GhostStory project but instead of running through PhantomJS, it now uses Selenium via the Webdriver protocol. This means you can run your same CSS tests - still written in Cucumber - against any Webdriver-capable browser. This means Chrome and Firefox and Opera and PhantomJS and Internet Explorer and Mobile Safari on iOS and the Android Browser and and and…. you get the idea.

    Installation

    It’s a simple npm-based install:

    npm install -g hardy
    

    You can then call it by passing a folder of .feature files and step definitions.

    hardy testfolder/
    

    Any relevant files it finds will be automatically parsed.

    Okay, that's most of the difficulty out of the way. A simple install, simple test run and, hopefully, a simple integration into your build system. The only thing left to solve is how to make it easier to make the Cucumber files in the first place.

    Hardy Chrome Extension

    It’s now as simple to make your initial test cases as opening Chrome DevTools and clicking around a bit. Well, almost. Still under development, the Chrome extension helps you make feature files by navigating around the site you want to test and capturing the styles you want to test for. A Hardy-compatible Cucumber file and the accompanying element selector map is generated ready to be dropped into your features folder.

    What's missing?

    Is there anything missing from this flow that you'd like added? A Grunt task to set it up? Prefer something else over Cucumber? Want a Maven Plugin instead of a grunt one? Just let me know. I'm not promising I'll do it, just that I'd like to know.

    Let me know by filing an issue on GitHub.

    Visit hardy.io to learn more.

    Credits and notes

    The image diff code is heavily borrowed from PhantomCSS. In fact, if PhantomCSS could be run through Selenium, I'd switch over to it straight away.

    Project structure and the automatic way Cucumber files, steps and suchlike all play nicely together mostly comes from WebDriverJS and CucumberJS.

    Note: It’s just Hardy, not Hardy.JS. The idea here is just to show how to setup basic CSS tests and provide one (JS) solution to the problem. It’d be nice if Hardy could include common JBehave steps for CSS testing, too. And whatever it is Ruby people use.

    CSS, Javascript, Development

  • newer posts
  • older posts

Categories

Toys, Guides, Opinion, Geek, Non-geek, Development, Design, CSS, JS, Open-source Ideas, Cartoons, Photos

Shop

Colourful clothes for colourful kids

I'm currently reading

Projects

  • Awsm Street – Kid's clothing
  • Stickture
  • Explanating
  • Open Source Snacks
  • My life in sans-serif
  • My life in monospace
Simon Madine (thingsinjars)

@thingsinjars.com

Hi, I’m Simon Madine and I make music, write books and code.

I’m the Engineering Lead for komment.

© 2025 Simon Madine