settings.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* global $ $$ */// dom.js
  2. /* global API */// msg.js
  3. /* exported StyleSettings */
  4. 'use strict';
  5. function StyleSettings(editor) {
  6. let {style} = editor;
  7. const inputs = [
  8. createInput('.style-update-url input', () => style.updateUrl || '',
  9. e => API.styles.config(style.id, 'updateUrl', e.target.value)),
  10. createRadio('.style-prefer-scheme input', () => style.preferScheme || 'none',
  11. e => API.styles.config(style.id, 'preferScheme', e.target.value)),
  12. ...[
  13. ['.style-include', 'inclusions'],
  14. ['.style-exclude', 'exclusions'],
  15. ].map(createArea),
  16. ];
  17. update(style);
  18. editor.on('styleChange', update);
  19. function textToList(text) {
  20. const list = text.split(/\s*\r?\n\s*/g);
  21. return list.filter(Boolean);
  22. }
  23. function update(newStyle, reason) {
  24. if (!newStyle.id) return;
  25. if (reason === 'editSave') return;
  26. style = newStyle;
  27. $('.style-settings').disabled = false;
  28. inputs.forEach(i => i.update());
  29. }
  30. function createArea([parentSel, type]) {
  31. const sel = parentSel + ' textarea';
  32. const el = $(sel);
  33. el.on('input', () => {
  34. const val = el.value;
  35. el.rows = val.match(/^/gm).length + !val.endsWith('\n');
  36. });
  37. return createInput(sel,
  38. () => {
  39. const list = style[type] || [];
  40. const text = list.join('\n');
  41. el.rows = (list.length || 1) + 1;
  42. return text;
  43. },
  44. () => API.styles.config(style.id, type, textToList(el.value))
  45. );
  46. }
  47. function createRadio(selector, getter, setter) {
  48. const els = $$(selector);
  49. for (const el of els) {
  50. el.addEventListener('change', e => {
  51. if (el.checked) {
  52. setter(e);
  53. }
  54. });
  55. }
  56. return {
  57. update() {
  58. for (const el of els) {
  59. if (el.value === getter()) {
  60. el.checked = true;
  61. }
  62. }
  63. },
  64. };
  65. }
  66. function createInput(selector, getter, setter) {
  67. const el = $(selector);
  68. el.addEventListener('change', setter);
  69. return {
  70. update() {
  71. el.value = getter();
  72. },
  73. };
  74. }
  75. }