spellRicher

简单富文本编辑

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/534392/1580077/spellRicher.js

  1. //altered from https://github.com/ninja33/ODH/blob/master/src/fg/js/spell.js
  2. ;
  3.  
  4. function spell() {
  5. let exec = (command, value = null) => document.execCommand(command, false, value)
  6. let ensureHTTP = url => /^https?:\//.test(url) ? url : `https://${url}`
  7. let $ = (tag, props, children = [], elm = document.createElement(tag)) =>
  8. children.map(child => child && elm.appendChild(child)) && Object.assign(elm, props)
  9.  
  10. let colorPicker = _ => $('input', {type: 'color'})
  11. let select = options => $('select', {}, options.map(o => $('option', {textContent: o})))
  12.  
  13. let buttons = {};
  14. let queryState = _ => {
  15. for (let cmd in buttons)
  16. buttons[cmd].classList.toggle('selected', document.queryCommandState(cmd))
  17. }
  18.  
  19. let actions = [
  20. [
  21. ['bold'],
  22. ['italic'],
  23. ['underline']
  24. ],
  25. [
  26. ['paragraph', '<p>'],
  27. ['quote', '<blockquote>'],
  28. ['code', '<pre>']
  29. ].map(([title, format]) => [title, _ => exec('formatBlock', format)]),
  30. [
  31. ['insertOrderedList'],
  32. ['insertUnorderedList'],
  33. ['insertHorizontalRule'],
  34. ],
  35. [
  36. ['removeFormat'],
  37. ['unlink']
  38. ],
  39. [
  40. ['createLink', 'link', ensureHTTP],
  41. ['insertImage', 'image', img => img]
  42. ].map(([cmd, type, t]) => [type, url => (url = prompt(`Enter the ${type} URL`)) && exec(cmd, t(url))]),
  43. [
  44. ['undo'],
  45. ['redo']
  46. ]
  47. ]
  48.  
  49. return $('div', {className: 'spell'}, [
  50. $('div', {className: 'spell-bar'}, actions.map(
  51. bar => $('div', {className: 'spell-zone'}, bar.map(
  52. ([cmd, onclick = _ => exec(cmd), control]) => buttons[cmd] = $('button', {
  53. className: 'spell-icon',
  54. title: cmd.replace(/([^a-z])/g, ' $1').toLowerCase(),
  55. onclick
  56. }, [$('i', {className: 'icon-' + cmd.toLowerCase()}), control])
  57. ))
  58. )),
  59. $('div', {
  60. className: 'spell-content',
  61. contentEditable: true,
  62. onkeydown: event => event.which !== 9,
  63. onkeyup: queryState,
  64. onmouseup: queryState
  65. })
  66. ])
  67. }