Skip to content

Instantly share code, notes, and snippets.

@jniac
Last active March 11, 2018 13:15
Show Gist options
  • Save jniac/4d66594cde8f528c286b3e7504e16f48 to your computer and use it in GitHub Desktop.
Save jniac/4d66594cde8f528c286b3e7504e16f48 to your computer and use it in GitHub Desktop.
scripts before oblivion
html = new Proxy({
div: document.createElement('div'),
dom(string) {
this.div.innerHTML = string
return this.div.firstChild
},
}, {
get(target, name) {
return new Proxy(function (name, classes, styles, ...content) {
classes = classes.length ? ` class="${classes.join(' ')}"` : ''
styles = Object.entries(Object.assign({}, ...styles)).map(([key, value]) => `${key}: ${value};`).join('')
styles = styles.length ? ` style="${styles}"` : ''
let string = `<${name}${classes}${styles}>${content.map(v => v.string || v).join('')}</${name}>`
return {
string,
get element() { return target.dom(string) },
}
}, {
name,
classes: [],
styles: [],
get(target, key, proxy) {
if (key === 'class')
return (...args) => {
this.classes.push(...args)
return proxy
}
if (key === 'style')
return (...args) => {
this.styles.push(...args)
return proxy
}
this.name = key
return proxy
},
apply(target, thisArg, arguments) {
return target(this.name, this.classes, this.styles, ...arguments)
},
})
},
})
console.log(
html.div( html.span('hello'), html.span('html') ).string,
)
document.body.append(
html.div(
html.h1('this is a title!'),
html.p(
'this is a paragraph, ',
html.span.style({ color: 'red' })('some words are red, '),
html.span.style({ color: 'blue' })('some others are blue '),
),
html.p.style({ 'font-style': 'italic' })(
'this html is rendered by <strong>javascript!</strong>'
),
html.p('fantastic, isn\'t it ?'),
).element
)
function factory(name) {
return new Proxy(function (name, classes, ...content) {
classes = classes.length ? ` class="${classes.join(' ')}"` : ''
return `<${name}${classes}>${content.join('')}</${name}>`
}, {
name,
classes: [],
get(target, key, proxy) {
this.classes.push(key)
return proxy
},
apply(target, thisArg, arguments) {
let result = target(this.name, this.classes, ...arguments)
this.classes.length = 0
return result
},
})
}
span = factory('span')
div = factory('div')
console.log( span('hello') ) // <span>hello</span>
console.log( span.foo.bar('hello') ) // <span class="foo bar">hello</span>
console.log( div.wrapper(span.word('hello'), span.word('world')) ) //<div class="wrapper"><span class="word">hello</span><span class="word">world</span></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment