KameSame Open Framework - Settings module

Settings module for KameSame Open Framework

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

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