Lorem

<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