utils.js 12.1 KB
Newer Older
璃白.'s avatar
璃白. 已提交
1
import marked from "marked";
璃白.'s avatar
璃白. 已提交
2 3
// import videojs from "video.js";
// import "video.js/dist/video-js.min.css";
璃白.'s avatar
璃白. 已提交
4
// 获取选中文本信息
G
guoweijia 已提交
5

璃白.'s avatar
璃白. 已提交
6 7
export function getSelectionInfo(selectorId) {
  const selector = document.getElementById(selectorId);
8
  if (!selector) return;
璃白.'s avatar
璃白. 已提交
9 10
  const { selectionStart = 0, selectionEnd = 0 } = selector;
  if (selectionStart === selectionEnd) return "";
璃白.'s avatar
璃白. 已提交
11
  const selection = window.getSelection().toString();
璃白.'s avatar
璃白. 已提交
12
  return {
璃白.'s avatar
璃白. 已提交
13
    selectorId,
璃白.'s avatar
璃白. 已提交
14
    selection,
璃白.'s avatar
璃白. 已提交
15 16 17 18 19
    selectionStart,
    selectionEnd
  };
}

20 21 22 23 24 25 26 27 28 29 30 31 32 33
// 节流
export const throttle = function(fn, wait) {
  var timer = null;
  return function() {
    var context = this;
    var args = arguments;
    if (!timer) {
      timer = setTimeout(function() {
        fn.apply(context, args);
        timer = null;
      }, wait);
    }
  };
};
璃白.'s avatar
璃白. 已提交
34
// 获取光标的位置
璃白.'s avatar
璃白. 已提交
35 36
export const getPosition = function(selectorId) {
  const element = document.getElementById(selectorId);
37
  if (!element) return 0;
璃白.'s avatar
璃白. 已提交
38 39 40 41 42 43 44 45 46 47 48 49
  let cursorPos = 0;
  if (document.selection) {
    //IE
    var selectRange = document.selection.createRange();
    selectRange.moveStart("character", -element.value.length);
    cursorPos = selectRange.text.length;
  } else if (element.selectionStart || element.selectionStart == "0") {
    cursorPos = element.selectionStart;
  }
  return cursorPos;
};

璃白.'s avatar
璃白. 已提交
50
// 工具栏格式化文本
璃白.'s avatar
璃白. 已提交
51
export function formatText(text, selectionInfo, startStr = "", endStr = "") {
璃白.'s avatar
璃白. 已提交
52 53
  if (!selectionInfo) return;
  const newText =
璃白.'s avatar
璃白. 已提交
54 55 56 57
    text.slice(0, selectionInfo.selectionStart) +
    startStr +
    text.slice(selectionInfo.selectionStart, selectionInfo.selectionEnd) +
    endStr +
璃白.'s avatar
璃白. 已提交
58 59
    text.slice(selectionInfo.selectionEnd);
  return newText;
璃白.'s avatar
璃白. 已提交
60
}
璃白.'s avatar
璃白. 已提交
61

62 63 64 65 66 67 68
export function setzIndex(index) {
  document.documentElement.style.setProperty(
    "--md-editor-fullScrren-zIndex",
    index
  );
}

