Wanikani Open Framework - ItemData module

ItemData module for Wanikani Open Framework

当前为 2018-04-20 提交的版本,查看 最新版本

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

  1. // ==UserScript==
  2. // @name Wanikani Open Framework - ItemData module
  3. // @namespace rfindley
  4. // @description ItemData module for Wanikani Open Framework
  5. // @version 1.0.10
  6. // @copyright 2018+, Robin Findley
  7. // @license MIT; http://opensource.org/licenses/MIT
  8. // ==/UserScript==
  9.  
  10. (function(global) {
  11.  
  12. //########################################################################
  13. //------------------------------
  14. // Published interface.
  15. //------------------------------
  16. global.wkof.ItemData = {
  17. presets: {},
  18. registry: {
  19. sources: {},
  20. indices: {},
  21. },
  22. get_items: get_items,
  23. get_index: get_index,
  24. pause_ready_event: pause_ready_event
  25. };
  26. //########################################################################
  27.  
  28. function promise(){var a,b,c=new Promise(function(d,e){a=d;b=e;});c.resolve=a;c.reject=b;return c;}
  29. function split_list(str) {return str.replace(/^\s+|\s*(,)\s*|\s+$/g, '$1').split(',').filter(function(name) {return (name.length > 0);});}
  30.  
  31. //------------------------------
  32. // Get the items specified by the configuration.
  33. //------------------------------
  34. function get_items(config, global_options) {
  35. // Default to WK 'subjects' only.
  36. if (!config) config = {wk_items:{}};
  37.  
  38. // Allow comma-separated list of WK-only endpoints.
  39. if (typeof config === 'string') {
  40. var endpoints = split_list(config)
  41. var config = {wk_items:{options:{}}};
  42. for (var idx in endpoints)
  43. config.wk_items.options[endpoints[idx]] = true;
  44. }
  45.  
  46. // Fetch the requested endpoints.
  47. var fetch_promise = promise();
  48. var items = [];
  49. var remaining = 0;
  50. for (var cfg_name in config) {
  51. var cfg = config[cfg_name];
  52. var spec = wkof.ItemData.registry.sources[cfg_name];
  53. if (!spec || typeof spec.fetcher !== 'function') {
  54. console.log('wkof.ItemData.get_items() - Config "'+cfg_name+'" not registered!');
  55. continue;
  56. }
  57. remaining++;
  58. spec.fetcher(cfg, global_options)
  59. .then(function(data){
  60. var filter_promise;
  61. if (typeof spec === 'object')
  62. filter_promise = apply_filters(data, cfg, spec);
  63. else
  64. filter_promise = Promise.resolve(data);
  65. filter_promise.then(function(data){
  66. items = items.concat(data);
  67. remaining--;
  68. if (!remaining) fetch_promise.resolve(items);
  69. });
  70. })
  71. .catch(function(e){
  72. if (e) throw e;
  73. console.log('wkof.ItemData.get_items() - Failed for config "'+cfg_name+'"');
  74. remaining--;
  75. if (!remaining) fetch_promise.resolve(items);
  76. });
  77. }
  78. if (remaining === 0) fetch_promise.resolve(items);
  79. return fetch_promise;
  80. }
  81.  
  82. //------------------------------
  83. // Get the wk_items specified by the configuration.
  84. //------------------------------
  85. function get_wk_items(config, options) {
  86. var cfg_options = config.options || {};
  87. options = options || {};
  88. var now = new Date().getTime();
  89.  
  90. // Endpoints that we can fetch (subjects MUST BE FIRST!!)
  91. var available_endpoints = ['subjects','assignments','review_statistics','study_materials'];
  92. var spec = wkof.ItemData.registry.sources.wk_items;
  93. for (var filter_name in config.filters) {
  94. var filter_spec = spec.filters[filter_name];
  95. if (!filter_spec || typeof filter_spec.set_options !== 'function') continue;
  96. var filter_cfg = config.filters[filter_name];
  97. filter_spec.set_options(cfg_options, filter_cfg.value);
  98. }
  99.  
  100. // Fetch all of the endpoints
  101. var ep_promises = [];
  102. for (var idx in available_endpoints) {
  103. var ep_name = available_endpoints[idx];
  104. if (ep_name === 'subjects' || cfg_options[ep_name] === true)
  105. ep_promises.push(
  106. wkof.Apiv2.get_endpoint(ep_name, options)
  107. .then(process_data.bind(null, ep_name))
  108. );
  109. }
  110. return Promise.all(ep_promises)
  111. .then(function(all_data){
  112. return all_data[0];
  113. });
  114.  
  115. //============
  116. function process_data(ep_name, ep_data) {
  117. if (ep_name === 'subjects') return ep_data;
  118. // Merge with 'subjects' when 'subjects' is done fetching.
  119. return ep_promises[0].then(cross_link.bind(null, ep_name, ep_data));
  120. }
  121.  
  122. //============
  123. function cross_link(ep_name, ep_data, subjects) {
  124. for (var id in ep_data) {
  125. var record = ep_data[id];
  126. var subject_id = record.data.subject_id;
  127. subjects[subject_id][ep_name] = record.data;
  128. }
  129. }
  130. }
  131.  
  132. //------------------------------
  133. // Filter the items array according to the specified filters and options.
  134. //------------------------------
  135. function apply_filters(items, config, spec) {
  136. var prep_promises = [];
  137. var options = config.options || {};
  138. var filters = [];
  139. for (var filter_name in config.filters) {
  140. var filter_cfg = config.filters[filter_name];
  141. if (typeof filter_cfg !== 'object' || filter_cfg.value === undefined)
  142. filter_cfg = {value:filter_cfg};
  143. var filter_value = filter_cfg.value;
  144. var filter_spec = spec.filters[filter_name];
  145. if (filter_spec === undefined) throw new Error('wkof.ItemData.get_item() - Invalid filter "'+filter_name+'"');
  146. if (typeof filter_spec.filter_value_map === 'function')
  147. filter_value = filter_spec.filter_value_map(filter_cfg.value);
  148. if (typeof filter_spec.prepare === 'function') {
  149. var result = filter_spec.prepare(filter_value);
  150. if (result instanceof Promise) prep_promises.push(result);
  151. }
  152. filters.push({
  153. name: filter_name,
  154. func: filter_spec.filter_func,
  155. filter_value: filter_value,
  156. invert: (filter_cfg.invert === true)
  157. });
  158. }
  159.  
  160. return Promise.all(prep_promises).then(function(){
  161. var result = [];
  162. var max_level = Math.max(wkof.user.max_level_granted_by_subscription, wkof.user.override_max_level || 0);
  163. for (var item_idx in items) {
  164. var keep = true;
  165. var item = items[item_idx];
  166. if (item.data.level > max_level) continue;
  167. for (var filter_idx in filters) {
  168. var filter = filters[filter_idx];
  169. try {
  170. keep = filter.func(filter.filter_value, item);
  171. if (filter.invert) keep = !keep;
  172. if (!keep) break;
  173. } catch(e) {
  174. keep = false;
  175. break;
  176. }
  177. }
  178. if (keep) result.push(item);
  179. }
  180. return result;
  181. });
  182. }
  183.  
  184. //------------------------------
  185. // Return the items indexed by an indexing function.
  186. //------------------------------
  187. function get_index(items, index_name) {
  188. var index_func = wkof.ItemData.registry.indices[index_name];
  189. if (typeof index_func !== 'function') throw new Error('wkof.ItemData.index_by() - Invalid index function "'+index_name+'"');
  190. return index_func(items);
  191. }
  192.  
  193. //------------------------------
  194. // Register wk_items data source.
  195. //------------------------------
  196. wkof.ItemData.registry.sources['wk_items'] = {
  197. description: 'Wanikani',
  198. fetcher: get_wk_items,
  199. options: {
  200. assignments: {
  201. type: 'checkbox',
  202. label: 'Assignments',
  203. default: false,
  204. hover_tip: 'Include the "/assignments" endpoint (SRS status, burn status, progress dates)'
  205. },
  206. review_statistics: {
  207. type: 'checkbox',
  208. label: 'Review Statistics',
  209. default: false,
  210. hover_tip: 'Include the "/review_statistics" endpoint:\n * Per-item review count\n *Correct/incorrect count\n * Longest streak'
  211. },
  212. study_materials: {
  213. type: 'checkbox',
  214. label: 'Study Materials',
  215. default: false,
  216. hover_tip: 'Include the "/study_materials" endpoint:\n * User synonyms\n * User notes'
  217. },
  218. },
  219. filters: {
  220. item_type: {
  221. type: 'multi',
  222. label: 'Item type',
  223. content: {radical:'Radicals',kanji:'Kanji',vocabulary:'Vocabulary'},
  224. default: [],
  225. filter_value_map: item_type_to_arr,
  226. filter_func: function(filter_value, item){return filter_value[item.object] === true;},
  227. hover_tip: 'Filter by item type (radical, kanji, vocabulary)',
  228. },
  229. level: {
  230. type: 'text',
  231. label: 'Level',
  232. placeholder: '(e.g. "1..3,5")',
  233. default: '',
  234. filter_value_map: levels_to_arr,
  235. filter_func: function(filter_value, item){return filter_value[item.data.level] === true;},
  236. hover_tip: 'Filter by Wanikani level\nExamples:\n "*" (All levels)\n "1..3,5" (Levels 1 through 3, and level 5)\n "1..-1" (From level 1 to your current level minus 1)\n "-5..+0" (Your current level and previous 5 levels)\n "+1" (Your next level)',
  237. },
  238. srs: {
  239. type: 'multi',
  240. label: 'SRS Level',
  241. content: {lock:'Locked',init:'Initiate (Lesson Queue)',appr1:'Apprentice 1',appr2:'Apprentice 2',appr3:'Apprentice 3',appr4:'Apprentice 4',guru1:'Guru 1',guru2:'Guru 2',mast:'Master',enli:'Enlightened',burn:'Burned'},
  242. default: [],
  243. set_options: function(options){options.assignments = true;},
  244. filter_value_map: srs_to_arr,
  245. filter_func: function(filter_value, item){return filter_value[(item.assignments ? item.assignments.srs_stage : -1)] === true;},
  246. hover_tip: 'Filter by SRS level (Apprentice 1, Apprentice 2, ..., Burn)',
  247. },
  248. have_burned: {
  249. type: 'checkbox',
  250. label: 'Have burned',
  251. default: true,
  252. set_options: function(options){options.assignments = true;},
  253. filter_func: function(filter_value, item){return (item.assignments.burned_at !== null) === filter_value;},
  254. hover_tip: 'Filter items by whether they have ever been burned.\n * If checked, select burned items (including resurrected)\n * If unchecked, select items that have never been burned',
  255. },
  256. }
  257. };
  258.  
  259. //------------------------------
  260. // Macro to build a function to index by a specific field.
  261. // Set make_subarrays to true if more than one item can share the same field value (e.g. same item_type).
  262. //------------------------------
  263. function make_index_func(name, field, entry_type) {
  264. var fn = '';
  265. fn +=
  266. 'var index = {}, value;\n'+
  267. 'for (var idx in items) {\n'+
  268. ' var item = items[idx];\n'+
  269. ' try {\n'+
  270. ' value = '+field+';\n'+
  271. ' } catch(e) {continue;}\n'+
  272. ' if (value === null || value === undefined) continue;\n';
  273. if (entry_type === 'array') {
  274. fn +=
  275. ' if (index[value] === undefined) {\n'+
  276. ' index[value] = [item];\n'+
  277. ' continue;\n'+
  278. ' }\n';
  279. } else {
  280. fn +=
  281. ' if (index[value] === undefined) {\n'+
  282. ' index[value] = item;\n'+
  283. ' continue;\n'+
  284. ' }\n';
  285. if (entry_type === 'single_or_array') {
  286. fn +=
  287. ' if (!Array.isArray(index[value]))\n'+
  288. ' index[value] = [index[value]];\n';
  289. }
  290. }
  291. fn +=
  292. ' index[value].push(item);\n'+
  293. '}\n'+
  294. 'return index;'
  295. wkof.ItemData.registry.indices[name] = new Function('items', fn);
  296. }
  297.  
  298. // Build some index functions.
  299. make_index_func('item_type', 'item.object', 'array');
  300. make_index_func('level', 'item.data.level', 'array');
  301. make_index_func('slug', 'item.data.slug', 'single_or_array');
  302. make_index_func('srs_stage', 'item.assignments.srs_stage', 'array');
  303. make_index_func('srs_stage_name', 'item.assignments.srs_stage_name', 'array');
  304. make_index_func('subject_id', 'item.id', 'single');
  305.  
  306. //------------------------------
  307. // Index by reading
  308. //------------------------------
  309. wkof.ItemData.registry.indices['reading'] = function(items) {
  310. var index = {};
  311. for (var idx in items) {
  312. var item = items[idx];
  313. if (!item.hasOwnProperty('data') || !item.data.hasOwnProperty('readings')) continue;
  314. if (!Array.isArray(item.data.readings)) continue;
  315. var readings = item.data.readings;
  316. for (var idx2 in readings) {
  317. var reading = readings[idx2].reading;
  318. if (reading === 'None') continue;
  319. if (!index[reading]) index[reading] = [];
  320. index[reading].push(item);
  321. }
  322. }
  323. return index;
  324. }
  325.  
  326. //------------------------------
  327. // Given an array of item type criteria (e.g. ['rad', 'kan', 'voc']), return
  328. // an array containing 'true' for each item type contained in the criteria.
  329. //------------------------------
  330. function item_type_to_arr(filter_value) {
  331. var xlat = {rad:'radical',kan:'kanji',voc:'vocabulary'};
  332. var arr = {}, value;
  333. if (typeof filter_value === 'string') filter_value = split_list(filter_value);
  334. if (typeof filter_value !== 'object') return {};
  335. if (Array.isArray(filter_value)) {
  336. for (var idx in filter_value) {
  337. value = filter_value[idx];
  338. value = xlat[value] || value;
  339. arr[value] = true;
  340. }
  341. } else {
  342. for (value in filter_value) {
  343. arr[xlat[value] || value] = (filter_value[value] === true);
  344. }
  345. }
  346. return arr;
  347. }
  348.  
  349. //------------------------------
  350. // Given an array of srs criteria (e.g. ['mast', 'enli', 'burn']), return an
  351. // array containing 'true' for each srs level contained in the criteria.
  352. //------------------------------
  353. function srs_to_arr(filter_value) {
  354. var index = ['init','appr1','appr2','appr3','appr4','guru1','guru2','mast','enli','burn'];
  355. var arr = [], value;
  356. if (typeof filter_value === 'string') filter_value = split_list(filter_value);
  357. if (typeof filter_value !== 'object') return {};
  358. if (Array.isArray(filter_value)) {
  359. for (var idx in filter_value) {
  360. value = Number(filter_value[idx]);
  361. if (isNaN(value)) value = index.indexOf(filter_value[idx]);
  362. arr[value] = true;
  363. }
  364. } else {
  365. for (value in filter_value) {
  366. arr[index.indexOf(value)] = (filter_value[value] === true);
  367. }
  368. }
  369. return arr;
  370. }
  371.  
  372. //------------------------------
  373. // Given an level criteria string (e.g. '1..3,5,8'), return an array containing
  374. // 'true' for each level contained in the criteria.
  375. //------------------------------
  376. function levels_to_arr(filter_value) {
  377. var levels = [], crit_idx, start, stop, lvl;
  378.  
  379. // Process each comma-separated criteria separately.
  380. var criteria = filter_value.split(',');
  381. for (crit_idx = 0; crit_idx < criteria.length; crit_idx++) {
  382. var crit = criteria[crit_idx];
  383. var value = true;
  384.  
  385. // Match '*' = all levels
  386. var match = crit.match(/^\s*(\*)\s*$/);
  387. if (match !== null) {
  388. start = to_num('1');
  389. stop = to_num('9999'); // All levels
  390. for (lvl = start; lvl <= stop; lvl++)
  391. levels[lvl] = value;
  392. continue;
  393. }
  394.  
  395. // Match 'a..b' = range of levels (or exclude if preceded by '!')
  396. match = crit.match(/^\s*(\!?)\s*((\+|-)?\d+)\s*(-|\.\.\.?|to)\s*((\+|-)?\d+)\s*$/);
  397. if (match !== null) {
  398. start = to_num(match[2]);
  399. stop = to_num(match[5]);
  400. if (match[1] === '!') value = false;
  401. for (lvl = start; lvl <= stop; lvl++)
  402. levels[lvl] = value;
  403. continue;
  404. }
  405.  
  406. // Match 'a' = specific level (or exclude if preceded by '!')
  407. match = crit.match(/^\s*(\!?)\s*((\+|-)?\d+)\s*$/);
  408. if (match !== null) {
  409. lvl = to_num(match[2]);
  410. if (match[1] === '!') value = false;
  411. levels[lvl] = value;
  412. continue;
  413. }
  414. var err = 'wkof.ItemData::levels_to_arr() - Bad filter criteria "'+filter_value+'"';
  415. console.log(err);
  416. throw err;
  417. }
  418. return levels;
  419.  
  420. //============
  421. function to_num(num) {
  422. num = (num[0] < '0' ? wkof.user.level : 0) + Number(num)
  423. return Math.min(Math.max(1, num), wkof.user.max_level_granted_by_subscription);
  424. }
  425. }
  426.  
  427. var registration_promise;
  428. var registration_timeout;
  429. var registration_counter = 0;
  430. //------------------------------
  431. // Ask clients to add items to the registry.
  432. //------------------------------
  433. function call_for_registration() {
  434. registration_promise = promise();
  435. wkof.set_state('wkof.ItemData.registry', 'ready');
  436. setTimeout(check_registration_counter, 1);
  437. registration_timeout = setTimeout(function(){
  438. registration_timeout = undefined;
  439. check_registration_counter(true /* force_ready */);
  440. }, 3000);
  441. return registration_promise;
  442. }
  443.  
  444. //------------------------------
  445. // Request to pause the 'ready' event.
  446. //------------------------------
  447. function pause_ready_event(value) {
  448. if (value === true) {
  449. registration_counter++;
  450. } else {
  451. registration_counter--;
  452. check_registration_counter();
  453. }
  454. }
  455.  
  456. //------------------------------
  457. // If registration is complete or timed out, mark it as resolved.
  458. //------------------------------
  459. function check_registration_counter(force_ready) {
  460. if (!force_ready && registration_counter > 0) return false;
  461. if (registration_timeout !== undefined) clearTimeout(registration_timeout);
  462. registration_promise.resolve();
  463. return true;
  464. }
  465.  
  466. //------------------------------
  467. // Notify listeners that we are ready.
  468. //------------------------------
  469. function notify_ready() {
  470. // Delay guarantees include() callbacks are called before ready() callbacks.
  471. setTimeout(function(){wkof.set_state('wkof.ItemData', 'ready');},0);
  472. }
  473. wkof.include('Apiv2');
  474. wkof.ready('Apiv2').then(call_for_registration).then(notify_ready);
  475.  
  476. })(this);