Files: 80d6f2d0c52876f05da71c887266523c37645bf1 / lib / util.js
2304 bytesRaw
1 | var pull = require('pull-stream') |
2 | var cat = require('pull-cat') |
3 | var h = require('hyperscript') |
4 | var u = exports |
5 | |
6 | u.ssbRefRegex = /((?:@|%|&|ssb:\/\/%)[A-Za-z0-9\/+]{43}=\.[\w\d]+)/g |
7 | |
8 | u.isRef = function (str) { |
9 | if (!str) return false |
10 | u.ssbRefRegex.lastIndex = 0 |
11 | return u.ssbRefRegex.test(str) |
12 | } |
13 | |
14 | u.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 | |
26 | u.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 | |
36 | u.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 | |
44 | u.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 | |
63 | u.linkDest = function (link) { |
64 | return typeof link === 'string' ? link : link && link.link || link |
65 | } |
66 | |
67 | u.toArray = function (x) { |
68 | return !x ? [] : Array.isArray(x) ? x : [x] |
69 | } |
70 | |
71 | u.fromArray = function (arr) { |
72 | return Array.isArray(arr) && arr.length === 1 ? arr[0] : arr |
73 | } |
74 | |
75 | u.renderError = function(err) { |
76 | return h('div.error', |
77 | h('h3', err.name), |
78 | h('pre', err.stack)) |
79 | } |
80 | |
81 | u.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 | |
90 | u.tryDecodeJSON = function (json) { |
91 | try { |
92 | return JSON.parse(json) |
93 | } catch(e) { |
94 | return null |
95 | } |
96 | } |
97 | |
98 | u.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