Skip to content
Browse files

add a widget that displays items as array - by default as a markdown …

…subset
  • Loading branch information...
1 parent a2717ee commit 84039af4771d4075e3bb6aca2409450fed7b6349 @dominictarr committed
Showing with 96 additions and 0 deletions.
  1. +55 −0 default-template.js
  2. +41 −0 widget.js
View
55 default-template.js
@@ -0,0 +1,55 @@
+
+function trim (string) {
+ return string.substring(1, string.length - 1)
+}
+
+function style (rx, tag) {
+ return function (text) {
+ var m = rx.exec(text)
+ while (m) {
+ text = text.replace(m[0], '<'+tag+'>'+trim(m[0])+'</'+tag+'>')
+ m = rx.exec(text)
+ }
+ return text
+ }
+}
+
+var italics = style(/_[^_]+_/, 'em')
+var bold = style(/\*[^\*]+\*/, 'strong')
+var code = style(/`[^`]+`/, 'code')
+
+function prefix (rx, tag) {
+ return function (val) {
+ var m = rx.exec(val)
+ if(m) {
+ var l = m[0].length
+ //oh yeah, escape chars...
+ var t = 'function' === typeof tag ? tag(m) : tag
+ return '<'+t+'>'+val.substring(l)+'</'+t+'>'
+ }
+ return val
+ }
+}
+
+var header = prefix(/^#+/, function (m) { return 'H'+m[0].length })
+var li = prefix(/^\s*-+/, 'li')
+
+function styles (text) {
+ return header(li(bold(italics(code(text)))))
+}
+
+function toHTML (val) {
+ if('\n' === val)
+ return '<br/>'
+ return styles(val)
+}
+
+function defaultTemplate (val, key, el) {
+ if(el)
+ return el.innerHTML = toHTML(val), el
+ var el = document.createElement('span')
+ el.innerHTML = toHTML(val)
+ return el
+}
+
+module.exports = defaultTemplate
View
41 widget.js
@@ -0,0 +1,41 @@
+
+module.exports = function (rarry, template) {
+
+ var root = document.createElement('div')
+ template = template || require('./default-template')
+
+ console.log(template)
+
+ var elements = {}
+
+ rarry.on('update', function (change) {
+ for(var id in change)
+ update(id, change[id])
+ })
+
+ function update (key, change) {
+ var el
+ if(el = elements[key]) {
+ var _el = template.call(el, change, key, el)
+ if(_el != el) {
+ elements[key] = _el
+ div.replaceChild(_el, el)
+ }
+ //else, template updated el.
+ return
+ }
+ el = template.call(null, change, key)
+ console.log(el)
+ //var rarry.indexOf(id)
+ //insert before the element that is already there...
+ var before = elements[rarry.keys[rarry.indexOfKey(key) + 1]]
+ elements[key] = el
+ if(before) {
+ root.insertBefore(el, before)
+ } else {
+ root.appendChild(el)
+ }
+ }
+ return root
+}
+

0 comments on commit 84039af

Please sign in to comment.
Something went wrong with that request. Please try again.