KameSame Open Framework - Settings module

Settings module for KameSame Open Framework

当前为 2022-10-06 提交的版本,查看 最新版本

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/451521/1101578/KameSame%20Open%20Framework%20-%20Settings%20module.js

  1. // ==UserScript==
  2. // @name KameSame Open Framework - Settings module
  3. // @namespace timberpile
  4. // @description Settings module for KameSame Open Framework
  5. // @version 0.7
  6. // @copyright 2022+, Robin Findley, Timberpile
  7. // @license MIT; http://opensource.org/licenses/MIT
  8. // ==/UserScript==
  9. (async function (global) {
  10. // const publish_context = false; // Set to 'true' to make context public.
  11. const ksof = global.ksof;
  12. const background_funcs = () => {
  13. return {
  14. open: () => {
  15. const anchor = install_anchor();
  16. let bkgd = anchor.find('> #ksofs_bkgd');
  17. if (bkgd.length === 0) {
  18. bkgd = $('<div id="ksofs_bkgd" refcnt="0"></div>');
  19. anchor.prepend(bkgd);
  20. }
  21. const refcnt = Number(bkgd.attr('refcnt'));
  22. bkgd.attr('refcnt', refcnt + 1);
  23. },
  24. close: () => {
  25. const bkgd = $('#ksof_ds > #ksofs_bkgd');
  26. if (bkgd.length === 0)
  27. return;
  28. const refcnt = Number(bkgd.attr('refcnt'));
  29. if (refcnt <= 0)
  30. return;
  31. bkgd.attr('refcnt', refcnt - 1);
  32. }
  33. };
  34. };
  35. //########################################################################
  36. //------------------------------
  37. // Constructor
  38. //------------------------------
  39. class Settings {
  40. constructor(config) {
  41. // if (!config.content) config.content = config.settings;
  42. // if (publish_context) this.context = context;
  43. this.cfg = config;
  44. this.config_list = {};
  45. this.open_dialog = $();
  46. this.background = background_funcs();
  47. }
  48. //------------------------------
  49. // Open the settings dialog.
  50. //------------------------------
  51. static save(context) {
  52. if (!ksof.settings)
  53. throw new Error('ksof.settings not defined');
  54. if (!ksof.Settings)
  55. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  56. const script_id = ((typeof context === 'string') ? context : context.cfg.script_id);
  57. const settings = ksof.settings[script_id];
  58. if (!settings)
  59. return Promise.resolve('');
  60. return ksof.file_cache.save('ksof.settings.' + script_id, settings);
  61. }
  62. save() {
  63. return Settings.save(this);
  64. }
  65. //------------------------------
  66. // Open the settings dialog.
  67. //------------------------------
  68. static async load(context, defaults) {
  69. const script_id = ((typeof context === 'string') ? context : context.cfg.script_id);
  70. try {
  71. const settings = await ksof.file_cache.load('ksof.settings.' + script_id);
  72. return finish(settings);
  73. }
  74. catch (error) {
  75. return finish.call(null, {});
  76. }
  77. function finish(settings) {
  78. if (!ksof.settings)
  79. throw new Error('ksof.settings not defined');
  80. if (!ksof.Settings)
  81. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  82. if (defaults)
  83. ksof.settings[script_id] = deep_merge(defaults, settings);
  84. else
  85. ksof.settings[script_id] = settings;
  86. return ksof.settings[script_id];
  87. }
  88. }
  89. load(defaults) {
  90. return Settings.load(this, defaults);
  91. }
  92. //------------------------------
  93. // Save button handler.
  94. //------------------------------
  95. save_btn() {
  96. if (!ksof.settings)
  97. throw new Error('ksof.settings not defined');
  98. if (!ksof.Settings)
  99. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  100. const script_id = this.cfg.script_id;
  101. const settings = ksof.settings[script_id];
  102. if (settings) {
  103. const active_tabs = this.open_dialog.find('.ui-tabs-active').toArray().map(function (tab) { return '#' + tab.attributes.getNamedItem('id')?.value || ''; });
  104. if (active_tabs.length > 0)
  105. settings.ksofs_active_tabs = active_tabs;
  106. }
  107. if (this.cfg.autosave === undefined || this.cfg.autosave === true)
  108. this.save();
  109. if (typeof this.cfg.on_save === 'function')
  110. this.cfg.on_save(ksof.settings[this.cfg.script_id]);
  111. // ksof.trigger('ksof.settings.save'); // TODO what should this do?
  112. this.keep_settings = true;
  113. this.open_dialog.dialog('close');
  114. }
  115. //------------------------------
  116. // Cancel button handler.
  117. //------------------------------
  118. cancel_btn() {
  119. if (!ksof.settings)
  120. throw new Error('ksof.settings not defined');
  121. if (!ksof.Settings)
  122. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  123. this.open_dialog.dialog('close');
  124. if (typeof this.cfg.on_cancel === 'function')
  125. this.cfg.on_cancel(ksof.settings[this.cfg.script_id]);
  126. }
  127. //------------------------------
  128. // Open the settings dialog.
  129. //------------------------------
  130. open() {
  131. if (!ksof.settings)
  132. throw new Error('ksof.settings not defined');
  133. if (!ksof.Settings)
  134. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  135. if (!ready)
  136. return;
  137. if (this.open_dialog.length > 0)
  138. return;
  139. install_anchor();
  140. if (this.cfg.background !== false)
  141. this.background.open();
  142. this.open_dialog = $('<div id="ksofs_' + this.cfg.script_id + '" class="ksof_settings" style="display:none;"></div>');
  143. this.open_dialog.html(config_to_html(this));
  144. const resize = (event, ui) => {
  145. const is_narrow = this.open_dialog.hasClass('narrow');
  146. if (is_narrow && ui.size.width >= 510) {
  147. this.open_dialog.removeClass('narrow');
  148. }
  149. else if (!is_narrow && ui.size.width < 490) {
  150. this.open_dialog.addClass('narrow');
  151. }
  152. };
  153. const tab_activated = () => {
  154. const wrapper = $(this.open_dialog.dialog('widget'));
  155. if ((wrapper.outerHeight() || 0) + wrapper.position().top > document.body.clientHeight) {
  156. this.open_dialog.dialog('option', 'maxHeight', document.body.clientHeight);
  157. }
  158. };
  159. let width = 500;
  160. if (window.innerWidth < 510) {
  161. width = 280;
  162. this.open_dialog.addClass('narrow');
  163. }
  164. this.open_dialog.dialog({
  165. title: this.cfg.title,
  166. buttons: [
  167. { text: 'Save', click: this.save_btn.bind(this) },
  168. { text: 'Cancel', click: this.cancel_btn.bind(this) }
  169. ],
  170. width: width,
  171. maxHeight: document.body.clientHeight,
  172. modal: false,
  173. autoOpen: false,
  174. appendTo: '#ksof_ds',
  175. resize: resize.bind(this),
  176. close: close.bind(this)
  177. });
  178. $(this.open_dialog.dialog('widget')).css('position', 'fixed');
  179. this.open_dialog.parent().addClass('ksof_settings_dialog');
  180. $('.ksof_stabs').tabs({ activate: tab_activated.bind(null) });
  181. const settings = ksof.settings[this.cfg.script_id];
  182. if (settings && settings.ksofs_active_tabs instanceof Array) {
  183. const active_tabs = settings.ksofs_active_tabs;
  184. for (let tab_idx = 0; tab_idx < active_tabs.length; tab_idx++) {
  185. const tab = $(active_tabs[tab_idx]);
  186. tab.closest('.ui-tabs').tabs({ active: tab.index() });
  187. }
  188. }
  189. const toggle_multi = (e) => {
  190. if (e.button != 0)
  191. return true;
  192. const multi = $(e.currentTarget);
  193. const scroll = e.currentTarget.scrollTop;
  194. e.target.selected = !e.target.selected;
  195. setTimeout(function () {
  196. e.currentTarget.scrollTop = scroll;
  197. multi.focus();
  198. }, 0);
  199. return this.setting_changed(e);
  200. };
  201. const setting_button_clicked = (e) => {
  202. const name = e.target.attributes.name.value;
  203. const item = this.config_list[name];
  204. if (typeof item.on_click === 'function')
  205. item.on_click.call(e, name, item, this.setting_changed.bind(this, e));
  206. };
  207. this.open_dialog.dialog('open');
  208. const dialog_elem = $('#ksofs_' + this.cfg.script_id);
  209. dialog_elem.find('.setting[multiple]').on('mousedown', toggle_multi.bind(null));
  210. dialog_elem.find('.setting').on('change', this.setting_changed.bind(null));
  211. dialog_elem.find('form').on('submit', function () { return false; });
  212. dialog_elem.find('button.setting').on('click', setting_button_clicked.bind(null));
  213. if (typeof this.cfg.pre_open === 'function')
  214. this.cfg.pre_open(this.open_dialog);
  215. this.reversions = deep_merge({}, ksof.settings[this.cfg.script_id]);
  216. this.refresh();
  217. //============
  218. }
  219. //------------------------------
  220. // Handler for live settings changes. Handles built-in validation and user callbacks.
  221. //------------------------------
  222. setting_changed(event) {
  223. if (!ksof.settings)
  224. throw new Error('ksof.settings not defined');
  225. if (!ksof.Settings)
  226. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  227. const elem = $(event.currentTarget);
  228. const name = elem.attr('name');
  229. if (!name)
  230. return false;
  231. const _item = this.config_list[name];
  232. // Extract the value
  233. let value;
  234. if (_item.type == 'dropdown') {
  235. value = elem.find(':checked').attr('name');
  236. }
  237. else if (_item.type == 'list') {
  238. const item = _item;
  239. if (item.multi === true) {
  240. value = {};
  241. elem.find('option').each(function (i, e) {
  242. const opt_name = e.getAttribute('name') || '#' + e.index;
  243. value[opt_name] = e.selected;
  244. });
  245. }
  246. else {
  247. value = elem.find(':checked').attr('name');
  248. }
  249. }
  250. else if (_item.type == 'input') {
  251. const item = _item;
  252. if (item.subtype === 'number') {
  253. value = Number(elem.val());
  254. }
  255. }
  256. else if (_item.type == 'checkbox') {
  257. value = elem.is(':checked');
  258. }
  259. else if (_item.type == 'number') {
  260. value = Number(elem.val());
  261. }
  262. else {
  263. value = elem.val();
  264. }
  265. // Validation
  266. let valid = { valid: true, msg: '' };
  267. {
  268. const item = _item;
  269. if (typeof item.validate === 'function')
  270. valid = item.validate.call(event.target, value, item);
  271. if (typeof valid === 'boolean')
  272. valid = { valid: valid, msg: '' };
  273. else if (typeof valid === 'string')
  274. valid = { valid: false, msg: valid };
  275. else if (valid === undefined)
  276. valid = { valid: true, msg: '' };
  277. }
  278. if (_item.type == 'number') {
  279. const item = _item;
  280. if (item.min && Number(value) < item.min) {
  281. valid.valid = false;
  282. if (valid.msg.length === 0) {
  283. if (typeof item.max === 'number')
  284. valid.msg = 'Must be between ' + item.min + ' and ' + item.max;
  285. else
  286. valid.msg = 'Must be ' + item.min + ' or higher';
  287. }
  288. }
  289. else if (item.max && Number(value) > item.max) {
  290. valid.valid = false;
  291. if (valid.msg.length === 0) {
  292. if (typeof item.min === 'number')
  293. valid.msg = 'Must be between ' + item.min + ' and ' + item.max;
  294. else
  295. valid.msg = 'Must be ' + item.max + ' or lower';
  296. }
  297. }
  298. }
  299. else if (_item.type == 'text') {
  300. const item = _item;
  301. if (item.match !== undefined && value.match(item.match) === null) {
  302. valid.valid = false;
  303. if (valid.msg.length === 0)
  304. // valid.msg = item.error_msg || 'Invalid value';
  305. valid.msg = 'Invalid value';
  306. }
  307. }
  308. // Style for valid/invalid
  309. const parent = elem.closest('.right');
  310. parent.find('.note').remove();
  311. if (typeof valid.msg === 'string' && valid.msg.length > 0)
  312. parent.append('<div class="note' + (valid.valid ? '' : ' error') + '">' + valid.msg + '</div>');
  313. if (!valid.valid) {
  314. elem.addClass('invalid');
  315. }
  316. else {
  317. elem.removeClass('invalid');
  318. }
  319. const script_id = this.cfg.script_id;
  320. const settings = ksof.settings[script_id];
  321. if (valid.valid) {
  322. // if (item.no_save !== true) set_value(context, settings, name, value);
  323. set_value(this, settings, name, value);
  324. const item = _item;
  325. if (typeof item.on_change === 'function')
  326. item.on_change.call(event.target, name, value, item);
  327. if (typeof this.cfg.on_change === 'function')
  328. this.cfg.on_change.call(event.target, name, value, item);
  329. // if (item.refresh_on_change === true) this.refresh();
  330. return true;
  331. }
  332. return false;
  333. }
  334. //------------------------------
  335. // Close and destroy the dialog.
  336. //------------------------------
  337. close(keep_settings) {
  338. if (!ksof.settings)
  339. throw new Error('ksof.settings not defined');
  340. if (!ksof.Settings)
  341. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  342. console.log(1);
  343. if (!this.keep_settings && keep_settings !== true) {
  344. // Revert settings
  345. ksof.settings[this.cfg.script_id] = deep_merge({}, this.reversions || {});
  346. delete this.reversions;
  347. }
  348. console.log(2);
  349. delete this.keep_settings;
  350. console.log(3);
  351. this.open_dialog.dialog('destroy');
  352. console.log(4);
  353. this.open_dialog = $();
  354. console.log(5);
  355. if (this.cfg.background !== false)
  356. this.background.close();
  357. console.log(6);
  358. if (typeof this.cfg.on_close === 'function')
  359. this.cfg.on_close(ksof.settings[this.cfg.script_id]);
  360. console.log(7);
  361. }
  362. //------------------------------
  363. // Update the dialog to reflect changed settings.
  364. //------------------------------
  365. refresh() {
  366. if (!ksof.settings)
  367. throw new Error('ksof.settings not defined');
  368. if (!ksof.Settings)
  369. throw new Error('ksof.Settings not defined'); // this line is used to tell the compiler that settings and Settigns definitely are defined in the following lines
  370. const script_id = this.cfg.script_id;
  371. const settings = ksof.settings[script_id];
  372. for (const name in this.config_list) {
  373. const elem = this.open_dialog.find('#' + script_id + '_' + name);
  374. const _config = this.config_list[name];
  375. const value = get_value(this, settings, name);
  376. if (_config.type == 'dropdown') {
  377. elem.find('option[name="' + value + '"]').prop('selected', true);
  378. }
  379. else if (_config.type == 'list') {
  380. const config = _config;
  381. if (config.multi === true) {
  382. elem.find('option').each(function (i, e) {
  383. const opt_name = e.getAttribute('name') || '#' + e.index;
  384. e.selected = value[opt_name];
  385. });
  386. }
  387. else {
  388. elem.find('option[name="' + value + '"]').prop('selected', true);
  389. }
  390. }
  391. else if (_config.type == 'checkbox') {
  392. elem.prop('checked', value);
  393. }
  394. else {
  395. elem.val(value);
  396. }
  397. }
  398. if (typeof this.cfg.on_refresh === 'function')
  399. this.cfg.on_refresh(ksof.settings[this.cfg.script_id]);
  400. }
  401. }
  402. // TODO find better name than SettingsClass. SettingsObj?
  403. function createSettingsObj() {
  404. const settings_obj = (config) => {
  405. return new Settings(config);
  406. };
  407. settings_obj.save = (context) => { return Settings.save(context); };
  408. settings_obj.load = (context, defaults) => { return Settings.load(context, defaults); };
  409. settings_obj.background = background_funcs();
  410. return settings_obj;
  411. }
  412. ksof.Settings = createSettingsObj();
  413. ksof.settings = {};
  414. //########################################################################
  415. let ready = false;
  416. //========================================================================
  417. function deep_merge(...objects) {
  418. const merged = {};
  419. function recursive_merge(dest, src) {
  420. for (const prop in src) {
  421. if (typeof src[prop] === 'object' && src[prop] !== null) {
  422. const srcProp = src[prop];
  423. if (Array.isArray(srcProp)) {
  424. dest[prop] = srcProp.slice();
  425. }
  426. else {
  427. dest[prop] = dest[prop] || {};
  428. recursive_merge(dest[prop], srcProp);
  429. }
  430. }
  431. else {
  432. dest[prop] = src[prop];
  433. }
  434. }
  435. return dest;
  436. }
  437. for (const obj in objects) {
  438. recursive_merge(merged, objects[obj]);
  439. }
  440. return merged;
  441. }
  442. //------------------------------
  443. // Convert a config object to html dialog.
  444. //------------------------------
  445. /* eslint-disable no-case-declarations */
  446. function config_to_html(context) {
  447. context.config_list = {};
  448. if (!ksof.settings) {
  449. return '';
  450. }
  451. let base = ksof.settings[context.cfg.script_id];
  452. if (base === undefined)
  453. ksof.settings[context.cfg.script_id] = base = {};
  454. let html = '';
  455. const child_passback = {};
  456. const id = context.cfg.script_id + '_dialog';
  457. for (const name in context.cfg.content) {
  458. html += parse_item(name, context.cfg.content[name], child_passback);
  459. }
  460. if (child_passback.tabs && child_passback.pages)
  461. html = assemble_pages(id, child_passback.tabs, child_passback.pages) + html;
  462. return '<form>' + html + '</form>';
  463. //============
  464. function parse_item(name, _item, passback) {
  465. if (typeof _item.type !== 'string')
  466. return '';
  467. const id = context.cfg.script_id + '_' + name;
  468. let cname, html = '', child_passback, non_page = '';
  469. const _type = _item.type;
  470. if (_type == 'tabset') {
  471. const item = _item;
  472. child_passback = {};
  473. for (cname in item.content) {
  474. non_page += parse_item(cname, item.content[cname], child_passback);
  475. }
  476. if (child_passback.tabs && child_passback.pages) {
  477. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  478. }
  479. }
  480. else if (_type == 'page') {
  481. const item = _item;
  482. if (typeof item.content !== 'object')
  483. item.content = {};
  484. if (!passback.tabs) {
  485. passback.tabs = [];
  486. }
  487. if (!passback.pages) {
  488. passback.pages = [];
  489. }
  490. passback.tabs.push('<li id="' + id + '_tab"' + to_title(item.hover_tip) + '><a href="#' + id + '">' + item.label + '</a></li>');
  491. child_passback = {};
  492. for (cname in item.content)
  493. non_page += parse_item(cname, item.content[cname], child_passback);
  494. if (child_passback.tabs && child_passback.pages)
  495. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  496. passback.pages.push('<div id="' + id + '">' + html + non_page + '</div>');
  497. passback.is_page = true;
  498. html = '';
  499. }
  500. else if (_type == 'group') {
  501. const item = _item;
  502. if (typeof item.content !== 'object')
  503. item.content = {};
  504. child_passback = {};
  505. for (cname in item.content)
  506. non_page += parse_item(cname, item.content[cname], child_passback);
  507. if (child_passback.tabs && child_passback.pages)
  508. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  509. html = '<fieldset id="' + id + '" class="ksof_group"><legend>' + item.label + '</legend>' + html + non_page + '</fieldset>';
  510. }
  511. else if (_type == 'dropdown') {
  512. const item = _item;
  513. context.config_list[name] = item;
  514. let value = get_value(context, base, name);
  515. if (value === undefined) {
  516. if (item.default !== undefined) {
  517. value = item.default;
  518. }
  519. else {
  520. value = Object.keys(item.content)[0];
  521. }
  522. set_value(context, base, name, value);
  523. }
  524. html = `<select id="${id}" name="${name}" class="setting"${to_title(item.hover_tip)}>`;
  525. for (cname in item.content)
  526. html += '<option name="' + cname + '">' + escape_text(item.content[cname]) + '</option>';
  527. html += '</select>';
  528. html = make_label(item) + wrap_right(html);
  529. html = wrap_row(html, item.full_width, item.hover_tip);
  530. }
  531. else if (_type == 'list') {
  532. const item = _item;
  533. context.config_list[name] = item;
  534. let value = get_value(context, base, name);
  535. if (value === undefined) {
  536. if (item.default !== undefined) {
  537. value = item.default;
  538. }
  539. else {
  540. if (item.multi === true) {
  541. value = {};
  542. Object.keys(item.content).forEach(function (key) {
  543. value[key] = false;
  544. });
  545. }
  546. else {
  547. value = Object.keys(item.content)[0];
  548. }
  549. }
  550. set_value(context, base, name, value);
  551. }
  552. let attribs = ' size="' + (item.size || Object.keys(item.content).length || 4) + '"';
  553. if (item.multi === true)
  554. attribs += ' multiple';
  555. html = `<select id="${id}" name="${name}" class="setting list"${attribs}${to_title(item.hover_tip)}>`;
  556. for (cname in item.content)
  557. html += '<option name="' + cname + '">' + escape_text(item.content[cname]) + '</option>';
  558. html += '</select>';
  559. html = make_label(item) + wrap_right(html);
  560. html = wrap_row(html, item.full_width, item.hover_tip);
  561. }
  562. else if (_type == 'checkbox') {
  563. const item = _item;
  564. context.config_list[name] = item;
  565. html = make_label(item);
  566. let value = get_value(context, base, name);
  567. if (value === undefined) {
  568. value = (item.default || false);
  569. set_value(context, base, name, value);
  570. }
  571. html += wrap_right('<input id="' + id + '" class="setting" type="checkbox" name="' + name + '">');
  572. html = wrap_row(html, item.full_width, item.hover_tip);
  573. }
  574. else if (_type == 'input') {
  575. const item = _item;
  576. const itype = item.subtype || 'text';
  577. context.config_list[name] = item;
  578. html += make_label(item);
  579. let value = get_value(context, base, name);
  580. if (value === undefined) {
  581. const is_number = (item.subtype === 'number');
  582. value = (item.default || (is_number ? 0 : ''));
  583. set_value(context, base, name, value);
  584. }
  585. html += wrap_right(`<input id="${id}" class="setting" type="${itype}" name="${name}"${(item.placeholder ? ' placeholder="' + escape_attr(item.placeholder) + '"' : '')}>`);
  586. html = wrap_row(html, item.full_width, item.hover_tip);
  587. }
  588. else if (_type == 'number') {
  589. const item = _item;
  590. const itype = item.type;
  591. context.config_list[name] = item;
  592. html += make_label(item);
  593. let value = get_value(context, base, name);
  594. if (value === undefined) {
  595. const is_number = (item.type === 'number');
  596. value = (item.default || (is_number ? 0 : ''));
  597. set_value(context, base, name, value);
  598. }
  599. html += wrap_right(`<input id="${id}" class="setting" type="${itype}" name="${name}"${(item.placeholder ? ' placeholder="' + escape_attr(item.placeholder) + '"' : '')}>`);
  600. html = wrap_row(html, item.full_width, item.hover_tip);
  601. }
  602. else if (_type == 'text') {
  603. const item = _item;
  604. const itype = item.type;
  605. context.config_list[name] = item;
  606. html += make_label(item);
  607. let value = get_value(context, base, name);
  608. if (value === undefined) {
  609. value = (item.default || '');
  610. set_value(context, base, name, value);
  611. }
  612. html += wrap_right(`<input id="${id}" class="setting" type="${itype}" name="${name}"${(item.placeholder ? ' placeholder="' + escape_attr(item.placeholder) + '"' : '')}>`);
  613. html = wrap_row(html, item.full_width, item.hover_tip);
  614. }
  615. else if (_type == 'color') {
  616. const item = _item;
  617. context.config_list[name] = item;
  618. html += make_label(item);
  619. let value = get_value(context, base, name);
  620. if (value === undefined) {
  621. value = (item.default || '#000000');
  622. set_value(context, base, name, value);
  623. }
  624. html += wrap_right('<input id="' + id + '" class="setting" type="color" name="' + name + '">');
  625. html = wrap_row(html, item.full_width, item.hover_tip);
  626. }
  627. else if (_type == 'button') {
  628. const item = _item;
  629. context.config_list[name] = item;
  630. html += make_label(item);
  631. const text = escape_text(item.text || 'Click');
  632. html += wrap_right('<button type="button" class="setting" name="' + name + '">' + text + '</button>');
  633. html = wrap_row(html, item.full_width, item.hover_tip);
  634. }
  635. else if (_type == 'divider') {
  636. html += '<hr>';
  637. }
  638. else if (_type == 'section') {
  639. const item = _item;
  640. html += '<section>' + (item.label || '') + '</section>';
  641. }
  642. else if (_type == 'html') {
  643. const item = _item;
  644. html += make_label(item);
  645. html += item.html;
  646. switch (item.wrapper) {
  647. case 'row':
  648. html = wrap_row(html, undefined, item.hover_tip);
  649. break;
  650. case 'left':
  651. html = wrap_left(html);
  652. break;
  653. case 'right':
  654. html = wrap_right(html);
  655. break;
  656. }
  657. }
  658. return html;
  659. function make_label(item) {
  660. if (typeof item.label !== 'string')
  661. return '';
  662. return wrap_left('<label for="' + id + '">' + item.label + '</label>');
  663. }
  664. }
  665. /* eslint-enable no-case-declarations */
  666. //============
  667. function assemble_pages(id, tabs, pages) { return '<div id="' + id + '" class="ksof_stabs"><ul>' + tabs.join('') + '</ul>' + pages.join('') + '</div>'; }
  668. function wrap_row(html, full, hover_tip) { return '<div class="row' + (full ? ' full' : '') + '"' + to_title(hover_tip) + '>' + html + '</div>'; }
  669. function wrap_left(html) { return '<div class="left">' + html + '</div>'; }
  670. function wrap_right(html) { return '<div class="right">' + html + '</div>'; }
  671. function escape_text(text) {
  672. return text.replace(/[<>]/g, (ch) => {
  673. if (ch == '<')
  674. return '&lt';
  675. if (ch == '>')
  676. return '&gt';
  677. return '';
  678. });
  679. }
  680. function escape_attr(text) { return text.replace(/"/g, '&quot;'); }
  681. function to_title(tip) { if (!tip)
  682. return ''; return ' title="' + tip.replace(/"/g, '&quot;') + '"'; }
  683. }
  684. function get_value(context, base, name) {
  685. const item = context.config_list[name];
  686. const evaluate = (item.path !== undefined);
  687. const path = (item.path || name);
  688. try {
  689. if (!evaluate)
  690. return base[path];
  691. return eval(path.replace(/@/g, 'base.'));
  692. }
  693. catch (e) {
  694. return;
  695. }
  696. }
  697. function set_value(context, base, name, value) {
  698. const item = context.config_list[name];
  699. const evaluate = (item.path !== undefined);
  700. const path = (item.path || name);
  701. try {
  702. if (!evaluate)
  703. return base[path] = value;
  704. let depth = 0;
  705. let new_path = '';
  706. let param = '';
  707. let c;
  708. for (let idx = 0; idx < path.length; idx++) {
  709. c = path[idx];
  710. if (c === '[') {
  711. if (depth++ === 0) {
  712. new_path += '[';
  713. param = '';
  714. }
  715. else {
  716. param += '[';
  717. }
  718. }
  719. else if (c === ']') {
  720. if (--depth === 0) {
  721. new_path += JSON.stringify(eval(param)) + ']';
  722. }
  723. else {
  724. param += ']';
  725. }
  726. }
  727. else {
  728. if (c === '@')
  729. c = 'base.';
  730. if (depth === 0)
  731. new_path += c;
  732. else
  733. param += c;
  734. }
  735. }
  736. eval(new_path + '=value');
  737. }
  738. catch (e) {
  739. return;
  740. }
  741. }
  742. function install_anchor() {
  743. let anchor = $('#ksof_ds');
  744. if (anchor.length === 0) {
  745. anchor = $('<div id="ksof_ds"></div></div>');
  746. $('body').prepend(anchor);
  747. $('#ksof_ds').on('keydown keyup keypress', '.ksof_settings_dialog', function (e) {
  748. // Stop keys from bubbling beyond the background overlay.
  749. e.stopPropagation();
  750. });
  751. }
  752. return anchor;
  753. }
  754. //------------------------------
  755. // Load jquery UI and the appropriate CSS based on location.
  756. //------------------------------
  757. const css_url = ksof.support_files['jqui_ksmain.css'];
  758. ksof.include('Jquery');
  759. await ksof.ready('document, Jquery');
  760. await Promise.all([
  761. ksof.load_script(ksof.support_files['jquery_ui.js'], true /* cache */),
  762. ksof.load_css(css_url, true /* cache */)
  763. ]);
  764. ready = true;
  765. // Workaround... https://community.wanikani.com/t/19984/55
  766. try {
  767. const temp = $.fn;
  768. delete temp.autocomplete;
  769. }
  770. catch (e) {
  771. // do nothing
  772. }
  773. // Notify listeners that we are ready.
  774. // Delay guarantees include() callbacks are called before ready() callbacks.
  775. setTimeout(function () { ksof.set_state('ksof.Settings', 'ready'); }, 0);
  776. })(this);