lbry-desktop/src/ui/util/remark-lbry.js

67 lines
1.9 KiB
JavaScript
Raw Normal View History

2019-05-30 22:51:23 +02:00
import { parseURI } from 'lbry-redux';
const protocol = 'lbry://';
const locateURI = (value, fromIndex) => value.indexOf(protocol, fromIndex);
const locateMention = (value, fromIndex) => value.indexOf('@', fromIndex);
// Generate a valid markdown link
2019-05-31 22:09:54 +02:00
const createURI = (text, uri) => ({
2019-05-30 22:51:23 +02:00
type: 'link',
2019-05-31 22:09:54 +02:00
url: (uri.startsWith(protocol) ? '' : protocol) + uri,
2019-05-30 22:51:23 +02:00
children: [{ type: 'text', value: text }],
});
2019-05-31 22:09:54 +02:00
const validateURI = (match) => {
2019-05-30 22:51:23 +02:00
if (match) {
try {
const text = match[0];
2019-05-31 22:09:54 +02:00
const uri = parseURI(text);
2019-05-30 22:51:23 +02:00
// Create channel link
if (uri.isChannel) {
2019-05-31 22:09:54 +02:00
return eat(text)(createURI(uri.claimName, text));
2019-05-30 22:51:23 +02:00
}
// Create uri link
2019-05-31 22:09:54 +02:00
return eat(text)(createURI(text, text));
2019-05-30 22:51:23 +02:00
} catch (err) {
// Silent errors: console.error(err)
}
}
}
2019-05-31 22:09:54 +02:00
// Generate a markdown link from channel name
function tokenizeMention(eat, value, silent) {
const match = /^@(\w+)/.exec(value);
return validateURI(match);
}
// Generate a markdown link from lbry url
function tokenizeURI(eat, value, silent) {
const match = /^(lbry:\/\/)+([A-z0-9-_#@])+/.exec(value);
return validateURI(match);
}
2019-05-30 22:51:23 +02:00
// Configure tokenizer for lbry urls
tokenizeURI.locator = locateURI;
tokenizeURI.notInLink = true;
tokenizeURI.notInBlock = true;
// Configure tokenizer for lbry channels
tokenizeMention.locator = locateMention;
tokenizeMention.notInLink = true;
tokenizeMention.notInBlock = true;
// Main module
export default function remarkLBRY() {
const Parser = this.Parser;
const tokenizers = Parser.prototype.inlineTokenizers;
const methods = Parser.prototype.inlineMethods;
// Add an inline tokenizer (defined in the following example).
tokenizers.uri = tokenizeURI;
tokenizers.mention = tokenizeMention;
// Run it just before `text`.
methods.splice(methods.indexOf('text'), 0, 'uri');
methods.splice(methods.indexOf('text'), 0, 'mention');
}