KameSame Open Framework - Settings module

Settings module for KameSame Open Framework

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

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