cherry-markdown icon indicating copy to clipboard operation
cherry-markdown copied to clipboard

[Feature request] 增加字数统计功能

Open rachlegend opened this issue 3 years ago • 2 comments

对于lines,words,characters这些方面进行统计

rachlegend avatar Aug 05 '22 01:08 rachlegend

用扩展的方法写了个:

function wordCount(markdown) {
  // 匹配中文和标点符号
  const pattern = /[\u4e00-\u9fa5]|[\u3001\u3002\uff01\uff0c\uff1b\uff1a\u201c\u201d\u2018\u2019\u300a\u300b\u3008\u3009\u3010\u3011\u300e\u300f\u300c\u300d\uff08\uff09\u2014\u2026\u2013\uff0e]/g
  // 统计字符数量,排除换行和空格
  const characters = markdown.replace(/\n|\s/g, '').length;
  // 统计中文和标点符号
  const chineseWords = (markdown.match(pattern) || []).length;
  // 统计英文单词
  const englishWords = markdown.replace(pattern, ' ').split(/[\s\n]+/).filter(Boolean).length;
  const words = chineseWords + englishWords;
  // 统计段落数量,使用至少两个连续换行符分割段落
  const paragraphs = markdown.split(/\n{2,}/).filter(line => line.trim() !== '').length;
  return { characters, words, paragraphs };
}

const countEvent = new Event('count');
let countState = 0;
let customMenuA = Cherry.createMenuHook('字数',  {
  iconName: '',
  onClick: function(selection) {
    const span = document.querySelector('.cherry-toolbar-button.cherry-toolbar-字数');
    countState = (countState + 1) % 3; // 循环切换状态
    span.dispatchEvent(countEvent);
  }
});

let cherry = new Cherry({
  id: 'markdown',
  value: '',
  toolbars:{                                       
    toolbar : ['wordCount'],   
    customMenu: {
      wordCount: customMenuA,
    },
  },
});

const span = document.querySelector('.cherry-toolbar-button.cherry-toolbar-字数');
span.addEventListener('count', () => {
  const markdown = cherry.getMarkdown();
  const { characters, words, paragraphs } = wordCount(markdown);
  if (countState === 0) {
    span.innerHTML = `W ${words}`;
  } else if (countState === 1) {
    span.innerHTML = `C ${characters}`;
  } else {
    span.innerHTML = `P ${paragraphs}`;
  }
});

const editor = cherry.getCodeMirror();
editor.on('change', () => {
  // 每次 editor 修改都触发计数事件
  span.dispatchEvent(countEvent);
})

感觉这个功能比较基础,可以提个PR到hooks里吗

3thernet avatar Nov 24 '23 03:11 3thernet

@H4kur31 没问题的,欢迎贡献。

lyngai avatar Nov 24 '23 04:11 lyngai