WaniKani Markdown Editor Notes (2023)

Write Markdown and HTML in the notes

  1. // ==UserScript==
  2. // @name WaniKani Markdown Editor Notes (2023)
  3. // @namespace wanikani
  4. // @description Write Markdown and HTML in the notes
  5. // @version 2.2.0
  6. // @require https://uicdn.toast.com/editor/latest/toastui-editor-all.min.js
  7. // @require https://unpkg.com/dexie@3/dist/dexie.js
  8. // @require https://gf.qytechs.cn/scripts/430565-wanikani-item-info-injector/code/WaniKani%20Item%20Info%20Injector.user.js?version=1276693
  9. // @icon https://www.google.com/s2/favicons?sz=64&domain=markdownguide.org
  10. // @match *://www.wanikani.com/*
  11. // @match *://preview.wanikani.com/*
  12. // @license MIT
  13. // @homepage https://gf.qytechs.cn/en/scripts/468764-wanikani-markdown-editor-notes-2023
  14. // @source https://github.com/patarapolw/wanikani-userscript/blob/master/userscripts/markdown-notes.user.js
  15. // @supportURL https://community.wanikani.com/t/userscript-markdown-editor-notes-2023/62246
  16. // @grant none
  17. // ==/UserScript==
  18.  
  19. // @ts-check
  20. /// <reference path="./types/item-info.d.ts" />
  21. (function () {
  22. 'use strict';
  23.  
  24. const entryClazz = 'wk-markdown-notes';
  25.  
  26. // @ts-ignore
  27. const _Dexie = /** @type {typeof import('dexie').default} */ (Dexie);
  28. /**
  29. * @typedef {{ id: number; state: any; markdown: string }} EntryMarkdown
  30. */
  31.  
  32. class Database extends _Dexie {
  33. /** @type {import('dexie').Table<EntryMarkdown, number>} */
  34. markdown;
  35.  
  36. constructor() {
  37. super(entryClazz);
  38. this.version(8)
  39. .stores({
  40. markdown: 'id,state.characters',
  41. })
  42. .upgrade((tx) => {
  43. const toKeep = [];
  44. tx.table('markdown')
  45. .each((it) => {
  46. if (it.markdown.trim()) {
  47. toKeep.push(it.id);
  48. }
  49. })
  50. .then(() => {
  51. return tx.table('markdown').where('id').noneOf(toKeep).delete();
  52. });
  53. });
  54. }
  55. }
  56.  
  57. const wkMarkdown = {};
  58. Object.assign(window, { wkMarkdown });
  59.  
  60. const db = new Database();
  61. wkMarkdown.db = db;
  62.  
  63. /** @type {HTMLElement} */
  64. let elEditor;
  65. /** @type {import('@toast-ui/editor').Editor} */
  66. let editor;
  67. /** @type {WKItemInfoState} */
  68. let state;
  69. /** @type {EntryMarkdown | undefined} */
  70. let currentEntry;
  71.  
  72. const injector = wkItemInfo
  73. .under('meaning,reading')
  74. .spoiling('nothing')
  75. .append('Markdown Notes', (o) => {
  76. save();
  77. state = o;
  78.  
  79. const onElLoaded = () => {
  80. db.markdown.get(state.id).then((entry) => {
  81. currentEntry = entry;
  82. const md = entry?.markdown;
  83. setTimeout(() => {
  84. if (!editor) return;
  85.  
  86. editor.changePreviewStyle('vertical');
  87. if (md) {
  88. editor.exec('toggle-preview');
  89. }
  90.  
  91. setTimeout(() => {
  92. editor.blur();
  93. });
  94. });
  95.  
  96. if (editor) {
  97. editor.setMarkdown(md || '');
  98. } else {
  99. /** @type {import('@toast-ui/editor').EditorOptions} */
  100. const opts = {
  101. el: elEditor,
  102. initialEditType: 'markdown',
  103. previewStyle: 'vertical',
  104. hideModeSwitch: true,
  105. linkAttributes: {
  106. target: '_blank',
  107. },
  108. toolbarItems: [
  109. ['heading', 'bold', 'italic', 'strike'],
  110. [
  111. {
  112. name: 'big',
  113. tooltip: 'Big',
  114. command: 'big',
  115. text: 'BIG',
  116. className: 'toastui-editor-toolbar-icons',
  117. style: {
  118. backgroundImage: 'none',
  119. fontSize: '0.7em',
  120. fontFamily: 'sans-serif',
  121. },
  122. },
  123. {
  124. name: 'furigana',
  125. tooltip: 'Furigana',
  126. command: 'furigana',
  127. text: 'ふ',
  128. className: 'toastui-editor-toolbar-icons',
  129. style: {
  130. backgroundImage: 'none',
  131. fontSize: '1em',
  132. fontFamily: 'sans-serif',
  133. },
  134. },
  135. {
  136. name: 'subject-type',
  137. tooltip: 'Subject type',
  138. text: '漢',
  139. className: 'toastui-editor-toolbar-icons',
  140. style: {
  141. backgroundImage: 'none',
  142. fontSize: '1em',
  143. fontFamily: 'sans-serif',
  144. },
  145. popup: {
  146. className: 'toastui-editor-popup-add-heading',
  147. body: ((el) => {
  148. el.className = 'toastui-editor-popup-body';
  149.  
  150. const ul = document.createElement('ul');
  151. ul.setAttribute('aria-role', 'menu');
  152. el.append(ul);
  153.  
  154. for (const p of ['rad', 'kan', 'voc', 'read']) {
  155. const li = document.createElement('li');
  156. ul.append(li);
  157. li.setAttribute('aria-role', 'menuitem');
  158.  
  159. switch (p) {
  160. case 'rad':
  161. li.innerText = 'Radical';
  162. break;
  163. case 'kan':
  164. li.innerText = 'Kanji';
  165. break;
  166. case 'voc':
  167. li.innerText = 'Vocabulary';
  168. break;
  169. default:
  170. li.innerText = 'Reading';
  171. }
  172. li.title = li.innerText;
  173.  
  174. li.onclick = () => {
  175. const text = editor.getSelectedText();
  176. if (text) {
  177. editor.replaceSelection(`#${p}#${text}#/${p}#`);
  178. }
  179. };
  180. }
  181.  
  182. return el;
  183. })(document.createElement('div')),
  184. },
  185. },
  186. ],
  187. ['hr', 'quote'],
  188. ['ul', 'ol'],
  189. ['table', 'image', 'link'],
  190. // ['code', 'codeblock'],
  191. ['scrollSync'],
  192. [
  193. {
  194. name: 'preview',
  195. tooltip: 'Preview',
  196. el: ((btn) => {
  197. btn.type = 'button';
  198. btn.className =
  199. 'fa fa-eye toastui-editor-toolbar-icons toggle-preview';
  200. btn.style.backgroundImage = 'none';
  201. btn.style.fontSize = '1em';
  202. btn.style.margin = '-7px -5px';
  203. btn.onclick = () => {
  204. editor.exec('toggle-preview');
  205. };
  206. return btn;
  207. })(document.createElement('button')),
  208. },
  209. {
  210. name: 'save',
  211. tooltip: 'Save/Reload',
  212. command: 'save',
  213. text: '',
  214. className: 'fa fa-save toastui-editor-toolbar-icons',
  215. style: { backgroundImage: 'none', fontSize: '1em' },
  216. },
  217. ],
  218. ],
  219. previewHighlight: false,
  220. customHTMLSanitizer: (s) => {
  221. return s;
  222. },
  223. customHTMLRenderer: {
  224. htmlInline: {
  225. big(node, { entering }) {
  226. const { attrs = {} } = node;
  227. attrs.style = 'font-size: 2em';
  228. return entering
  229. ? {
  230. type: 'openTag',
  231. tagName: 'span',
  232. attributes: attrs,
  233. }
  234. : { type: 'closeTag', tagName: 'span' };
  235. },
  236. small(node, { entering }) {
  237. const { attrs = {} } = node;
  238. attrs.style = 'font-size: 0.7em';
  239. return entering
  240. ? {
  241. type: 'openTag',
  242. tagName: 'span',
  243. attributes: attrs,
  244. }
  245. : { type: 'closeTag', tagName: 'span' };
  246. },
  247. },
  248. text: function (node, ctx) {
  249. /** @type {import('@toast-ui/editor/types/toastmark').HTMLToken[]} */
  250. const out = [];
  251.  
  252. /**
  253. *
  254. * @param {string} tag
  255. * @param {() => void} doInside
  256. */
  257. const addTag = (tag, doInside) => {
  258. out.push({
  259. type: 'openTag',
  260. tagName: tag,
  261. });
  262.  
  263. doInside();
  264.  
  265. out.push({
  266. type: 'closeTag',
  267. tagName: tag,
  268. });
  269. };
  270.  
  271. /**
  272. *
  273. * @param {string} rb
  274. * @param {string} rt
  275. */
  276. const addRubyContent = (rb, rt) => {
  277. addTag('ruby', () => {
  278. out.push({
  279. type: 'text',
  280. content: rb,
  281. });
  282.  
  283. addTag('rp', () => {
  284. out.push({
  285. type: 'text',
  286. content: '(',
  287. });
  288. });
  289.  
  290. addTag('rt', () => {
  291. out.push({
  292. type: 'text',
  293. content: rt,
  294. });
  295. });
  296.  
  297. addTag('rp', () => {
  298. out.push({
  299. type: 'text',
  300. content: ')',
  301. });
  302. });
  303. });
  304. };
  305.  
  306. /** @param {string} s */
  307. const wkFuriganaParser = (s) => {
  308. const segments = s.split(/<(.+?)>\[(.+?)\]/g);
  309. while (segments.length) {
  310. const [raw, rb, rt] = segments.splice(0, 3);
  311. out.push({
  312. type: 'text',
  313. content: raw,
  314. });
  315.  
  316. if (rb) {
  317. addRubyContent(rb, rt);
  318. }
  319. }
  320. };
  321.  
  322. /** @param {string} s */
  323. const mdItFuriganaParser = (s) => {
  324. const segments = s.split(/\[(.+?)\]\{(.+?)\}/g);
  325. while (segments.length) {
  326. const [raw, rb, rt] = segments.splice(0, 3);
  327. wkFuriganaParser(raw);
  328.  
  329. if (rb) {
  330. addTag('ruby', () => {
  331. let rbArr = rb.split('.');
  332. if (rbArr.length === 1) {
  333. rbArr = rb.split('');
  334. }
  335. const rtArr = rt.split('.');
  336.  
  337. if (rbArr.length >= rtArr.length) {
  338. rtArr.map((t, i) => {
  339. if (i < rtArr.length - 1) {
  340. addRubyContent(rbArr[i], t);
  341. } else {
  342. addRubyContent(rbArr.slice(i).join(''), t);
  343. }
  344. });
  345. } else {
  346. addRubyContent(rb, rt);
  347. }
  348. });
  349. }
  350. }
  351. };
  352.  
  353. /** @param {string} s */
  354. const wkMarkParser = (s) => {
  355. const segments = s.split(
  356. /#(rad|kan|voc|read)#(.+?)#\/\1#/g,
  357. );
  358. while (segments.length) {
  359. const [raw, p, text] = segments.splice(0, 3);
  360. mdItFuriganaParser(raw);
  361.  
  362. if (text) {
  363. let className = '';
  364. let title = '';
  365.  
  366. switch (p) {
  367. case 'rad':
  368. className = 'radical-highlight';
  369. title = 'Radical';
  370. break;
  371. case 'kan':
  372. className = 'kanji-highlight';
  373. title = 'Kanji';
  374. break;
  375. case 'voc':
  376. className = 'vocabulary-highlight';
  377. title = 'Vocabulary';
  378. break;
  379. default:
  380. className = 'reading-highlight';
  381. title = 'Reading';
  382. }
  383.  
  384. out.push(
  385. {
  386. type: 'openTag',
  387. tagName: 'span',
  388. classNames: [className],
  389. attributes: { title },
  390. },
  391. {
  392. type: 'text',
  393. content: text,
  394. },
  395. {
  396. type: 'closeTag',
  397. tagName: 'span',
  398. },
  399. );
  400. }
  401. }
  402. };
  403.  
  404. wkMarkParser(node.literal || '');
  405.  
  406. return out;
  407. },
  408. },
  409. autofocus: false,
  410. initialValue: md,
  411. };
  412.  
  413. // @ts-ignore
  414. editor = new toastui.Editor(opts);
  415. wkMarkdown.editor = editor;
  416.  
  417. editor.addCommand('markdown', 'save', () => {
  418. save();
  419. const md = editor.getMarkdown();
  420. // editor.reset();
  421. editor.setMarkdown(md, false);
  422. return true;
  423. });
  424.  
  425. editor.addCommand('markdown', 'toggle-preview', () => {
  426. if (editor.getCurrentPreviewStyle() === 'tab') {
  427. editor.changePreviewStyle('vertical');
  428. } else {
  429. editor.changePreviewStyle('tab');
  430. const elPreviewButton = elEditor.querySelector(
  431. '.toastui-editor-tabs > .tab-item:last-child',
  432. );
  433.  
  434. if (elPreviewButton instanceof HTMLElement) {
  435. elPreviewButton.click();
  436. }
  437. }
  438. return false;
  439. });
  440.  
  441. editor.addCommand('markdown', 'big', () => {
  442. const text = editor.getSelectedText();
  443. if (text) {
  444. editor.replaceSelection(`<big>${text}</big>`);
  445. return true;
  446. }
  447. return false;
  448. });
  449.  
  450. editor.addCommand('markdown', 'furigana', () => {
  451. const text = editor.getSelectedText();
  452. if (text) {
  453. editor.replaceSelection(`[${text}]{ふり}`);
  454. return true;
  455. }
  456. return false;
  457. });
  458.  
  459. editor.on('blur', () => {
  460. save();
  461. });
  462. }
  463. });
  464. };
  465.  
  466. if (!elEditor) {
  467. elEditor = document.createElement('div');
  468. elEditor.id = 'wk-markdown-editor';
  469. elEditor.lang = 'ja';
  470. elEditor.onkeydown = (ev) => {
  471. ev.stopImmediatePropagation();
  472. ev.stopPropagation();
  473. };
  474. }
  475.  
  476. onElLoaded();
  477.  
  478. return elEditor;
  479. });
  480.  
  481. window.addEventListener('willShowNextQuestion', () => {
  482. injector.renew();
  483. });
  484.  
  485. function save(force = true) {
  486. if (editor) {
  487. const markdown = editor.getMarkdown().trim();
  488. if (markdown || currentEntry) force = true;
  489.  
  490. if (force) {
  491. db.markdown.put({ id: state.id, state, markdown }, state.id);
  492. }
  493.  
  494. if (!elEditor) {
  495. editor.destroy();
  496. }
  497. }
  498. }
  499.  
  500. const isClickedClass = 'is-clicked';
  501.  
  502. (function add_css() {
  503. const style = document.createElement('style');
  504.  
  505. const K = '.toastui-editor-defaultUI';
  506.  
  507. style.append(
  508. document.createTextNode(/* css */ `
  509. @import url("https://uicdn.toast.com/editor/latest/toastui-editor.min.css");
  510.  
  511. ${K} {
  512. /* Font list from Jisho.org */
  513. --md-font-family-sans-serif: "Source Han Sans", "源ノ角ゴシック", "Hiragino Sans", "HiraKakuProN-W3", "Hiragino Kaku Gothic ProN W3", "Hiragino Kaku Gothic ProN", "ヒラギノ角ゴ ProN W3", "Noto Sans", "Noto Sans CJK JP", "メイリオ", Meiryo, "游ゴシック", YuGothic, "MS Pゴシック", "MS PGothic", "MS ゴシック", "MS Gothic", sans-serif;
  514. --md-font-family-serif: "HiraMinProN-W3", "Hiragino Mincho ProN W3", "Hiragino Mincho ProN", "ヒラギノ明朝 ProN W3", "游明朝", YuMincho, "HG明朝E", "MS P明朝", "MS PMincho", "MS 明朝", "MS Mincho", serif;
  515. --md-font-family: var(--md-font-family-sans-serif);
  516.  
  517. background-color: #fff;
  518. }
  519.  
  520. ${K} .ProseMirror {
  521. font-family: var(--md-font-family);
  522. }
  523.  
  524. ${K} .toastui-editor-md-preview * {
  525. font-family: var(--md-font-family);
  526. }
  527.  
  528. ${K} .serif {
  529. font-family: var(--md-font-family-serif);
  530. }
  531.  
  532. ${K} .sans,
  533. ${K} .sans-serif {
  534. font-family: var(--md-font-family-sans-serif);
  535. }
  536.  
  537. ${K} .toastui-editor-md-tab-container {
  538. display: none !important;
  539. }
  540.  
  541. ${K} .toastui-editor-toolbar-icons.${isClickedClass} {
  542. background-color: gray;
  543. }
  544. `),
  545. );
  546.  
  547. document.head.append(style);
  548. })();
  549. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址