通用评论

helper.js 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { REGEXP, IMAGE_SPLIT } from "./constant";
  2. import emoji, { prefixUrl, ext } from "./emoji";
  3. const emojiObejct = arrayToObject(emoji, "title");
  4. export function isFunction(functionToCheck) {
  5. return (
  6. functionToCheck && {}.toString.call(functionToCheck) === "[object Function]"
  7. );
  8. }
  9. export function isUrl(userInput) {
  10. const regexp = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g;
  11. var res = userInput.match(regexp);
  12. if (res === null) return false;
  13. else return true;
  14. }
  15. /**
  16. * 将对象数组转换为对象
  17. * @param {array} array Array of Objects
  18. * @param {string} keyField string
  19. */
  20. export function arrayToObject(array, keyField) {
  21. return array.reduce((obj, item) => {
  22. obj[item[keyField]] = item;
  23. return obj;
  24. }, {});
  25. }
  26. /**
  27. * HTML 编码
  28. * 将 < > 等字符串进行编码
  29. * @param {string} str 文本
  30. */
  31. export function htmlEncode(str) {
  32. if (!str) return "";
  33. return str.replace(/<>/gim, function(i) {
  34. return "&#" + i.charCodeAt(0) + ";";
  35. });
  36. }
  37. /**
  38. * 渲染编辑器
  39. * [x] => <img src="x" />
  40. * @param {strig} content
  41. */
  42. export function renderContent(content, onClick) {
  43. let newContent = content;
  44. if (newContent.indexOf(IMAGE_SPLIT) !== -1) {
  45. newContent = newContent.split(IMAGE_SPLIT);
  46. newContent.pop();
  47. newContent = newContent.join("");
  48. }
  49. return htmlEncode(newContent).replace(REGEXP, function(a, b) {
  50. const src = a.slice(1, -1);
  51. // 兼容旧的评
  52. // 因为旧的评论用 [img url] 方式存储的
  53. if (isUrl(src)) {
  54. return `<br/><img src="${src}" alt="${src}" style="max-width: 100%" />`;
  55. }
  56. const value = emojiObejct[src] ? emojiObejct[src].value : src;
  57. return `<img src="${prefixUrl}${value}.${ext}" alt="${value}" />`;
  58. });
  59. }