Skip to content

Instantly share code, notes, and snippets.

@angusgrant
Last active March 3, 2023 22:46
Show Gist options
  • Select an option

  • Save angusgrant/738d04f0eb7b2c7cb37f969ceb02428c to your computer and use it in GitHub Desktop.

Select an option

Save angusgrant/738d04f0eb7b2c7cb37f969ceb02428c to your computer and use it in GitHub Desktop.

Revisions

  1. angusgrant revised this gist Mar 3, 2023. No changes.
  2. angusgrant created this gist Mar 3, 2023.
    173 changes: 173 additions & 0 deletions dice-component-template.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,173 @@
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>Dice - Shadow DOM</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style type="text/css">
    body {
    margin: 0 auto;
    max-width: 40em;
    width: 88%;
    }

    roll-dice {
    --msg-font-size: 1.2rem;
    }
    roll-dice[type="lurid"] {
    --msg-color: white;
    --msg-font-size: 2rem;
    --msg-background-color: cyan;
    }

    roll-dice[type="lurid"]::part(btn) {
    background-color: hotpink;
    border-color:darkblue;
    color: yellow;
    font-size: 1.5rem;
    border-radius: 5px;
    }

    </style>
    </head>
    <body>

    <h1>Dice - Shadow DOM</h1>

    <roll-dice>Roll a D6</roll-dice>


    <roll-dice type="lurid"></roll-dice>


    <script>
    class RollDice extends HTMLElement {

    #dice;

    /**
    * The constructor object
    */
    constructor () {

    // Access parent class properties and methods
    super();

    //create a shadow root
    this.root = this.attachShadow({mode: 'closed'});

    // Define properties
    this.#dice = [1, 2, 3, 4, 5, 6];

    // Render HTML

    this.root.innerHTML =
    `<style>
    .msg {
    color: var(--msg-color, blue);
    background-color: var(--msg-background-color, white);
    font-size: var(--msg-font-size, 14px);
    }
    .btn {
    background-color: red;
    }
    </style>
    <p>
    <button part="btn" class="btn"><slot>Roll Dice</slot></button>
    </p>
    <div aria-live="polite" class="msg"></div>`;

    }

    /**
    * Randomly shuffle an array
    * https://stackoverflow.com/a/2450976/1293256
    * @param {Array} array The array to shuffle
    * @return {Array} The shuffled array
    */
    #shuffle (array) {

    let currentIndex = array.length;
    let temporaryValue, randomIndex;

    // While there remain elements to shuffle...
    while (0 !== currentIndex) {
    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
    }

    return array;

    }

    /**
    * Shuffle dice array and return first number
    * @return {Number} The result
    */
    #roll () {
    this.#shuffle(this.#dice);
    return this.#dice[0];
    }

    /**
    * Handle click events
    * @param {Event} event The event object
    */
    #clickHandler (event) {

    // Get the host component
    let host = event.target.getRootNode().host;

    // Get the message element
    let target = host.root.querySelector('[aria-live="polite"]');
    if (!target) return;

    // Roll the dice
    let roll = host.#roll();

    // Inject the message into the UI
    target.textContent = `You rolled a ${roll}`;

    }

    /**
    * Runs each time the element is appended to or moved in the DOM
    */
    connectedCallback () {

    // Attach a click event listener to the button
    let btn = this.root.querySelector('button');
    if (!btn) return;
    btn.addEventListener('click', this.#clickHandler);

    }

    /**
    * Runs when the element is removed from the DOM
    */
    disconnectedCallback () {

    // Remove the click event listener from the button
    let btn = this.root.querySelector('button');
    if (!btn) return;
    btn.removeEventListener('click', this.#clickHandler);

    }

    }

    if ('customElements' in window) {
    customElements.define('roll-dice', RollDice);
    }
    </script>
    </body>
    </html>