Who

Fear Not The Eloquent DSL

This is not for the faint of heart. 

I present this javascript unjustly designated unfit for production, banished to the deprecated lists and banned from strict mode.  Caught in a heedless fear of dangerous things, the sharp and powerful with keyword held out as one of javascript’s final remnants of hope and last chance for beauty. 

Caution: if you or someone you love has been affected by premature deprecation, ask your doctor about switching to other languages. 

Trigger warning: this does not use strict mode. 

with(safePruned(AppComponents)) {
  mountTo({id: 'app'},
    main({class: 'centered card'}, () => [
      title(`Eloquent Components`),

      p(() => [
        `This example uses a `, em(`custom DSL`),
        ` and `, em(`custom components`),
        ` like this emojiButton:`,
        div(() => emojiButton('random button 1', '🦄'))
      ]),

      p(() => [
        `Edit this and try adding h2, h3, `,
        `strong, span, code, etc...`,
        emojiButton('random button 2', '🦄')
      ])
    ])
  )
}

🦋 Eloquent Components 🦋

This example uses a custom DSL and custom components like this emojiButton:

Edit this and try adding h2, h3, strong, span, code, etc... 

So what does the setup look like? 

First, there’s the base library’s components:

const HtmlComponents = (function() {
  const tags = 'h1 h2 h3 h4 h5 h6 p div b i em span' // and more

  const result = {
    ...Eloquence,

    text(text) {
      return document.createTextNode(renderCallback(text))
    },
  }
  tags.split(' ').forEach(name => {
    result[name] = function(...args) {
      return this.el(name, args)
    }
  })
  return result
})();

Then we add the app’s components:

with(safePruned(HtmlComponents)) {
  const AppComponents = {
    ...HtmlComponents,

    title(...args) {
      const {attrs, cb} = extractOptions(args)
      return div({...attrs, class: 'title'}, () =>
        h1(['🦋 ', cb, ' 🦋'])
      )
    },

    emojiButton(name, emoji) {
      return button(
        { class: 'emoji-button' },
        `${emoji} ${name} ${emoji}`
      )
    }
  }
}

And it’s all a functional approach building up a DOM which can be inserted, appended, rendered over the wire, or just discarded because it uses with and we’ve all given up on javascript? 

One more thing: The “library” for this is can be found in its entirety in source for this post, It’s hardly noticeable weighing in at about 90 short lines, not minified, not compressed, and counting blank lines. 

It’s pure javascript no need to bring along a JSX transpiler. 

I bet it would go great with stimulus.js.