git ssb

16+

cel / patchfoo



Tree: 80d6f2d0c52876f05da71c887266523c37645bf1

Files: 80d6f2d0c52876f05da71c887266523c37645bf1 / lib / util.js

2304 bytesRaw
1var pull = require('pull-stream')
2var cat = require('pull-cat')
3var h = require('hyperscript')
4var u = exports
5
6u.ssbRefRegex = /((?:@|%|&|ssb:\/\/%)[A-Za-z0-9\/+]{43}=\.[\w\d]+)/g
7
8u.isRef = function (str) {
9 if (!str) return false
10 u.ssbRefRegex.lastIndex = 0
11 return u.ssbRefRegex.test(str)
12}
13
14u.readNext = function (fn) {
15 var next
16 return function (end, cb) {
17 if (next) return next(end, cb)
18 fn(function (err, _next) {
19 if (err) return cb(err)
20 next = _next
21 next(null, cb)
22 })
23 }
24}
25
26u.pullReverse = function () {
27 return function (read) {
28 return u.readNext(function (cb) {
29 pull(read, pull.collect(function (err, items) {
30 cb(err, items && pull.values(items.reverse()))
31 }))
32 })
33 }
34}
35
36u.toHTML = function (el) {
37 if (!el) return ''
38 if (typeof el === 'string' || Array.isArray(el)) {
39 return h('div', el).innerHTML
40 }
41 return el.outerHTML || String(el)
42}
43
44u.hyperwrap = function (fn) {
45 var token = '__HYPERWRAP_' + Math.random() + '__'
46 return function (read) {
47 return u.readNext(function (cb) {
48 fn(token, function (err, el) {
49 if (err) return cb(err)
50 var parts = u.toHTML(el).split(token)
51 switch (parts.length) {
52 case 0: return cb(null, pull.empty())
53 case 1: return cb(null, pull.once(parts[0]))
54 case 2: return cb(null,
55 cat([pull.once(parts[0]), read, pull.once(parts[1])]))
56 default: return cb(new Error('duplicate wrap'))
57 }
58 })
59 })
60 }
61}
62
63u.linkDest = function (link) {
64 return typeof link === 'string' ? link : link && link.link || link
65}
66
67u.toArray = function (x) {
68 return !x ? [] : Array.isArray(x) ? x : [x]
69}
70
71u.fromArray = function (arr) {
72 return Array.isArray(arr) && arr.length === 1 ? arr[0] : arr
73}
74
75u.renderError = function(err) {
76 return h('div.error',
77 h('h3', err.name),
78 h('pre', err.stack))
79}
80
81u.pullLength = function (cb) {
82 var len = 0
83 return pull.through(function (data) {
84 len += data.length
85 }, function (err) {
86 cb(err, len)
87 })
88}
89
90u.tryDecodeJSON = function (json) {
91 try {
92 return JSON.parse(json)
93 } catch(e) {
94 return null
95 }
96}
97
98u.extractFeedIds = function (str) {
99 var ids = []
100 String(str).replace(u.ssbRefRegex, function (id) {
101 ids.push(id)
102 })
103 return ids
104}
105

Built with git-ssb-web