forked from AgregoreWeb/extension-agregore-renderer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssb.js
98 lines (82 loc) · 2.43 KB
/
ssb.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/* global location */ // eslint-disable-line
const markdown = require('ssb-markdown')
const { convert } = require('html-to-text')
const {
isSSBURI,
fromMessageSigil,
fromBlobSigil,
fromFeedSigil
} = require('ssb-uri2')
const { isMsgId, isBlobId, isFeedId, isMsgType, isBlobType, isFeedType, extract: extractSSBref } = require('ssb-ref')
const renderPage = require('./template.js')
const markdownOptions = {
toUrl: ref => renderUrlRef(ref),
imageLink: ref => ref,
emoji: emojiAsMarkup => emojiAsMarkup
}
// Might only work on Chromium
const text = document.querySelector('pre').innerText
const { rendered, title } = renderSsbMarkdown(text)
renderPage(rendered, title)
function renderSsbMarkdown (text) {
const json = JSON.parse(text)
const post = json.value?.content?.text
const rendered = renderMarkdown(post)
const title = renderTitle(post)
return { rendered, title }
}
function renderTitle (md, options = markdownOptions) {
const html = markdown.inline(md, options)
const text = convert(html)
const sentences = text.match(/\(?[^\.\?\!]+[\.!\?]\)?/g) // eslint-disable-line
const title = sentences && sentences.length > 0 ? '' + sentences[0] : ''
return title
}
function renderMarkdown (md, options = markdownOptions) {
return markdown.block(md, options)
}
function renderUrlRef (ref) {
if (looksLikeLegacySSB(ref)) return convertLegacySSB(ref)
if (isSSBURI(ref)) return ref
return ref
}
function sigilToUrlSafe (id) {
const msgKey = isMsgId(id)
const blobKey = isBlobId(id)
const feedKey = isFeedId(id)
const msgType = msgKey
? 'msgKey'
: blobKey
? 'blobKey'
: feedKey
? 'feedKey'
: null
switch (msgType) {
case 'msgKey':
return fromMessageSigil(id)
case 'blobKey':
return fromBlobSigil(id)
case 'feedKey':
return fromFeedSigil(id)
default:
throw new Error(`Invalid ssb id: ${id}`)
}
}
function looksLikeLegacySSB (str) {
if (!str.startsWith('%') && !str.startsWith('&') && !str.startsWith('@')) return false
if (isMsgType(str)) return true
if (isBlobType(str)) return true
if (isFeedType(str)) return true
return false
}
function convertLegacySSB (url) {
return standardiseSSBuri(sigilToUrlSafe(extractSSBref(url)))
}
/** prefer ssb:// uri */
function standardiseSSBuri (url) {
if (!url.startsWith('ssb://') && url.startsWith('ssb:')) {
const path = url.split('ssb:')
return `ssb://${path.slice(1)}`
}
return url
}