-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
184 lines (174 loc) · 5.8 KB
/
Copy pathindex.js
File metadata and controls
184 lines (174 loc) · 5.8 KB
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
const Escaped = { '<': '<', '>': '>', '&': '&' };
const isHtml = Symbol.for('tg-format.html');
function escapeHtml(raw) {
return raw && raw[isHtml] ? raw.text :
(raw == null ? '' : String(raw).replace(/[<>&]/g, m => Escaped[m]));
}
class HtmlString {
constructor(text) {
this.text = text || '';
this[isHtml] = true;
}
static join(vals, sep) {
const result = new HtmlString();
for (let i = 0; i < vals.length; i++) {
if (i > 0) {
result.text += sep; // Separator should not be escaped
}
result.append(vals[i]);
}
return result;
}
append(...others) {
for (let other of others) {
if (Array.isArray(other)) {
this.append(...other);
} else {
this.text += escapeHtml(other);
}
}
return this;
}
toString() {
return this.text;
}
}
function html(strs, ...exprs) {
let text = strs[0];
for (let i = 0; i < strs.length - 1; i++) {
text += escapeHtml(exprs[i]) + strs[i + 1];
}
return new HtmlString(text);
}
function isFormattedLike(object) {
return object && (typeof object == 'object') && ('text' in object) && ('entities' in object) && Array.isArray(object.entities);
}
function detectType(object) {
if ('type' in object) return;
if ('url' in object) return 'text_link';
if ('user' in object) return 'text_mention';
if ('language' in object) return 'pre';
if ('custom_emoji_id' in object) return 'custom_emoji';
}
class FormattedString {
constructor(...vals) {
this.text = '';
this.entities = [];
this.append(...vals);
}
static join(vals, sep) {
const result = new FormattedString();
for (let i = 0; i < vals.length; i++) {
i > 0 && result.append(sep);
result.append(vals[i]);
}
return result;
}
append(...others) {
// We can append other FormattedStrings, strings, or nested arrays of them
for (let other of others) {
if (Array.isArray(other)) {
// Flatten all nested arrays
this.append(...other);
} else
if (isFormattedLike(other)) {
// FormattedString or something similar; merge entities
const len = this.text.length;
this.text += other.text;
for (let entity of other.entities) {
this.entities.push(Object.assign({}, entity, {
offset: entity.offset + len,
}));
}
} else {
// Just stringify
this.text += String(other);
}
}
return this;
}
concat(...others) {
return (new FormattedString(this)).append(...others);
}
substring(st, en) {
// Normalize args
st = st < 0 || isNaN(st) ? 0 : Math.min(st, this.text.length);
en = en === undefined ? this.text.length : (en < 0 || isNaN(en) ? 0 : Math.min(en, this.text.length));
if (st > en) {
[st, en] = [en, st];
}
const result = new FormattedString(this.text.substring(st, en));
result.entities = this.entities.filter(entity => {
return entity.offset - st < result.text.length && entity.offset + entity.length - st > 0;
}).map(entity => {
return Object.assign({}, entity, {
offset: Math.max(entity.offset - st, 0),
length: Math.min(entity.length, result.text.length - (entity.offset - st)),
});
});
return result;
}
slice(st, en) {
const length = this.text.length;
st = Math.max(0, Math.min(st < 0 ? st + length : st, length));
en = en === undefined ? length : Math.max(0, Math.min(en < 0 ? en + length : en, length));
return st < en ? this.substring(st, en) : new FormattedString();
}
toObject(textField, entitiesField) {
// Simple helper for renaming text/entities while destructuring, e.g.:
// const msg = { ...fmt`Hello world`.toObject('photo', 'photo_entities') }
return {
[textField]: this.text,
[entitiesField]: this.entities,
};
}
// TODO: padStart, padEnd, replace, replaceAll, split, trim, trimStart, trimEnd
}
for (const method of ['charAt', 'charCodeAt', 'codePointAt', 'endsWith', 'includes', 'indexOf',
'isWellFormed', 'lastIndexOf', 'localeCompare', 'match', 'matchAll', 'normalize',
'search', 'startsWith', 'toWellFormed']) {
// Lift some methods from String class
FormattedString.prototype[method] = function() {
return this.text[method].apply(this.text, arguments);
}
}
for (const method of ['toLocaleLowerCase', 'toLocaleUpperCase', 'toLowerCase', 'toUpperCase']) {
FormattedString.prototype[method] = function() {
const result = new FormattedString(this.text[method].apply(this.text, arguments));
result.entities = this.entities.map(entity => Object.assign({}, entity));
return result;
}
}
function fmt(strs, ...exprs) {
// Use with tagged template literals: fmt`First name: ${[firstName, 'bold']}, last: ${lastName}`
const builder = new FormattedString(strs[0]);
for (let i = 0; i < strs.length - 1; i++) {
const expr = exprs[i];
if (Array.isArray(expr)) {
// Format segment
const offset = builder.text.length;
let j = 0, k = builder.entities.length;
do {
// Always append first element and all FormattedStrings/Arrays
builder.append(expr[j++]);
} while (isFormattedLike(expr[j]) || Array.isArray(expr[j]));
const length = builder.text.length - offset;
for (; length && j < expr.length; j++, k++) {
// Rest describes either entity types, or full entities (falsy values are filtered out)
expr[j] && builder.entities.splice(k, 0, typeof expr[j] == 'string' ?
{ type: expr[j], offset, length } :
Object.assign(
detectType(expr[j]) ? { type: detectType(expr[j]) } : {},
expr[j],
{ offset, length },
)
);
}
} else {
builder.append(expr);
}
builder.text += strs[i + 1];
}
return builder;
}
module.exports = { fmt, html, FormattedString, HtmlString };