Wanikani Open Framework - ItemData module

ItemData module for Wanikani Open Framework

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/38580/265576/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.5
  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. for (var item_idx in items) {
  163. var keep = true;
  164. var item = items[item_idx];
  165. for (var filter_idx in filters) {
  166. var filter = filters[filter_idx];
  167. try {
  168. keep = filter.func(filter.filter_value, item);
  169. if (filter.invert) keep = !keep;
  170. if (!keep) break;
  171. } catch(e) {
  172. keep = false;
  173. break;
  174. }
  175. }
  176. if (keep) result.push(item);
  177. }
  178. return result;
  179. });
  180. }
  181.  
  182. //------------------------------
  183. // Return the items indexed by an indexing function.
  184. //------------------------------
  185. function get_index(items, index_name) {
  186. var index_func = wkof.ItemData.registry.indices[index_name];
  187. if (typeof index_func !== 'function') throw new Error('wkof.ItemData.index_by() - Invalid index function "'+index_name+'"');
  188. return index_func(items);
  189. }
  190.  
  191. //------------------------------
  192. // Register wk_items data source.
  193. //------------------------------
  194. wkof.ItemData.registry.sources['wk_items'] = {
  195. description: 'Wanikani',
  196. fetcher: get_wk_items,
  197. options: {
  198. assignments: {
  199. type: 'checkbox',
  200. label: 'Assignments',
  201. default: false,
  202. hover_tip: 'Include the "/assignments" endpoint (SRS status, burn status, progress dates)'
  203. },
  204. review_statistics: {
  205. type: 'checkbox',
  206. label: 'Review Statistics',
  207. default: false,
  208. hover_tip: 'Include the "/review_statistics" endpoint:\n * Per-item review count\n *Correct/incorrect count\n * Longest streak'
  209. },
  210. study_materials: {
  211. type: 'checkbox',
  212. label: 'Study Materials',
  213. default: false,
  214. hover_tip: 'Include the "/study_materials" endpoint:\n * User synonyms\n * User notes'
  215. },
  216. },
  217. filters: {
  218. item_type: {
  219. type: 'multi',
  220. label: 'Item type',
  221. content: {radical:'Radicals',kanji:'Kanji',vocabulary:'Vocabulary'},
  222. default: [],
  223. filter_value_map: item_type_to_arr,
  224. filter_func: function(filter_value, item){return filter_value[item.object] === true;},
  225. hover_tip: 'Filter by item type (radical, kanji, vocabulary)',
  226. },
  227. level: {
  228. type: 'text',
  229. label: 'Level',
  230. placeholder: '(e.g. "1-3,5")',
  231. default: '',
  232. filter_value_map: levels_to_arr,
  233. filter_func: function(filter_value, item){return filter_value[item.data.level] === true;},
  234. 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)',
  235. },
  236. srs: {
  237. type: 'multi',
  238. label: 'SRS Level',
  239. content: {appr1:'Apprentice 1',appr2:'Apprentice 2',appr3:'Apprentice 3',appr4:'Apprentice 4',guru1:'Guru 1',guru2:'Guru 2',mast:'Master',enli:'Enlightened',burn:'Burned'},
  240. default: [],
  241. set_options: function(options){options.assignments = true;},
  242. filter_value_map: srs_to_arr,
  243. filter_func: function(filter_value, item){return filter_value[item.assignments.srs_stage] === true;},
  244. hover_tip: 'Filter by SRS level (Apprentice 1, Apprentice 2, ..., Burn)',
  245. },
  246. have_burned: {
  247. type: 'checkbox',
  248. label: 'Have burned',
  249. default: true,
  250. set_options: function(options){options.assignments = true;},
  251. filter_func: function(filter_value, item){return (item.assignments.burned_at !== null) === filter_value;},
  252. 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',
  253. },
  254. }
  255. };
  256.  
  257. //------------------------------
  258. // Macro to build a function to index by a specific field.
  259. // Set make_subarrays to true if more than one item can share the same field value (e.g. same item_type).
  260. //------------------------------
  261. function make_index_func(name, field, entry_type) {
  262. var fn = '';
  263. fn +=
  264. 'var index = {}, value;\n'+
  265. 'for (var idx in items) {\n'+
  266. ' var item = items[idx];\n'+
  267. ' try {\n'+
  268. ' value = '+field+';\n'+
  269. ' } catch(e) {continue;}\n'+
  270. ' if (value === null || value === undefined) continue;\n';
  271. if (entry_type === 'array') {
  272. fn +=
  273. ' if (index[value] === undefined) {\n'+
  274. ' index[value] = [item];\n'+
  275. ' continue;\n'+
  276. ' }\n';
  277. } else {
  278. fn +=
  279. ' if (index[value] === undefined) {\n'+
  280. ' index[value] = item;\n'+
  281. ' continue;\n'+
  282. ' }\n';
  283. if (entry_type === 'single_or_array') {
  284. fn +=
  285. ' if (!Array.isArray(index[value]))\n'+
  286. ' index[value] = [index[value]];\n';
  287. }
  288. }
  289. fn +=
  290. ' index[value].push(item);\n'+
  291. '}\n'+
  292. 'return index;'
  293. wkof.ItemData.registry.indices[name] = new Function('items', fn);
  294. }
  295.  
  296. // Build some index functions.
  297. make_index_func('item_type', 'item.object', 'array');
  298. make_index_func('level', 'item.data.level', 'array');
  299. make_index_func('slug', 'item.data.slug', 'single_or_array');
  300. make_index_func('srs_stage', 'item.assignments.srs_stage', 'array');
  301. make_index_func('srs_stage_name', 'item.assignments.srs_stage_name', 'array');
  302. make_index_func('subject_id', 'item.id', 'single');
  303.  
  304. //------------------------------
  305. // Index by reading
  306. //------------------------------
  307. wkof.ItemData.registry.indices['reading'] = function(items) {
  308. var index = {};
  309. for (var idx in items) {
  310. var item = items[idx];
  311. if (!item.hasOwnProperty('data') || !item.data.hasOwnProperty('readings')) continue;
  312. if (!Array.isArray(item.data.readings)) continue;
  313. var readings = item.data.readings;
  314. for (var idx2 in readings) {
  315. var reading = readings[idx2].reading;
  316. if (reading === 'None') continue;
  317. if (!index[reading]) index[reading] = [];
  318. index[reading].push(item);
  319. }
  320. }
  321. return index;
  322. }
  323.  
  324. //------------------------------
  325. // Given an array of item type criteria (e.g. ['rad', 'kan', 'voc']), return
  326. // an array containing 'true' for each item type contained in the criteria.
  327. //------------------------------
  328. function item_type_to_arr(filter_value) {
  329. var xlat = {rad:'radical',kan:'kanji',voc:'vocabulary'};
  330. var arr = {}, value;
  331. if (typeof filter_value === 'string') filter_value = split_list(filter_value);
  332. if (typeof filter_value !== 'object') return {};
  333. if (Array.isArray(filter_value)) {
  334. for (var idx in filter_value) {
  335. value = filter_value[idx];
  336. value = xlat[value] || value;
  337. arr[value] = true;
  338. }
  339. } else {
  340. for (value in filter_value) {
  341. arr[xlat[value] || value] = (filter_value[value] === true);
  342. }
  343. }
  344. return arr;
  345. }
  346.  
  347. //------------------------------
  348. // Given an array of srs criteria (e.g. ['mast', 'enli', 'burn']), return an
  349. // array containing 'true' for each srs level contained in the criteria.
  350. //------------------------------
  351. function srs_to_arr(filter_value) {
  352. var index = ['init','appr1','appr2','appr3','appr4','guru1','guru2','mast','enli','burn'];
  353. var arr = [], value;
  354. if (typeof filter_value === 'string') filter_value = split_list(filter_value);
  355. if (typeof filter_value !== 'object') return {};
  356. if (Array.isArray(filter_value)) {
  357. for (var idx in filter_value) {
  358. value = Number(filter_value[idx]);
  359. if (isNaN(value)) value = index.indexOf(filter_value[idx]);
  360. arr[value] = true;
  361. }
  362. } else {
  363. for (value in filter_value) {
  364. arr[index.indexOf(value)] = (filter_value[value] === true);
  365. }
  366. }
  367. return arr;
  368. }
  369.  
  370. //------------------------------
  371. // Given an level criteria string (e.g. '1-3,5,8'), return an array containing
  372. // 'true' for each level contained in the criteria.
  373. //------------------------------
  374. function levels_to_arr(filter_value) {
  375. var levels = [], crit_idx, start, stop, lvl;
  376.  
  377. // Process each comma-separated criteria separately.
  378. var criteria = filter_value.split(',');
  379. for (crit_idx = 0; crit_idx < criteria.length; crit_idx++) {
  380. var crit = criteria[crit_idx];
  381. var value = true;
  382.  
  383. // Match '*' = all levels
  384. var match = crit.match(/^\s*(\*)\s*$/);
  385. if (match !== null) {
  386. start = to_num('1');
  387. stop = to_num('9999'); // All levels
  388. for (lvl = start; lvl <= stop; lvl++)
  389. levels[lvl] = value;
  390. continue;
  391. }
  392.  
  393. // Match 'a-b' = range of levels (or exclude if preceded by '!')
  394. match = crit.match(/^\s*(\!?)\s*((\+|-)?\d+)\s*-\s*((\+|-)?\d+)\s*$/);
  395. if (match !== null) {
  396. start = to_num(match[2]);
  397. stop = to_num(match[4]);
  398. if (match[1] === '!') value = false;
  399. for (lvl = start; lvl <= stop; lvl++)
  400. levels[lvl] = value;
  401. continue;
  402. }
  403.  
  404. // Match 'a' = specific level (or exclude if preceded by '!')
  405. match = crit.match(/^\s*(\!?)\s*((\+|-)?\d+)\s*$/);
  406. if (match !== null) {
  407. lvl = to_num(match[2]);
  408. if (match[1] === '!') value = false;
  409. levels[lvl] = value;
  410. continue;
  411. }
  412. var err = 'wkof.ItemData::levels_to_arr() - Bad filter criteria "'+filter_value+'"';
  413. console.log(err);
  414. throw err;
  415. }
  416. return levels;
  417.  
  418. //============
  419. function to_num(num) {
  420. num = (num[0] < '0' ? wkof.user.level : 0) + Number(num)
  421. return Math.min(Math.max(1, num), wkof.user.max_level_granted_by_subscription);
  422. }
  423. }
  424.  
  425. var registration_promise;
  426. var registration_timeout;
  427. var registration_counter = 0;
  428. //------------------------------
  429. // Ask clients to add items to the registry.
  430. //------------------------------
  431. function call_for_registration() {
  432. registration_promise = promise();
  433. wkof.trigger('wkof.ItemData.request_registration');
  434. if (!check_registration_counter()) {
  435. registration_timeout = setTimeout(function(){
  436. console.log('Timeout waiting for wkof.ItemData.registry');
  437. registration_timeout = undefined;
  438. check_registration_counter(true /* force_ready */);
  439. }, 3000);
  440. }
  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. console.log('pause_ready_event(true)');
  450. registration_counter++;
  451. } else {
  452. console.log('pause_ready_event(false)');
  453. registration_counter--;
  454. check_registration_counter();
  455. }
  456. }
  457.  
  458. //------------------------------
  459. // If registration is complete or timed out, mark it as resolved.
  460. //------------------------------
  461. function check_registration_counter(force_ready) {
  462. if (!force_ready && registration_counter > 0) return false;
  463. if (registration_timeout !== undefined) clearTimeout(registration_timeout);
  464. registration_promise.resolve();
  465. return true;
  466. }
  467.  
  468. //------------------------------
  469. // Notify listeners that we are ready.
  470. //------------------------------
  471. function notify_ready() {
  472. // Delay guarantees include() callbacks are called before ready() callbacks.
  473. setTimeout(function(){wkof.set_state('wkof.ItemData', 'ready');},0);
  474. }
  475. wkof.include('Apiv2');
  476. wkof.ready('Apiv2').then(call_for_registration).then(notify_ready);
  477.  
  478. })(this);