rudeshark.net/src/common/text/index.js

69 lines
1.1 KiB
JavaScript
Raw Normal View History

2016-12-28 23:49:51 +01:00
/**
* Misskey Text Analyzer
*/
const elements = [
require('./elements/bold'),
require('./elements/url'),
require('./elements/mention'),
2017-02-08 17:07:06 +01:00
require('./elements/hashtag'),
require('./elements/code')
2016-12-28 23:49:51 +01:00
];
function analyze(source) {
if (source == '') {
return null;
}
const tokens = [];
function push(token) {
if (token != null) {
tokens.push(token);
source = source.substr(token.content.length);
}
}
let i = 0;
// パース
while (source != '') {
const parsed = elements.some(el => {
2017-02-10 18:32:00 +01:00
let tokens = el(source, i);
if (tokens) {
2016-12-28 23:49:51 +01:00
if (!Array.isArray(tokens)) {
tokens = [tokens];
}
tokens.forEach(push);
return true;
}
});
if (!parsed) {
push({
type: 'text',
content: source[0]
});
}
i++;
}
// テキストを纏める
tokens[0] = [tokens[0]];
return tokens.reduce((a, b) => {
if (a[a.length - 1].type == 'text' && b.type == 'text') {
const tail = a.pop();
return a.concat({
type: 'text',
content: tail.content + b.content
});
} else {
return a.concat(b);
}
});
}
module.exports = analyze;