璃白.'s avatar
璃白. 已提交
69 70
// 初始化样式
export function initStyle({
璃白.'s avatar
璃白. 已提交
71
  dark,
璃白.'s avatar
璃白. 已提交
72 73 74
  borderColor,
  borderColorActive,
  textColor,
璃白.'s avatar
璃白. 已提交
75
  textColorActive,
璃白.'s avatar
fix  
璃白. 已提交
76
  placeholderColor,
璃白.'s avatar
璃白. 已提交
77 78
  frameBgColor,
  contentBgColor,
璃白.'s avatar
fix  
璃白. 已提交
79
  codeBgColor,
璃白.'s avatar
feat  
璃白. 已提交
80
  codeTheme,
璃白.'s avatar
璃白. 已提交
81
  helpdocColor,
璃白.'s avatar
璃白. 已提交
82 83
  itemActiveBgColor,
  linkCardBgColor
璃白.'s avatar
璃白. 已提交
84
}) {
璃白.'s avatar
璃白. 已提交
85 86
  // 夜晚模式
  if (dark) {
87 88 89
    borderColor = "#44444F";
    borderColorActive = "#2998F2";
    textColor = "#777888";
璃白.'s avatar
fix  
璃白. 已提交
90
    placeholderColor = "#777888";
91 92 93 94
    textColorActive = "#CCCCD8";
    frameBgColor = "#222226";
    codeBgColor = "#777888";
    contentBgColor = "#222226";
璃白.'s avatar
feat  
璃白. 已提交
95
    helpdocColor = "#CCCCD8";
璃白.'s avatar
璃白. 已提交
96
    itemActiveBgColor = "#777888";
璃白.'s avatar
璃白. 已提交
97 98 99 100 101 102 103
    linkCardBgColor = "#222226";
  }
  if (linkCardBgColor) {
    document.documentElement.style.setProperty(
      "--md-editor-link-card-bg-color",
      linkCardBgColor
    );
璃白.'s avatar
璃白. 已提交
104 105 106 107 108 109 110
  }
  if (frameBgColor) {
    document.documentElement.style.setProperty(
      "--md-editor-frame-bg-color",
      frameBgColor
    );
  }
璃白.'s avatar
璃白. 已提交
111 112 113 114 115 116
  if (itemActiveBgColor) {
    document.documentElement.style.setProperty(
      "--md-editor-item-active-bg-color",
      itemActiveBgColor
    );
  }
璃白.'s avatar
璃白. 已提交
117 118 119 120
  if (contentBgColor) {
    document.documentElement.style.setProperty(
      "--md-editor-content-bg-color",
      contentBgColor
121
    );
璃白.'s avatar
璃白. 已提交
122 123 124 125 126 127 128 129 130
  }

  if (codeBgColor) {
    document.documentElement.style.setProperty(
      "--md-editor-code-bg-color",
      codeBgColor
    );
  }

璃白.'s avatar
璃白. 已提交
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
  if (borderColor) {
    document.documentElement.style.setProperty(
      "--md-editor-border-color",
      borderColor
    );
  }
  if (borderColorActive) {
    document.documentElement.style.setProperty(
      "--md-editor-border-color-active",
      borderColorActive
    );
  }
  if (textColor) {
    document.documentElement.style.setProperty(
      "--md-editor-text-color",
      textColor
    );
  }
璃白.'s avatar
feat  
璃白. 已提交
149 150 151 152 153 154
  if (helpdocColor) {
    document.documentElement.style.setProperty(
      "--md-editor-helpdoc-color",
      helpdocColor
    );
  }
璃白.'s avatar
璃白. 已提交
155 156 157 158 159 160
  if (textColorActive) {
    document.documentElement.style.setProperty(
      "--md-editor-text-color-active",
      textColorActive
    );
  }
璃白.'s avatar
fix  
璃白. 已提交
161 162 163
  if (codeTheme) {
    switch (codeTheme) {
      case "dark":
璃白.'s avatar
璃白. 已提交
164
        import("@/assets/style/code/dark.less");
璃白.'s avatar
fix  
璃白. 已提交
165 166
        break;
      case "light":
璃白.'s avatar
璃白. 已提交
167
        import("@/assets/style/code/lightfair.less");
璃白.'s avatar
fix  
璃白. 已提交
168
        break;
璃白.'s avatar
fix  
璃白. 已提交
169
      case "atom-one-dark":
璃白.'s avatar
璃白. 已提交
170
        import("@/assets/style/code/atom-one-dark.less");
璃白.'s avatar
fix  
璃白. 已提交
171 172 173 174
        break;
      default:
        break;
    }
璃白.'s avatar
fix  
璃白. 已提交
175
  } else {
璃白.'s avatar
璃白. 已提交
176
    import("@/assets/style/code/lightfair.less");
璃白.'s avatar
fix  
璃白. 已提交
177
  }
璃白.'s avatar
璃白. 已提交
178 179
}

