markdown.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. const md = require("ssb-markdown");
  3. const ssbMessages = require("ssb-msgs");
  4. const ssbRef = require("ssb-ref");
  5. const { span } = require("hyperaxe");
  6. /** @param {{ link: string}[]} mentions */
  7. const toUrl = (mentions) => {
  8. /** @type {{name: string, link: string}[]} */
  9. const mentionNames = [];
  10. /** @param {{ link: string, name: string}} arg */
  11. const handleLink = ({ name, link }) => {
  12. if (typeof name === "string") {
  13. const atName = name.charAt(0) === "@" ? name : `@${name}`;
  14. mentionNames.push({ name: atName, link });
  15. }
  16. };
  17. ssbMessages.links(mentions, "feed").forEach(handleLink);
  18. /** @param {string} ref */
  19. const urlHandler = (ref) => {
  20. // @mentions
  21. const found = mentionNames.find(({ name }) => name === ref);
  22. if (found !== undefined) {
  23. return `/author/${encodeURIComponent(found.link)}`;
  24. }
  25. if (ssbRef.isFeedId(ref)) {
  26. return `/author/${encodeURIComponent(ref)}`;
  27. }
  28. if (ssbRef.isMsgId(ref)) {
  29. return `/thread/${encodeURIComponent(ref)}`;
  30. }
  31. const splitIndex = ref.indexOf("?");
  32. const blobRef = splitIndex === -1 ? ref : ref.slice(0, splitIndex);
  33. // const blobParams = splitIndex !== -1 ? ref.slice(splitIndex) : "";
  34. if (ssbRef.isBlobId(blobRef)) {
  35. return `/blob/${encodeURIComponent(blobRef)}`;
  36. }
  37. if (ref && ref[0] === "#") {
  38. return `/hashtag/${encodeURIComponent(ref.substr(1))}`;
  39. }
  40. return "";
  41. };
  42. return urlHandler;
  43. };
  44. /**
  45. * @param {string} input
  46. * @param {{name: string, link: string}[]} mentions
  47. */
  48. module.exports = (input, mentions = []) =>
  49. md.block(input, {
  50. toUrl: toUrl(mentions),
  51. /** @param character {string} */
  52. emoji: (character) => span({ class: "emoji" }, character).outerHTML,
  53. });