Lorem

<lorem> custom element

<lorem>

// 0.1.1 + lorem

import {attr, randomInt} from './helpers.mjs';

// generate <p> html
function _paragraph({
    // words used in a paragraph
    wordsMin = 10,
    wordsMax = 50,
    // characters used in a word
    charsMin = 2,
    charsMax = 10,
}={}){
  
  // # of words
  const w = randomInt(wordsMin, wordsMax);  

  let spans = Array(w).fill(1)      // [ 1, 1, 1, ...]
    .map(_ => randomInt(charsMin,charsMax))
    .map(n => 'x'.repeat(n))        // [ 'xx', 'xxxxx', 'xxx', ...]
    .map(str => `<span>${str}</span>`)
    .join(' ');

  return `<p>${spans}</p>`;
}

// generate <lorem> paragraphs
// n: # of paragraphs
function _lorem(n, {
    // words used in a paragraph
    wordsMin = 10,
    wordsMax = 50,
    // characters used in a word
    charsMin = 2,
    charsMax = 10,
}={}){                  
  return Array(n).fill(1)      // [ 1, 1, 1, ...]
    .map(_ => _paragraph({wordsMin, wordsMax, charsMin, charsMax}))
    .join('');                      // '<p><p><p> ...'
}


/*
  Lorem 可以控制的屬性
  ------------------
  • 有幾個段落 (paragraphs="1")
  • 每個段落幾個單字 (words="15,50")
  • 每個單字有幾個字母 (letters="2,10")
  • 段落間的間距 (gap="1rem")
  • 字體顏色:color="#ddd"
*/

/**
 * Lorem
 * -----
 * # syntax:
 * ```
 * <lorem- 
 *     paragraphs="1" 
 *     words="15,50"    // ⭐️ not implemented❗️
 *     letters="2,10"   // ⭐️ not implemented❗️
 *     gap="1rem"       // ⭐️ not implemented❗️
 *     color="#ddd"
 * >
 * ```
 * 
 * # examples
 * ```
 * <lorem-></lorem->
 * <lorem- color="darkkhaki"></lorem->
 * <lorem- paragraphs="3" color="chocolate"></lorem->
 * ```
 */
export default class Lorem extends HTMLElement {

    // connected to doc
    connectedCallback(){

        // get # of paragraphs from `paragraphs` attribute
        let paragraphs = attr(this, 'paragraphs');
        let n = paragraphs ? +paragraphs : 1;

        // get color from `color` attribute
        let color = attr(this, 'color');
        // ⭐️ set css custom property (css var)
        if (color) this.style.setProperty('--lorem-color', color);

        this.innerHTML = _lorem(n); 
    }
    
}

// ⭐️ register <lorem->
customElements.get('lorem-') || 
customElements.define('lorem-', Lorem);

Last updated

Was this helpful?