-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbracery-web.js
236 lines (217 loc) · 6.95 KB
/
bracery-web.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
function extend (dest) {
dest = dest || {};
Array.prototype.slice.call (arguments, 1).forEach (function (src) {
if (src)
Object.keys(src).forEach (function (key) { dest[key] = src[key]; })
});
return dest;
}
function cloneDeep (obj) {
return JSON.parse(JSON.stringify(obj));
}
function fromEntries (props_values) {
var obj = {};
props_values.forEach (function (prop_value) {
obj[prop_value[0]] = prop_value[1];
});
return obj;
}
function escapeHTML (str) {
if (typeof(str) !== 'string')
return str;
return str
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
function makeInternalLink (btoa, text, link, funcname) {
var safeLink = btoa (link.text);
return '@@LINK_TYPE@@' + funcname + '@@LINK_DEST@@' + safeLink + '@@LINK_TEXT@@' + text.text + '@@LINK_END@@';
}
var clickHandlerName = 'handleBraceryLink';
function expandInternalLinks (text, isRevealed) {
var regex = /^([\s\S]*)@@LINK_TYPE@@(\S*)?@@LINK_DEST@@(\S*?)@@LINK_TEXT@@([\s\S]*?)@@LINK_END@@([\s\S]*)$/;
var internalLinkCounter = 0;
function replacer (_m, before, linkType, safeLink, text, after) {
replaced = true;
var linkName = 'link' + (++internalLinkCounter) + '_' + safeLink;
return (before
+ (isRevealed[linkName]
? atob(safeLink)
: '<a href="#" onclick="' + clickHandlerName + '(atob(\'' + safeLink + '\'),\'' + linkType + '\',\'' + linkName + '\')">' + text + '</a>')
+ after);
}
do {
var replaced = false;
text = text.replace (regex, replacer);
} while (replaced);
return text;
}
var bookmarkTag = '<bookmark>';
var bookmarkRegex = new RegExp (bookmarkTag, 'ig');
function expandMarkdown (text, marked, isRevealed) {
// Prevent inclusion of <script> tags or arbitrary HTML
var safeText = text.replace(bookmarkRegex,'').replace(/</g,'<').replace(/>/g,'>');
var html = marked (safeText); // Markdown expansion
return expandInternalLinks (html, isRevealed || {});
}
function decodeURIParams (url) {
url = url || window.location.href;
let params = {};
url.replace (/[?&]+([^=&]+)=([^&]*)/gi, (m,key,value) => {
params[key] = window.decodeURIComponent (value);
});
return params;
}
function encodeURIParams (url, params) {
params = params || {};
let paramNames = Object.keys(params).filter ((p) => params[p]);
return url + (paramNames.length
? ('?' + paramNames.map ((p) => (p + '=' + window.encodeURIComponent (params[p]))).join('&'))
: '');
}
function digestText (text, maxDigestChars, link, alwaysIncludeLink) {
var digested = text.replace(/^\s*/,'').replace(/\s*$/,'');
var linkNeeded = ((typeof(link) === 'string' && link.match(/\S/))
|| (digested.length > maxDigestChars)
|| alwaysIncludeLink);
return (linkNeeded
? (typeof(link) === 'function'
? link()
: Promise.resolve(link))
: Promise.resolve())
.then (function (link) {
var linkWithSpace = link ? (' ' + link) : '';
var truncationIndicator = '...';
var truncationNeeded = maxDigestChars && (digested.length > (maxDigestChars - linkWithSpace.length));
var maxTruncatedChars = maxDigestChars - truncationIndicator.length - linkWithSpace.length;
return (truncationNeeded
? (digested.substr (0, maxTruncatedChars) + truncationIndicator)
: digested)
+ ((alwaysIncludeLink || truncationNeeded) ? linkWithSpace : '');
});
}
// So-called "countWords" actually just flags which "words" we have seen
// Words are symbol/variable/function names, or fragments of text
function countWords (text, ParseTree, isWord) {
isWord = isWord || {};
function countWord (word) {
if (word)
isWord[word.toLowerCase()] = true;
}
function countWordsAtNodes (nodes) {
if (nodes)
nodes.forEach (countWordsAtNode);
}
function countWordsAtNode (node) {
if (typeof(node) === 'object') {
if (node.functag)
countWord (ParseTree.funcChar + node.functag);
switch (node.type) {
case 'lookup':
countWord (ParseTree.varChar + node.varname);
break
case 'assign':
countWord (ParseTree.varChar + node.varname);
countWordsAtNodes (node.value);
countWordsAtNodes (node.local);
break
case 'alt':
node.opts.forEach (countWordsAtNodes);
break
case 'rep':
countWordsAtNodes (node.unit);
break
case 'func':
countWord (ParseTree.funcChar + node.funcname);
switch (node.funcname) {
case 'eval':
countWordsAtNodes (node.value);
countWordsAtNodes (node.args);
break
case 'strictquote':
case 'quote':
case 'unquote':
default:
countWordsAtNodes (node.args);
break
}
break
case 'cond':
if (ParseTree.isTraceryExpr (node))
countWord (ParseTree.traceryChar + ParseTree.traceryVarName(node) + ParseTree.traceryChar);
countWordsAtNodes (node.test);
countWordsAtNodes (node.t);
countWordsAtNodes (node.f);
break
case 'root':
case 'alt_sampled':
countWordsAtNodes (node.rhs);
break
case 'rep_sampled':
node.reps.forEach (countWordsAtNodes);
break
case 'sym':
countWord (ParseTree.symChar + ParseTree.leftBraceChar + (node.user || ParseTree.defaultUser) + '/' + node.name + ParseTree.rightBraceChar);
countWordsAtNodes (node.rhs);
countWordsAtNodes (node.bind);
break
default:
break
}
} else if (typeof(node) === 'string')
node
.replace(/[^a-zA-Z0-9_]/g,' ') // these are the characters we keep
.replace(/\s+/g,' ').replace(/^ /,'').replace(/ $/,'') // collapse all runs of space & remove start/end space
.split(' ')
.forEach (countWord);
}
var parsed = ParseTree.parseRhs (text);
countWordsAtNodes (parsed);
return isWord;
}
function getWords (text, ParseTree) {
return Object.keys (countWords (text, ParseTree, {})).sort();
}
function userPartOfName (name) {
var i = name.indexOf('/')
return i < 0 ? '' : name.substr(0,i)
}
function symbolPartOfName (name) {
var i = name.indexOf('/')
return i < 0 ? '' : name.slice(i+1)
}
module.exports = {
extend: extend,
cloneDeep: cloneDeep,
fromEntries: fromEntries,
escapeHTML: escapeHTML,
expandMarkdown: expandMarkdown,
decodeURIParams: decodeURIParams,
encodeURIParams: encodeURIParams,
digestText: digestText,
clickHandlerName: clickHandlerName,
makeInternalLink: makeInternalLink,
countWords: countWords,
getWords: getWords,
userPartOfName: userPartOfName,
symbolPartOfName: symbolPartOfName,
// Special pages
defaultUserName: 'guest',
defaultSymbolName: 'welcome',
suggestionsSymbolName: 'editor_suggestions',
// Other special strings
bookmarkTag: bookmarkTag,
bookmarkRegex: bookmarkRegex,
// Bracery expansion limits
braceryLimits: {
maxDepth: 100,
maxRecursion: 3,
maxReps: 10,
maxNodes: 1048576, // 2^20
maxLength: 16384, // 2^14
enableParse: false,
},
};