KameSame Open Framework - Settings module

Settings module for KameSame Open Framework

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/451521/1101658/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.15
  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: (e) => { this.close(false); }
  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. console.log(e);
  193. const multi = $(e.currentTarget);
  194. const scroll = e.currentTarget.scrollTop;
  195. e.target.selected = !e.target.selected;
  196. setTimeout(function () {
  197. e.currentTarget.scrollTop = scroll;
  198. multi.focus(); // TODO what should this normally do??
  199. }, 0);
  200. return this.setting_changed(e);
  201. };
  202. const setting_button_clicked = (e) => {
  203. const name = e.target.attributes.name.value;
  204. const item = this.config_list[name];
  205. if (typeof item.on_click === 'function')
  206. item.on_click.call(e, name, item, this.setting_changed.bind(this, e));
  207. };
  208. this.open_dialog.dialog('open');
  209. // const dialog_elem = $('#ksofs_'+this.cfg.script_id);
  210. // dialog_elem.find('.setting[multiple]').on('mousedown', toggle_multi.bind(this));
  211. // dialog_elem.find('.setting').on('change', this.setting_changed.bind(this));
  212. // dialog_elem.find('form').on('submit', function(){return false;});
  213. // dialog_elem.find('button.setting').on('click', setting_button_clicked.bind(this));
  214. this.open_dialog.find('.setting[multiple]').on('mousedown', toggle_multi.bind(this));
  215. this.open_dialog.find('.setting').on('change', this.setting_changed.bind(this));
  216. this.open_dialog.find('form').on('submit', function () { return false; });
  217. this.open_dialog.find('button.setting').on('click', setting_button_clicked.bind(this));
  218. if (typeof this.cfg.pre_open === 'function')
  219. this.cfg.pre_open(this.open_dialog);
  220. this.reversions = deep_merge({}, ksof.settings[this.cfg.script_id]);
  221. this.refresh();
  222. //============
  223. }
  224. //------------------------------
  225. // Handler for live settings changes. Handles built-in validation and user callbacks.
  226. //------------------------------
  227. setting_changed(event) {
  228. if (!ksof.settings)
  229. throw new Error('ksof.settings not defined');
  230. if (!ksof.Settings)
  231. 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
  232. const elem = $(event.currentTarget);
  233. const name = elem.attr('name');
  234. if (!name)
  235. return false;
  236. const _item = this.config_list[name];
  237. // Extract the value
  238. let value;
  239. if (_item.type == 'dropdown') {
  240. value = elem.find(':checked').attr('name');
  241. }
  242. else if (_item.type == 'list') {
  243. const item = _item;
  244. if (item.multi === true) {
  245. value = {};
  246. elem.find('option').each(function (i, e) {
  247. const opt_name = e.getAttribute('name') || '#' + e.index;
  248. value[opt_name] = e.selected;
  249. });
  250. }
  251. else {
  252. value = elem.find(':checked').attr('name');
  253. }
  254. }
  255. else if (_item.type == 'input') {
  256. const item = _item;
  257. if (item.subtype === 'number') {
  258. value = Number(elem.val());
  259. }
  260. }
  261. else if (_item.type == 'checkbox') {
  262. value = elem.is(':checked');
  263. }
  264. else if (_item.type == 'number') {
  265. value = Number(elem.val());
  266. }
  267. else {
  268. value = elem.val();
  269. }
  270. // Validation
  271. let valid = { valid: true, msg: '' };
  272. {
  273. const item = _item;
  274. if (typeof item.validate === 'function')
  275. valid = item.validate.call(event.target, value, item);
  276. if (typeof valid === 'boolean')
  277. valid = { valid: valid, msg: '' };
  278. else if (typeof valid === 'string')
  279. valid = { valid: false, msg: valid };
  280. else if (valid === undefined)
  281. valid = { valid: true, msg: '' };
  282. }
  283. if (_item.type == 'number') {
  284. const item = _item;
  285. if (item.min && Number(value) < item.min) {
  286. valid.valid = false;
  287. if (valid.msg.length === 0) {
  288. if (typeof item.max === 'number')
  289. valid.msg = 'Must be between ' + item.min + ' and ' + item.max;
  290. else
  291. valid.msg = 'Must be ' + item.min + ' or higher';
  292. }
  293. }
  294. else if (item.max && Number(value) > item.max) {
  295. valid.valid = false;
  296. if (valid.msg.length === 0) {
  297. if (typeof item.min === 'number')
  298. valid.msg = 'Must be between ' + item.min + ' and ' + item.max;
  299. else
  300. valid.msg = 'Must be ' + item.max + ' or lower';
  301. }
  302. }
  303. }
  304. else if (_item.type == 'text') {
  305. const item = _item;
  306. if (item.match !== undefined && value.match(item.match) === null) {
  307. valid.valid = false;
  308. if (valid.msg.length === 0)
  309. // valid.msg = item.error_msg || 'Invalid value';
  310. valid.msg = 'Invalid value';
  311. }
  312. }
  313. // Style for valid/invalid
  314. const parent = elem.closest('.right');
  315. parent.find('.note').remove();
  316. if (typeof valid.msg === 'string' && valid.msg.length > 0)
  317. parent.append('<div class="note' + (valid.valid ? '' : ' error') + '">' + valid.msg + '</div>');
  318. if (!valid.valid) {
  319. elem.addClass('invalid');
  320. }
  321. else {
  322. elem.removeClass('invalid');
  323. }
  324. const script_id = this.cfg.script_id;
  325. const settings = ksof.settings[script_id];
  326. if (valid.valid) {
  327. // if (item.no_save !== true) set_value(context, settings, name, value);
  328. set_value(this, settings, name, value);
  329. const item = _item;
  330. if (typeof item.on_change === 'function')
  331. item.on_change.call(event.target, name, value, item);
  332. if (typeof this.cfg.on_change === 'function')
  333. this.cfg.on_change.call(event.target, name, value, item);
  334. // if (item.refresh_on_change === true) this.refresh();
  335. // return true
  336. }
  337. return false;
  338. }
  339. //------------------------------
  340. // Close and destroy the dialog.
  341. //------------------------------
  342. close(keep_settings) {
  343. if (!ksof.settings)
  344. throw new Error('ksof.settings not defined');
  345. if (!ksof.Settings)
  346. 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
  347. if (!this.keep_settings && keep_settings !== true) {
  348. // Revert settings
  349. ksof.settings[this.cfg.script_id] = deep_merge({}, this.reversions || {});
  350. delete this.reversions;
  351. }
  352. delete this.keep_settings;
  353. this.open_dialog.dialog('destroy');
  354. this.open_dialog = $();
  355. if (this.cfg.background !== false)
  356. this.background.close();
  357. if (typeof this.cfg.on_close === 'function')
  358. this.cfg.on_close(ksof.settings[this.cfg.script_id]);
  359. }
  360. //------------------------------
  361. // Update the dialog to reflect changed settings.
  362. //------------------------------
  363. refresh() {
  364. if (!ksof.settings)
  365. throw new Error('ksof.settings not defined');
  366. if (!ksof.Settings)
  367. 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
  368. const script_id = this.cfg.script_id;
  369. const settings = ksof.settings[script_id];
  370. for (const name in this.config_list) {
  371. const elem = this.open_dialog.find('#' + script_id + '_' + name);
  372. const _config = this.config_list[name];
  373. const value = get_value(this, settings, name);
  374. if (_config.type == 'dropdown') {
  375. elem.find('option[name="' + value + '"]').prop('selected', true);
  376. }
  377. else if (_config.type == 'list') {
  378. const config = _config;
  379. if (config.multi === true) {
  380. elem.find('option').each(function (i, e) {
  381. const opt_name = e.getAttribute('name') || '#' + e.index;
  382. e.selected = value[opt_name];
  383. });
  384. }
  385. else {
  386. elem.find('option[name="' + value + '"]').prop('selected', true);
  387. }
  388. }
  389. else if (_config.type == 'checkbox') {
  390. elem.prop('checked', value);
  391. }
  392. else {
  393. elem.val(value);
  394. }
  395. }
  396. if (typeof this.cfg.on_refresh === 'function')
  397. this.cfg.on_refresh(ksof.settings[this.cfg.script_id]);
  398. }
  399. }
  400. // TODO find better name than SettingsClass. SettingsObj?
  401. function createSettingsObj() {
  402. const settings_obj = (config) => {
  403. return new Settings(config);
  404. };
  405. settings_obj.save = (context) => { return Settings.save(context); };
  406. settings_obj.load = (context, defaults) => { return Settings.load(context, defaults); };
  407. settings_obj.background = background_funcs();
  408. return settings_obj;
  409. }
  410. ksof.Settings = createSettingsObj();
  411. ksof.settings = {};
  412. //########################################################################
  413. let ready = false;
  414. //========================================================================
  415. function deep_merge(...objects) {
  416. const merged = {};
  417. function recursive_merge(dest, src) {
  418. for (const prop in src) {
  419. if (typeof src[prop] === 'object' && src[prop] !== null) {
  420. const srcProp = src[prop];
  421. if (Array.isArray(srcProp)) {
  422. dest[prop] = srcProp.slice();
  423. }
  424. else {
  425. dest[prop] = dest[prop] || {};
  426. recursive_merge(dest[prop], srcProp);
  427. }
  428. }
  429. else {
  430. dest[prop] = src[prop];
  431. }
  432. }
  433. return dest;
  434. }
  435. for (const obj in objects) {
  436. recursive_merge(merged, objects[obj]);
  437. }
  438. return merged;
  439. }
  440. //------------------------------
  441. // Convert a config object to html dialog.
  442. //------------------------------
  443. /* eslint-disable no-case-declarations */
  444. function config_to_html(context) {
  445. context.config_list = {};
  446. if (!ksof.settings) {
  447. return '';
  448. }
  449. let base = ksof.settings[context.cfg.script_id];
  450. if (base === undefined)
  451. ksof.settings[context.cfg.script_id] = base = {};
  452. let html = '';
  453. const child_passback = {};
  454. const id = context.cfg.script_id + '_dialog';
  455. for (const name in context.cfg.content) {
  456. html += parse_item(name, context.cfg.content[name], child_passback);
  457. }
  458. if (child_passback.tabs && child_passback.pages)
  459. html = assemble_pages(id, child_passback.tabs, child_passback.pages) + html;
  460. return '<form>' + html + '</form>';
  461. //============
  462. function parse_item(name, _item, passback) {
  463. if (typeof _item.type !== 'string')
  464. return '';
  465. const id = context.cfg.script_id + '_' + name;
  466. let cname, html = '', child_passback, non_page = '';
  467. const _type = _item.type;
  468. if (_type == 'tabset') {
  469. const item = _item;
  470. child_passback = {};
  471. for (cname in item.content) {
  472. non_page += parse_item(cname, item.content[cname], child_passback);
  473. }
  474. if (child_passback.tabs && child_passback.pages) {
  475. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  476. }
  477. }
  478. else if (_type == 'page') {
  479. const item = _item;
  480. if (typeof item.content !== 'object')
  481. item.content = {};
  482. if (!passback.tabs) {
  483. passback.tabs = [];
  484. }
  485. if (!passback.pages) {
  486. passback.pages = [];
  487. }
  488. passback.tabs.push('<li id="' + id + '_tab"' + to_title(item.hover_tip) + '><a href="#' + id + '">' + item.label + '</a></li>');
  489. child_passback = {};
  490. for (cname in item.content)
  491. non_page += parse_item(cname, item.content[cname], child_passback);
  492. if (child_passback.tabs && child_passback.pages)
  493. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  494. passback.pages.push('<div id="' + id + '">' + html + non_page + '</div>');
  495. passback.is_page = true;
  496. html = '';
  497. }
  498. else if (_type == 'group') {
  499. const item = _item;
  500. if (typeof item.content !== 'object')
  501. item.content = {};
  502. child_passback = {};
  503. for (cname in item.content)
  504. non_page += parse_item(cname, item.content[cname], child_passback);
  505. if (child_passback.tabs && child_passback.pages)
  506. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  507. html = '<fieldset id="' + id + '" class="ksof_group"><legend>' + item.label + '</legend>' + html + non_page + '</fieldset>';
  508. }
  509. else if (_type == 'dropdown') {
  510. const item = _item;
  511. context.config_list[name] = item;
  512. let value = get_value(context, base, name);
  513. if (value === undefined) {
  514. if (item.default !== undefined) {
  515. value = item.default;
  516. }
  517. else {
  518. value = Object.keys(item.content)[0];
  519. }
  520. set_value(context, base, name, value);
  521. }
  522. html = `<select id="${id}" name="${name}" class="setting"${to_title(item.hover_tip)}>`;
  523. for (cname in item.content)
  524. html += '<option name="' + cname + '">' + escape_text(item.content[cname]) + '</option>';
  525. html += '</select>';
  526. html = make_label(item) + wrap_right(html);
  527. html = wrap_row(html, item.full_width, item.hover_tip);
  528. }
  529. else if (_type == 'list') {
  530. const item = _item;
  531. context.config_list[name] = item;
  532. let value = get_value(context, base, name);
  533. if (value === undefined) {
  534. if (item.default !== undefined) {
  535. value = item.default;
  536. }
  537. else {
  538. if (item.multi === true) {
  539. value = {};
  540. Object.keys(item.content).forEach(function (key) {
  541. value[key] = false;
  542. });
  543. }
  544. else {
  545. value = Object.keys(item.content)[0];
  546. }
  547. }
  548. set_value(context, base, name, value);
  549. }
  550. let attribs = ' size="' + (item.size || Object.keys(item.content).length || 4) + '"';
  551. if (item.multi === true)
  552. attribs += ' multiple';
  553. html = `<select id="${id}" name="${name}" class="setting list"${attribs}${to_title(item.hover_tip)}>`;
  554. for (cname in item.content)
  555. html += '<option name="' + cname + '">' + escape_text(item.content[cname]) + '</option>';
  556. html += '</select>';
  557. html = make_label(item) + wrap_right(html);
  558. html = wrap_row(html, item.full_width, item.hover_tip);
  559. }
  560. else if (_type == 'checkbox') {
  561. const item = _item;
  562. context.config_list[name] = item;
  563. html = make_label(item);
  564. let value = get_value(context, base, name);
  565. if (value === undefined) {
  566. value = (item.default || false);
  567. set_value(context, base, name, value);
  568. }
  569. html += wrap_right('<input id="' + id + '" class="setting" type="checkbox" name="' + name + '">');
  570. html = wrap_row(html, item.full_width, item.hover_tip);
  571. }
  572. else if (_type == 'input') {
  573. const item = _item;
  574. const itype = item.subtype || 'text';
  575. context.config_list[name] = item;
  576. html += make_label(item);
  577. let value = get_value(context, base, name);
  578. if (value === undefined) {
  579. const is_number = (item.subtype === 'number');
  580. value = (item.default || (is_number ? 0 : ''));
  581. set_value(context, base, name, value);
  582. }
  583. html += wrap_right(`<input id="${id}" class="setting" type="${itype}" name="${name}"${(item.placeholder ? ' placeholder="' + escape_attr(item.placeholder) + '"' : '')}>`);
  584. html = wrap_row(html, item.full_width, item.hover_tip);
  585. }
  586. else if (_type == 'number') {
  587. const item = _item;
  588. const itype = item.type;
  589. context.config_list[name] = item;
  590. html += make_label(item);
  591. let value = get_value(context, base, name);
  592. if (value === undefined) {
  593. const is_number = (item.type === 'number');
  594. value = (item.default || (is_number ? 0 : ''));
  595. set_value(context, base, name, value);
  596. }
  597. html += wrap_right(`<input id="${id}" class="setting" type="${itype}" name="${name}"${(item.placeholder ? ' placeholder="' + escape_attr(item.placeholder) + '"' : '')}>`);
  598. html = wrap_row(html, item.full_width, item.hover_tip);
  599. }
  600. else if (_type == 'text') {
  601. const item = _item;
  602. const itype = item.type;
  603. context.config_list[name] = item;
  604. html += make_label(item);
  605. let value = get_value(context, base, name);
  606. if (value === undefined) {
  607. value = (item.default || '');
  608. set_value(context, base, name, value);
  609. }
  610. html += wrap_right(`<input id="${id}" class="setting" type="${itype}" name="${name}"${(item.placeholder ? ' placeholder="' + escape_attr(item.placeholder) + '"' : '')}>`);
  611. html = wrap_row(html, item.full_width, item.hover_tip);
  612. }
  613. else if (_type == 'color') {
  614. const item = _item;
  615. context.config_list[name] = item;
  616. html += make_label(item);
  617. let value = get_value(context, base, name);
  618. if (value === undefined) {
  619. value = (item.default || '#000000');
  620. set_value(context, base, name, value);
  621. }
  622. html += wrap_right('<input id="' + id + '" class="setting" type="color" name="' + name + '">');
  623. html = wrap_row(html, item.full_width, item.hover_tip);
  624. }
  625. else if (_type == 'button') {
  626. const item = _item;
  627. context.config_list[name] = item;
  628. html += make_label(item);
  629. const text = escape_text(item.text || 'Click');
  630. html += wrap_right('<button type="button" class="setting" name="' + name + '">' + text + '</button>');
  631. html = wrap_row(html, item.full_width, item.hover_tip);
  632. }
  633. else if (_type == 'divider') {
  634. html += '<hr>';
  635. }
  636. else if (_type == 'section') {
  637. const item = _item;
  638. html += '<section>' + (item.label || '') + '</section>';
  639. }
  640. else if (_type == 'html') {
  641. const item = _item;
  642. html += make_label(item);
  643. html += item.html;
  644. switch (item.wrapper) {
  645. case 'row':
  646. html = wrap_row(html, undefined, item.hover_tip);
  647. break;
  648. case 'left':
  649. html = wrap_left(html);
  650. break;
  651. case 'right':
  652. html = wrap_right(html);
  653. break;
  654. }
  655. }
  656. return html;
  657. function make_label(item) {
  658. if (typeof item.label !== 'string')
  659. return '';
  660. return wrap_left('<label for="' + id + '">' + item.label + '</label>');
  661. }
  662. }
  663. /* eslint-enable no-case-declarations */
  664. //============
  665. function assemble_pages(id, tabs, pages) { return '<div id="' + id + '" class="ksof_stabs"><ul>' + tabs.join('') + '</ul>' + pages.join('') + '</div>'; }
  666. function wrap_row(html, full, hover_tip) { return '<div class="row' + (full ? ' full' : '') + '"' + to_title(hover_tip) + '>' + html + '</div>'; }
  667. function wrap_left(html) { return '<div class="left">' + html + '</div>'; }
  668. function wrap_right(html) { return '<div class="right">' + html + '</div>'; }
  669. function escape_text(text) {
  670. return text.replace(/[<>]/g, (ch) => {
  671. if (ch == '<')
  672. return '&lt';
  673. if (ch == '>')
  674. return '&gt';
  675. return '';
  676. });
  677. }
  678. function escape_attr(text) { return text.replace(/"/g, '&quot;'); }
  679. function to_title(tip) { if (!tip)
  680. return ''; return ' title="' + tip.replace(/"/g, '&quot;') + '"'; }
  681. }
  682. function get_value(context, base, name) {
  683. const item = context.config_list[name];
  684. const evaluate = (item.path !== undefined);
  685. const path = (item.path || name);
  686. try {
  687. if (!evaluate)
  688. return base[path];
  689. return eval(path.replace(/@/g, 'base.'));
  690. }
  691. catch (e) {
  692. return;
  693. }
  694. }
  695. function set_value(context, base, name, value) {
  696. const item = context.config_list[name];
  697. const evaluate = (item.path !== undefined);
  698. const path = (item.path || name);
  699. try {
  700. if (!evaluate)
  701. return base[path] = value;
  702. let depth = 0;
  703. let new_path = '';
  704. let param = '';
  705. let c;
  706. for (let idx = 0; idx < path.length; idx++) {
  707. c = path[idx];
  708. if (c === '[') {
  709. if (depth++ === 0) {
  710. new_path += '[';
  711. param = '';
  712. }
  713. else {
  714. param += '[';
  715. }
  716. }
  717. else if (c === ']') {
  718. if (--depth === 0) {
  719. new_path += JSON.stringify(eval(param)) + ']';
  720. }
  721. else {
  722. param += ']';
  723. }
  724. }
  725. else {
  726. if (c === '@')
  727. c = 'base.';
  728. if (depth === 0)
  729. new_path += c;
  730. else
  731. param += c;
  732. }
  733. }
  734. eval(new_path + '=value');
  735. }
  736. catch (e) {
  737. return;
  738. }
  739. }
  740. function install_anchor() {
  741. let anchor = $('#ksof_ds');
  742. if (anchor.length === 0) {
  743. anchor = $('<div id="ksof_ds"></div></div>');
  744. $('body').prepend(anchor);
  745. $('#ksof_ds').on('keydown keyup keypress', '.ksof_settings_dialog', function (e) {
  746. // Stop keys from bubbling beyond the background overlay.
  747. e.stopPropagation();
  748. });
  749. }
  750. return anchor;
  751. }
  752. //------------------------------
  753. // Load jquery UI and the appropriate CSS based on location.
  754. //------------------------------
  755. const css_url = ksof.support_files['jqui_ksmain.css'];
  756. ksof.include('Jquery');
  757. await ksof.ready('document, Jquery');
  758. await Promise.all([
  759. ksof.load_script(ksof.support_files['jquery_ui.js'], true /* cache */),
  760. ksof.load_css(css_url, true /* cache */)
  761. ]);
  762. ready = true;
  763. // Workaround... https://community.wanikani.com/t/19984/55
  764. try {
  765. const temp = $.fn;
  766. delete temp.autocomplete;
  767. }
  768. catch (e) {
  769. // do nothing
  770. }
  771. // Notify listeners that we are ready.
  772. // Delay guarantees include() callbacks are called before ready() callbacks.
  773. setTimeout(function () { ksof.set_state('ksof.Settings', 'ready'); }, 0);
  774. })(this);