通用评论

helper.js 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { REGEXP } from "./constant";
  2. import emoji, { prefixUrl, ext } from "./emoji";
  3. export function isFunction(functionToCheck) {
  4. return (
  5. functionToCheck && {}.toString.call(functionToCheck) === "[object Function]"
  6. );
  7. }
  8. export function isUrl(userInput) {
  9. const regexp = /(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9@:%._+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_+.~#?&//=]*)/g;
  10. var res = userInput.match(regexp);
  11. if (res === null) return false;
  12. else return true;
  13. }
  14. /**
  15. * 将对象数组转换为对象
  16. * @param {array} array Array of Objects
  17. * @param {string} keyField string
  18. */
  19. export function arrayToObject(array, keyField) {
  20. return array.reduce((obj, item) => {
  21. obj[item[keyField]] = item;
  22. return obj;
  23. }, {});
  24. }
  25. /**
  26. * HTML 编码
  27. * 将 < > 等字符串进行编码
  28. * @param {string} str 文本
  29. */
  30. export function htmlEncode(str) {
  31. if (!str) return "";
  32. // /[\u00A0-\u9999<>\&]/gim // 中文和 HTML 字符
  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. return htmlEncode(content).replace(REGEXP, function(a, b) {
  44. const src = a.slice(1, -1);
  45. if (isUrl(src)) {
  46. return `<img src="${src}" alt="${src}" style="max-width: 300px" />`;
  47. }
  48. const emojiObejct = arrayToObject(emoji, "title");
  49. const value = emojiObejct[src].value;
  50. return `<img src="${prefixUrl}${value}.${ext}" alt="${value}" />`;
  51. });
  52. }