璃白.'s avatar
璃白. 已提交
180
//
璃白.'s avatar
璃白. 已提交
181 182 183
export function isNotEmpty(val) {
  return val !== null && val !== undefined;
}
璃白.'s avatar
璃白. 已提交
184 185 186 187

export function isNotFalse(val) {
  return val !== false;
}
188 189 190 191 192 193 194

export function checktUrl(val, rule) {
  if (!val || !rule) return;
  const hideEl = document.createElement("div");
  hideEl.style.display = "none";
  hideEl.innerHTML = val;
  const imgList = Array.from(hideEl.getElementsByTagName("img"));
璃白.'s avatar
璃白. 已提交
195 196 197 198 199 200 201 202
  // const icoRule = /http[s]:\/\/.+\.ico/;
  return imgList.filter(item => {
    // return !rule.test(item.src) && !icoRule.test(item.src);
    return (
      !rule.test(item.src) &&
      item.getAttribute("referrerpolicy") !== "no-referrer"
    );
  });
203 204 205 206 207 208 209 210
}

export function checkBoswer() {
  const agent = navigator.userAgent.match(
    /(iPhone|iPod|Android|ios|iOS|iPad|Backerry|WebOS|Symbian|Windows Phone|Phone)/i
  );
  return agent !== null;
}
璃白.'s avatar
璃白. 已提交
211 212

export function isAndroid() {
璃白.'s avatar
璃白. 已提交
213
  const agent = navigator.userAgent.match(/(Android)/i);
璃白.'s avatar
璃白. 已提交
214 215
  return agent !== null;
}
璃白.'s avatar
璃白. 已提交
216
// 去除头部空格行
217 218 219 220
export function removeBlankLine(val) {
  if (!val) return "";
  return val.replace(/^\n/, "");
}
璃白.'s avatar
璃白. 已提交
221 222 223

// 获取被过滤掉的标签
export function getFilteredTags(oldStr, newStr) {
璃白.'s avatar
璃白. 已提交
224 225 226
  // if (oldStr.length - newStr.length === 0) return [];
  // const filteredStr = oldStr.replace(newStr.trim(), "");
  // console.log(11, filteredStr);
璃白.'s avatar
璃白. 已提交
227
  const virtualDom = document.createElement("div");
璃白.'s avatar
璃白. 已提交
228 229 230 231 232 233 234 235
  virtualDom.innerHTML = oldStr;
  const oldTags = Array.from(virtualDom.getElementsByTagName("*"));
  virtualDom.innerHTML = newStr;
  const newTags = Array.from(virtualDom.getElementsByTagName("*"));

  // 待优化
  const filteredTags = new Array(oldTags.length - newTags.length).fill(0);

璃白.'s avatar
璃白. 已提交
236 237
  return filteredTags;
}
璃白.'s avatar
璃白. 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
// 格式刷的规则
export function copyFormatRules(selection) {
  if (!selection) return "";
  const first1 = selection.slice(0, 1);
  const first2 = selection.slice(0, 2);
  const first3 = selection.slice(0, 3);
  const first4 = selection.slice(0, 4);
  const first5 = selection.slice(0, 5);
  const first6 = selection.slice(0, 6);
  const first7 = selection.slice(0, 7);
  const end1 = selection.slice(-1);
  const end2 = selection.slice(-2);
  const end3 = selection.slice(-3);
  let formatType = "";
  switch (true) {
    // 斜体
    case first1 === "_" && end1 === "_":
      formatType = {
        startStr: "_",
        endStr: "_"
      };
      break;
    // 加粗
    case first2 === "**" && end2 === "**":
      formatType = {
        startStr: "**",
        endStr: "**"
      };
      break;
    // 代码
    case first3 === "```" && end3 === "```":
      formatType = {
        startStr: "\n```\n",
璃白.'s avatar
璃白. 已提交
271 272
        endStr: "\n\n```",
        type: "code"
璃白.'s avatar
璃白. 已提交
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
      };
      break;
    // 引用
    case first2 === "> ":
      formatType = {
        startStr: "\n> ",
        endStr: ""
      };
      break;
    // 待办
    case first6 === "- [ ] ":
      formatType = {
        startStr: "\n- [ ] ",
        endStr: ""
      };
      break;
    // 无序列表
    case first2 === "- ":
      formatType = {
        startStr: "\n- ",
        endStr: ""
      };
      break;
    // H6
    case first7 === "###### ":
      formatType = {
        startStr: "\n###### ",
        endStr: ""
      };
      break;
    // H5
    case first6 === "##### ":
      formatType = {
        startStr: "\n##### ",
        endStr: ""
      };
      break;
    // H4
    case first5 === "#### ":
      formatType = {
        startStr: "\n#### ",
        endStr: ""
      };
      break;
    // H3
    case first4 === "### ":
      formatType = {
        startStr: "\n### ",
        endStr: ""
      };
      break;
    // H2
    case first3 === "## ":
      formatType = {
        startStr: "\n## ",
        endStr: ""
      };
      break;
    // H1
    case first2 === "# ":
      formatType = {
        startStr: "\n# ",
        endStr: ""
      };
      break;
    default:
      break;
  }

  return formatType;
}
璃白.'s avatar
璃白. 已提交
344 345 346 347 348 349 350 351 352 353 354

