Wanikani Open Framework - Settings module

Settings module for Wanikani Open Framework

当前为 2018-03-27 提交的版本,查看 最新版本

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

  1. // ==UserScript==
  2. // @name Wanikani Open Framework - Settings module
  3. // @namespace rfindley
  4. // @description Settings module for Wanikani Open Framework
  5. // @version 1.0.4
  6. // @copyright 2018+, Robin Findley
  7. // @license MIT; http://opensource.org/licenses/MIT
  8. // ==/UserScript==
  9.  
  10. (function(global) {
  11.  
  12. const publish_context = false; // Set to 'true' to make context public.
  13.  
  14. //########################################################################
  15. //------------------------------
  16. // Constructor
  17. //------------------------------
  18. function Settings(config) {
  19. var context = {
  20. self: this,
  21. cfg: config,
  22. }
  23.  
  24. if (publish_context) this.context = context;
  25.  
  26. // Create public methods bound to context.
  27. this.cancel = cancel_btn.bind(context, context);
  28. this.open = open.bind(context, context);
  29. this.load = load_settings.bind(context, context);
  30. this.save = save_settings.bind(context, context);
  31. this.refresh = refresh.bind(context, context);
  32. this.background = Settings.background;
  33. };
  34.  
  35. global.wkof.Settings = Settings;
  36. Settings.save = save_settings;
  37. Settings.load = load_settings;
  38. Settings.background = {
  39. open: open_background,
  40. close: close_background,
  41. }
  42. //########################################################################
  43.  
  44. wkof.settings = {};
  45. var ready = false;
  46.  
  47. //------------------------------
  48. // Convert a config object to html dialog.
  49. //------------------------------
  50. function config_to_html(context) {
  51. context.config_list = {};
  52. var base = wkof.settings[context.cfg.script_id];
  53. if (base === undefined) wkof.settings[context.cfg.script_id] = base = {};
  54.  
  55. var html = '', item, child_passback = {};
  56. var id = context.cfg.script_id+'_dialog';
  57. for (var name in context.cfg.settings) {
  58. var item = context.cfg.settings[name];
  59. html += parse_item(name, context.cfg.settings[name], child_passback);
  60. }
  61. if (child_passback.tabs)
  62. html = assemble_pages(id, child_passback.tabs, child_passback.pages) + html;
  63. return '<form>'+html+'</form>';
  64.  
  65. //============
  66. function parse_item(name, item, passback) {
  67. if (typeof item.type !== 'string') return '';
  68. var id = context.cfg.script_id+'_'+name;
  69. var cname, html = '', value, child_passback, non_page = '';
  70. switch (item.type) {
  71. case 'tabset':
  72. child_passback = {};
  73. for (cname in item.content)
  74. non_page += parse_item(cname, item.content[cname], child_passback);
  75. if (child_passback.tabs)
  76. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  77. break;
  78.  
  79. case 'page':
  80. if (typeof item.content !== 'object') item.content = {};
  81. if (!passback.tabs) {
  82. passback.tabs = [];
  83. passback.pages = [];
  84. }
  85. passback.tabs.push('<li id="'+id+'_tab"'+to_title(item.hover_tip)+'><a href="#'+id+'">'+item.label+'</a></li>');
  86. child_passback = {};
  87. for (cname in item.content)
  88. non_page += parse_item(cname, item.content[cname], child_passback);
  89. if (child_passback.tabs)
  90. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  91. passback.pages.push('<div id="'+id+'">'+html+non_page+'</div>');
  92. passback.is_page = true;
  93. html = '';
  94. break;
  95.  
  96. case 'group':
  97. if (typeof item.content !== 'object') item.content = {};
  98. child_passback = {};
  99. for (cname in item.content)
  100. non_page += parse_item(cname, item.content[cname], child_passback);
  101. if (child_passback.tabs)
  102. html = assemble_pages(id, child_passback.tabs, child_passback.pages);
  103. html = '<fieldset id="'+id+'" class="wkof_group"><legend>'+item.label+'</legend>'+html+non_page+'</fieldset>';
  104. break;
  105.  
  106. case 'dropdown':
  107. case 'list':
  108. var classes = 'setting', attribs = '';
  109. context.config_list[name] = item;
  110. value = get_value(context, base, name);
  111. if (value === undefined) {
  112. if (item.default !== undefined) {
  113. value = item.default;
  114. } else {
  115. if (item.multi === true) {
  116. value = {};
  117. Object.keys(item.content).forEach(function(key){
  118. value[key] = false;
  119. });
  120. } else {
  121. value = Object.keys(item.content)[0];
  122. }
  123. }
  124. set_value(context, base, name, value);
  125. }
  126. if (item.type === 'list') {
  127. classes += ' list';
  128. attribs += ' size="'+(item.size || Object.keys(item.content).length || 4)+'"';
  129. if (item.multi === true) attribs += ' multiple';
  130. }
  131. html = '<select id="'+id+'" name="'+name+'" class="'+classes+'"'+attribs+to_title(item.hover_tip)+'>';
  132. for (cname in item.content)
  133. html += '<option name="'+cname+'">'+escape(item.content[cname])+'</option>';
  134. html += '</select>';
  135. html = make_label(item) + wrap_right(html);
  136. html = wrap_row(html, item.full_width, item.hover_tip);
  137. break;
  138.  
  139. case 'checkbox':
  140. context.config_list[name] = item;
  141. html = make_label(item);
  142. value = get_value(context, base, name);
  143. if (value === undefined) {
  144. value = (item.default || false);
  145. set_value(context, base, name, value);
  146. }
  147. html += wrap_right('<input id="'+id+'" class="setting" type="checkbox" name="'+name+'">');
  148. html = wrap_row(html, item.full_width, item.hover_tip);
  149. break;
  150.  
  151. case 'input':
  152. case 'number':
  153. case 'text':
  154. var itype = item.type;
  155. if (itype === 'input') itype = item.subtype || 'text';
  156. context.config_list[name] = item;
  157. html += make_label(item);
  158. value = get_value(context, base, name);
  159. if (value === undefined) {
  160. var is_number = (item.type==='number' || item.subtype==='number');
  161. value = (item.default || (is_number==='number'?'0':''));
  162. set_value(context, base, name, value);
  163. }
  164. html += wrap_right('<input id="'+id+'" class="setting" type="'+itype+'" name="'+name+'"'+(item.placeholder?' placeholder="'+escape(item.placeholder)+'"':'')+'>');
  165. html = wrap_row(html, item.full_width, item.hover_tip);
  166. break;
  167.  
  168. case 'color':
  169. context.config_list[name] = item;
  170. html += make_label(item);
  171. value = get_value(context, base, name);
  172. if (value === undefined) {
  173. value = (item.default || '#000000');
  174. set_value(context, base, name, value);
  175. }
  176. html += wrap_right('<input id="'+id+'" class="setting" type="color" name="'+name+'">');
  177. html = wrap_row(html, item.full_width, item.hover_tip);
  178. break;
  179.  
  180. case 'divider':
  181. html += '<hr>';
  182. break;
  183.  
  184. case 'section':
  185. html += '<section>'+(item.label || '')+'</section>';
  186. break;
  187.  
  188. case 'html':
  189. html += make_label(item);
  190. html += item.html;
  191. switch (item.wrapper) {
  192. case 'row': html = wrap_row(html, null, item.hover_tip); break;
  193. case 'left': html = wrap_left(html); break;
  194. case 'right': html = wrap_right(html); break;
  195. }
  196. break;
  197. }
  198. return html;
  199.  
  200. function make_label(item) {
  201. if (typeof item.label !== 'string') return '';
  202. return wrap_left('<label for="'+id+'">'+item.label+'</label>');
  203. }
  204. }
  205.  
  206. //============
  207. function assemble_pages(id, tabs, pages) {return '<div id="'+id+'" class="wkof_stabs"><ul>'+tabs.join('')+'</ul>'+pages.join('')+'</div>';}
  208. function wrap_row(html,full,hover_tip) {return '<div class="row'+(full?' full':'')+'"'+to_title(hover_tip)+'>'+html+'</div>';}
  209. function wrap_left(html) {return '<div class="left">'+html+'</div>';}
  210. function wrap_right(html) {return '<div class="right">'+html+'</div>';}
  211. function escape(text) {return text.replace(/</g,'&lt;').replace(/>/g,'&gt;');}
  212. function to_title(tip) {if (!tip) return ''; return ' title="'+tip.replace(/"/g,'&quot;')+'"';}
  213. }
  214.  
  215. //------------------------------
  216. // Open the settings dialog.
  217. //------------------------------
  218. function open(context) {
  219. if (!ready) return;
  220. if ($('#wkofs_'+context.cfg.script_id).length > 0) return;
  221. install_anchor();
  222. if (context.cfg.background !== false) open_background();
  223. var dialog = $('<div id="wkofs_'+context.cfg.script_id+'" class="wkof_settings" style="display:none;"></div>');
  224. dialog.html(config_to_html(context));
  225.  
  226. var width = 500;
  227. if (window.innerWidth < 510) {
  228. width = 280;
  229. dialog.addClass('narrow');
  230. }
  231. dialog.dialog({
  232. title: context.cfg.title+' Settings',
  233. buttons: [
  234. {text:'Save',click:save_btn.bind(context,context)},
  235. {text:'Cancel',click:cancel_btn.bind(context,context)}
  236. ],
  237. width: width,
  238. maxHeight: window.innerHeight,
  239. modal: false,
  240. autoOpen: false,
  241. appendTo: '#wkof_ds',
  242. resize: resize.bind(context,context),
  243. close: close.bind(context,context)
  244. });
  245. dialog.closest('[role="dialog"]').css('position','fixed');
  246.  
  247. $('.wkof_stabs').tabs();
  248. dialog.dialog('open');
  249. $('#wkofs_'+context.cfg.script_id+' .setting[multiple]').on('mousedown', toggle_multi.bind(null,context));
  250. $('#wkofs_'+context.cfg.script_id+' .setting').on('change', setting_changed.bind(null,context));
  251. $('#wkofs_'+context.cfg.script_id+' form').on('submit', function(){return false;});
  252.  
  253. if (typeof context.cfg.pre_open === 'function') context.cfg.pre_open(dialog);
  254. context.reversions = $.extend(true,{},wkof.settings[context.cfg.script_id]);
  255. refresh(context);
  256.  
  257. //============
  258. function resize(context, event, ui){
  259. var dialog = $('#wkofs_'+context.cfg.script_id);
  260. var is_narrow = dialog.hasClass('narrow');
  261. if (is_narrow && ui.size.width >= 510)
  262. dialog.removeClass('narrow');
  263. else if (!is_narrow && ui.size.width < 490)
  264. dialog.addClass('narrow');
  265. }
  266.  
  267. function toggle_multi(context, e) {
  268. if (e.button != 0) return true;
  269. var multi = $(e.currentTarget);
  270. var scroll = e.currentTarget.scrollTop;
  271. e.target.selected = !e.target.selected;
  272. setTimeout(function(){
  273. e.currentTarget.scrollTop = scroll;
  274. multi.focus();
  275. },0);
  276. return setting_changed(context, e);
  277. }
  278. }
  279.  
  280. //------------------------------
  281. // Open the settings dialog.
  282. //------------------------------
  283. function save_settings(context) {
  284. var script_id = (typeof context === 'string' ? context : context.cfg.script_id);
  285. var settings = wkof.settings[script_id];
  286. if (!settings) return Promise.resolve();
  287. return wkof.file_cache.save('wkof.settings.'+script_id, settings);
  288. }
  289.  
  290. //------------------------------
  291. // Open the settings dialog.
  292. //------------------------------
  293. function load_settings(context) {
  294. var script_id = (typeof context === 'string' ? context : context.cfg.script_id);
  295. return wkof.file_cache.load('wkof.settings.'+script_id)
  296. .then(finish, finish.bind(null,{}));
  297.  
  298. function finish(settings) {
  299. wkof.settings[script_id] = settings;
  300. }
  301. }
  302.  
  303. //------------------------------
  304. // Save button handler.
  305. //------------------------------
  306. function save_btn(context, e) {
  307. if (context.cfg.autosave === undefined || context.cfg.autosave === true) save_settings(context);
  308. if (typeof context.cfg.on_save === 'function') context.cfg.on_save(wkof.settings[context.cfg.script_id]);
  309. wkof.trigger('wkof.settings.save');
  310. var dialog = $('#wkofs_'+context.cfg.script_id);
  311. context.keep_settings = true;
  312. dialog.dialog('close');
  313. }
  314.  
  315. //------------------------------
  316. // Cancel button handler.
  317. //------------------------------
  318. function cancel_btn(context) {
  319. var dialog = $('#wkofs_'+context.cfg.script_id);
  320. dialog.dialog('close');
  321. if (typeof context.cfg.on_cancel === 'function') context.cfg.on_cancel(wkof.settings[context.cfg.script_id]);
  322. }
  323.  
  324. //------------------------------
  325. // Close and destroy the dialog.
  326. //------------------------------
  327. function close(context) {
  328. var dialog = $('#wkofs_'+context.cfg.script_id);
  329. if (!context.keep_settings) {
  330. // Revert settings
  331. wkof.settings[context.cfg.script_id] = $.extend(true,{},context.reversions);
  332. delete context.reversions;
  333. }
  334. delete context.keep_settings;
  335. dialog.dialog('destroy');
  336. if (context.cfg.background !== false) close_background();
  337. if (typeof context.cfg.on_close === 'function') context.cfg.on_close(wkof.settings[context.cfg.script_id]);
  338. }
  339.  
  340. //------------------------------
  341. // Update the dialog to reflect changed settings.
  342. //------------------------------
  343. function refresh(context) {
  344. var script_id = context.cfg.script_id;
  345. var settings = wkof.settings[script_id];
  346. var dialog = $('#wkofs_'+script_id);
  347. for (var name in context.config_list) {
  348. var elem = dialog.find('#'+script_id+'_'+name);
  349. var config = context.config_list[name];
  350. var value = get_value(context, settings, name);
  351. switch (config.type) {
  352. case 'dropdown':
  353. case 'list':
  354. if (config.multi === true) {
  355. elem.find('option').each(function(i,e){
  356. var opt_name = e.getAttribute('name') || '#'+e.index;
  357. e.selected = value[opt_name];
  358. });
  359. } else {
  360. elem.find('option[name="'+value+'"]').prop('selected', true);
  361. }
  362. break;
  363.  
  364. case 'checkbox':
  365. elem.prop('checked', value);
  366. break;
  367.  
  368. default:
  369. elem.val(value);
  370. break;
  371. }
  372. }
  373. if (typeof context.cfg.on_refresh === 'function') context.cfg.on_refresh(wkof.settings[context.cfg.script_id]);
  374. }
  375.  
  376. //------------------------------
  377. // Handler for live settings changes. Handles built-in validation and user callbacks.
  378. //------------------------------
  379. function setting_changed(context, event) {
  380. var elem = $(event.currentTarget);
  381. var name = elem.attr('name');
  382. var item = context.config_list[name];
  383. var config;
  384.  
  385. // Extract the value
  386. var value;
  387. var itype = ((item.type==='input' && item.subtype==='number') ? 'number' : item.type);
  388. switch (itype) {
  389. case 'dropdown':
  390. case 'list':
  391. if (item.multi === true) {
  392. value = {};
  393. elem.find('option').each(function(i,e){
  394. var opt_name = e.getAttribute('name') || '#'+e.index;
  395. value[opt_name] = e.selected;
  396. });
  397. } else {
  398. value = elem.find(':checked').attr('name');
  399. }
  400. break;
  401. case 'checkbox': value = elem.is(':checked'); break;
  402. case 'number': value = Number(elem.val()); break;
  403. default: value = elem.val(); break;
  404. }
  405.  
  406. // Validation
  407. var valid = {valid:true, msg:''};
  408. if (typeof item.validate === 'function') valid = item.validate.call(event.target, value, item);
  409. if (typeof valid === 'boolean')
  410. valid = {valid:valid, msg:''};
  411. else if (typeof valid === 'string')
  412. valid = {valid:false, msg:valid};
  413. else if (valid === undefined)
  414. valid = {valid:true, msg:''};
  415. switch (itype) {
  416. case 'number':
  417. if (typeof item.min === 'number' && Number(value) < item.min) {
  418. valid.valid = false;
  419. if (valid.msg.length === 0) {
  420. if (typeof item.max === 'number')
  421. valid.msg = 'Must be between '+item.min+' and '+item.max;
  422. else
  423. valid.msg = 'Must be '+item.min+' or higher';
  424. }
  425. } else if (typeof item.max === 'number' && Number(value) > item.max) {
  426. valid.valid = false;
  427. if (valid.msg.length === 0) {
  428. if (typeof item.min === 'number')
  429. valid.msg = 'Must be between '+item.min+' and '+item.max;
  430. else
  431. valid.msg = 'Must be '+item.max+' or lower';
  432. }
  433. }
  434. if (!valid)
  435. break;
  436.  
  437. case 'text':
  438. if (item.match !== undefined && value.match(item.match) === null) {
  439. valid.valid = false;
  440. if (valid.msg.length === 0)
  441. valid.msg = item.error_msg || 'Invalid value';
  442. }
  443. break;
  444. }
  445.  
  446. // Style for valid/invalid
  447. var parent = elem.closest('.row');
  448. parent.find('.note').remove();
  449. if (typeof valid.msg === 'string' && valid.msg.length > 0)
  450. parent.append('<div class="note'+(valid.valid?'':' error')+'">'+valid.msg+'</div>');
  451. if (!valid.valid) {
  452. elem.addClass('invalid');
  453. } else {
  454. elem.removeClass('invalid');
  455. }
  456.  
  457. var script_id = context.cfg.script_id;
  458. var settings = wkof.settings[script_id];
  459. if (valid.valid) {
  460. if (item.no_save !== true) set_value(context, settings, name, value);
  461. if (typeof item.on_change === 'function') item.on_change.call(event.target, name, value, item);
  462. if (item.refresh_on_change === true) refresh(context);
  463. }
  464.  
  465. return false;
  466. }
  467.  
  468. function get_value(context, base, name){
  469. var item = context.config_list[name];
  470. var evaluate = (item.path !== undefined);
  471. var path = (item.path || name);
  472. try {
  473. if (!evaluate) return base[path];
  474. return eval(path.replace(/@/g,'base.'));
  475. } catch(e) {return;}
  476. }
  477.  
  478. function set_value(context, base, name, value) {
  479. var item = context.config_list[name];
  480. var evaluate = (item.path !== undefined);
  481. var path = (item.path || name);
  482. try {
  483. if (!evaluate) return base[path] = value;
  484. var depth=0, new_path='', param, c;
  485. for (var idx = 0; idx < path.length; idx++) {
  486. c = path[idx];
  487. if (c === '[') {
  488. if (depth++ === 0) {
  489. new_path += '[';
  490. param = '';
  491. } else {
  492. param += '[';
  493. }
  494. } else if (c === ']') {
  495. if (--depth === 0) {
  496. new_path += JSON.stringify(eval(param)) + ']';
  497. } else {
  498. param += ']';
  499. }
  500. } else {
  501. if (c === '@') c = 'base.';
  502. if (depth === 0)
  503. new_path += c;
  504. else
  505. param += c;
  506. }
  507. }
  508. eval(new_path + '=value');
  509. } catch(e) {return;}
  510. }
  511.  
  512. function install_anchor() {
  513. var anchor = $('#wkof_ds');
  514. if (anchor.length === 0) {
  515. anchor = $('<div id="wkof_ds"></div></div>');
  516. $('body').prepend(anchor);
  517. }
  518. return anchor;
  519. }
  520.  
  521. function open_background() {
  522. var anchor = install_anchor();
  523. var bkgd = anchor.find('> #wkofs_bkgd');
  524. if (bkgd.length === 0) {
  525. bkgd = $('<div id="wkofs_bkgd" refcnt="0"></div>');
  526. anchor.prepend(bkgd);
  527. }
  528. var refcnt = Number(bkgd.attr('refcnt'));
  529. bkgd.attr('refcnt', refcnt + 1);
  530. }
  531.  
  532. function close_background() {
  533. var bkgd = $('#wkof_ds > #wkofs_bkgd');
  534. if (bkgd.length === 0) return;
  535. var refcnt = Number(bkgd.attr('refcnt'));
  536. if (refcnt <= 0) return;
  537. bkgd.attr('refcnt', refcnt - 1);
  538. }
  539.  
  540. //------------------------------
  541. // Load jquery UI and the appropriate CSS based on location.
  542. //------------------------------
  543. var css_url;
  544. if (location.hostname.match(/^(www\.)?wanikani\.com$/) !== null)
  545. css_url = wkof.support_files['jqui_wkmain.css'];
  546.  
  547. Promise.all([
  548. wkof.load_script(wkof.support_files['jquery_ui.js'], true /* cache */),
  549. wkof.load_css(css_url, true /* cache */)
  550. ])
  551. .then(function(data){
  552. ready = true;
  553.  
  554. // Notify listeners that we are ready.
  555. // Delay guarantees include() callbacks are called before ready() callbacks.
  556. setTimeout(function(){wkof.set_state('wkof.Settings', 'ready');},0);
  557. });
  558.  
  559. })(this);