egirlskey/src/api/common/text/index.ts

72 lines
1.2 KiB
TypeScript
Raw Normal View History

2016-12-28 22:49:51 +00:00
/**
* Misskey Text Analyzer
*/
const elements = [
require('./elements/bold'),
require('./elements/url'),
2017-03-17 16:16:32 +00:00
require('./elements/link'),
2016-12-28 22:49:51 +00:00
require('./elements/mention'),
2017-02-08 16:07:06 +00:00
require('./elements/hashtag'),
2017-02-11 14:41:57 +00:00
require('./elements/code'),
require('./elements/inline-code'),
require('./elements/emoji')
2016-12-28 22:49:51 +00:00
];
2017-03-18 11:05:11 +00:00
export default (source: string) => {
2016-12-28 22:49:51 +00:00
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 17:32:00 +00:00
let tokens = el(source, i);
if (tokens) {
2016-12-28 22:49:51 +00:00
if (!Array.isArray(tokens)) {
tokens = [tokens];
}
tokens.forEach(push);
return true;
2017-03-18 11:05:11 +00:00
} else {
return false;
2016-12-28 22:49:51 +00:00
}
});
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);
}
});
2017-03-18 11:05:11 +00:00
};