export function addLanguageClass(html) {
  const virtualDom = document.createElement("div");
  virtualDom.innerHTML = html;
  virtualDom.querySelectorAll("code").forEach(item => {
    if (!/language-/.test(item.className)) {
      item.className = "language-javascript";
    }
  });
  return virtualDom;
}
璃白.'s avatar
璃白. 已提交
355 356 357 358 359 360 361 362 363 364 365 366 367
export function addLinkTarget(html) {
  const virtualDom = document.createElement("div");
  virtualDom.innerHTML = html;
  const userList = [];
  Array.from(virtualDom.querySelectorAll("a[href]")).forEach(item => {
    item.setAttribute("target", "_blank");
    if (item.getAttribute("type") === "user") {
      userList.push(item.dataset.user);
    }
  });
  const list = Array.from(new Set(userList)); // 去重
  return { callUserList: list, userHtml: virtualDom.innerHTML };
}
璃白.'s avatar
璃白. 已提交
368 369 370
export function getLinkTags(id, html) {
  const virtualDom = document.createElement("div");
  virtualDom.innerHTML = html;
璃白.'s avatar
璃白. 已提交
371
  const links = Array.from(
璃白.'s avatar
璃白. 已提交
372
    virtualDom.querySelectorAll("a:not([download])")
璃白.'s avatar
璃白. 已提交
373
  ).map((item, index) => {
璃白.'s avatar
璃白. 已提交
374
    item.id = id + "_" + new Date().getTime() + "_" + index;
璃白.'s avatar
璃白. 已提交
375 376 377 378 379 380
    return {
      id: item.id,
      title: item.innerText,
      url: item.href
    };
  });
璃白.'s avatar
璃白. 已提交
381 382
  return { vDom: virtualDom, links };
}
璃白.'s avatar
璃白. 已提交
383

璃白.'s avatar
璃白. 已提交
384 385 386 387
export function getLinkTitle(linkEl, item) {
  const originTitle = linkEl.innerText;
  const titleEl = Array.from(linkEl.getElementsByClassName("md_link_title"));
  if (titleEl.length) return item.title || titleEl[0].innerText;
璃白.'s avatar
璃白. 已提交
388 389 390 391 392 393
  return /^(http|www)/.test(originTitle) ? "" : originTitle;
}

