utils.js 1.8 KB
Newer Older
G
guoweijia 已提交
1 2
import store from '@/store'

璃白.'s avatar
璃白. 已提交
3
// 获取选中文本信息
G
guoweijia 已提交
4

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

璃白.'s avatar
璃白. 已提交
16
// 工具栏格式化文本
璃白.'s avatar
璃白. 已提交
17 18 19 20 21 22 23 24 25 26
export function formatText(text, selectionInfo, startStr = "", endStr = "") {
  if (!selectionInfo) return text + startStr + endStr;
  return (
    text.slice(0, selectionInfo.selectionStart) +
    startStr +
    text.slice(selectionInfo.selectionStart, selectionInfo.selectionEnd) +
    endStr +
    text.slice(selectionInfo.selectionEnd)
  );
}
璃白.'s avatar
璃白. 已提交
27

G
guoweijia 已提交
28 29 30 31 32 33 34 35 36
//
export function updateText(startStr, endStr) {
  const selectionInfo = store.state.selectionInfo;
  const originalText = store.state.text;
  const newText = formatText(originalText, selectionInfo, startStr, endStr);
  if (!newText) return;
  store.commit("setText", newText);
}

璃白.'s avatar
璃白. 已提交
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
// 初始化样式
export function initStyle({
  borderColor,
  borderColorActive,
  textColor,
  textColorActive
}) {
  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
    );
  }
  if (textColorActive) {
    document.documentElement.style.setProperty(
      "--md-editor-text-color-active",
      textColorActive
    );
  }
}

// 
export function isNotEmpty(val) {
  return val !== null && val !== undefined;
}