export function removeLinkHeadAndEnd(link) {
  if (!link) return "";
  return link.replace(/^https?:\/\//, "").replace(/\/$/, "");
璃白.'s avatar
璃白. 已提交
394
}
璃白.'s avatar
璃白. 已提交
395

璃白.'s avatar
璃白. 已提交
396
export function renderLinkCard(title, item) {
璃白.'s avatar
璃白. 已提交
397 398 399
  console.log(item.title);
  console.log(item.url);

璃白.'s avatar
璃白. 已提交
400
  return `
璃白.'s avatar
璃白. 已提交
401 402 403 404 405 406 407
  ${
    removeLinkHeadAndEnd(item.title) === removeLinkHeadAndEnd(item.url)
      ? ""
      : `
    <span class="md_link_title">${title || item.title || ""}</span>
    `
  }
璃白.'s avatar
璃白. 已提交
408 409 410
  ${`<span class="md_link_desc" style="${
    item.description ? "" : "margin: 0px 0 2px"
  }">${item.description || ""}</span>`}
璃白.'s avatar
璃白. 已提交
411 412
  <span class="md_flex_card">
  ${
璃白.'s avatar
璃白. 已提交
413
    item.icon
璃白.'s avatar
璃白. 已提交
414
      ? `<img class="md_link_img" referrerpolicy="no-referrer" id="md_link_img" src="${item.icon}" />`
璃白.'s avatar
璃白. 已提交
415 416 417 418 419 420 421 422
      : "<span class='md_link_img icon iconfont icon-lianjie'></span>"
  }
    <span class="flex-1">
      <span class="md_link_url">${item.url}</span>
    </span>
  </span>`;
}

璃白.'s avatar
璃白. 已提交
423 424 425 426 427 428 429
export function preventDefault(id) {
  const textEl = document.getElementById(id);
  textEl.blur();
  setTimeout(() => {
    textEl.focus();
  }, 0);
  return;
璃白.'s avatar
璃白. 已提交
430
}
璃白.'s avatar
璃白. 已提交
431

璃白.'s avatar
璃白. 已提交
432 433 434 435 436
// export async function renderVideo(id, html) {
//   const virtualDom = document.createElement("div");
//   virtualDom.innerHTML = html;
//   document.body.appendChild(virtualDom);
//   const videoList = Array.from(virtualDom.getElementsByTagName("video"));
璃白.'s avatar
璃白. 已提交
437

璃白.'s avatar
璃白. 已提交
438 439 440 441 442 443 444 445 446 447 448 449 450
//   const newHtml = await new Promise((resolve, rej) => {
//     videoList.forEach(item => {
//       console.log(item);
//       item.setAttribute("controls", "controls");
//     });
//     setTimeout(() => {
//       const newHtml = virtualDom.innerHTML;
//       resolve(newHtml);
//       document.body.removeChild(virtualDom);
//     }, 5000);
//   });
//   return newHtml;
// }
璃白.'s avatar
璃白. 已提交
451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479

// 获取方法参数名
export function getParameterName(fn) {
  if (typeof fn !== "object" && typeof fn !== "function") return;
  const COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/gm;
  const DEFAULT_PARAMS = /=[^,)]+/gm;
  const FAT_ARROWS = /=>.*$/gm;
  let code = fn.prototype ? fn.prototype.constructor.toString() : fn.toString();
  code = code
    .replace(COMMENTS, "")
    .replace(FAT_ARROWS, "")
    .replace(DEFAULT_PARAMS, "");
  let result = code
    .slice(code.indexOf("(") + 1, code.indexOf(")"))
    .match(/([^\s,]+)/g);
  return result === null ? [] : result;
}

export function getfilesize(size) {
  if (!size || isNaN(size)) return size;
  var num = 1024.0; //byte
  if (size < num) return size + "B";
  if (size < Math.pow(num, 2)) return (size / num).toFixed(2) + "K"; //kb
  if (size < Math.pow(num, 3))
    return (size / Math.pow(num, 2)).toFixed(2) + "M"; //M
  if (size < Math.pow(num, 4))
    return (size / Math.pow(num, 3)).toFixed(2) + "G"; //G
  return (size / Math.pow(num, 4)).toFixed(2) + "T"; //T
}