Wanikani Open Framework - ItemData module

ItemData module for Wanikani Open Framework

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

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.cn-greasyfork.org/scripts/38580/261382/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.2
  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. };
  25. //########################################################################
  26.  
  27. function promise(){var a,b,c=new Promise(function(d,e){a=d;b=e;});c.resolve=a;c.reject=b;return c;}
  28. function split_list(str) {return str.replace(/^\s+|\s*(,)\s*|\s+$/g, '$1').split(',').filter(function(name) {return (name.length > 0);});}
  29.  
  30. //------------------------------
  31. // Get the items specified by the configuration.
  32. //------------------------------
  33. function get_items(config, global_options) {
  34. // Default to WK 'subjects' only.
  35. if (!config) config = {wk_items:{}};
  36.  
  37. // Allow comma-separated list of WK-only endpoints.
  38. if (typeof config === 'string') {
  39. var endpoints = split_list(config)
  40. var config = {wk_items:{options:{}}};
  41. for (var idx in endpoints)
  42. config.wk_items.options[endpoints[idx]] = true;
  43. }
  44.  
  45. // Fetch the requested endpoints.
  46. var fetch_promise = promise();
  47. var items = [];
  48. var remaining = 0;
  49. for (var cfg_name in config) {
  50. var cfg = config[cfg_name];
  51. var spec = wkof.ItemData.registry.sources[cfg_name];
  52. if (!spec || typeof spec.fetcher !== 'function') {
  53. console.log('wkof.ItemData.get_items() - Config "'+cfg_name+'" not registered!');
  54. continue;
  55. }
  56. remaining++;
  57. spec.fetcher(cfg, global_options)
  58. .then(function(data){
  59. if (typeof spec === 'object')
  60. data = apply_filters(data, cfg, spec);
  61. items = items.concat(data);
  62. remaining--;
  63. if (!remaining) fetch_promise.resolve(items);
  64. })
  65. .catch(function(e){
  66. if (e) throw e;
  67. console.log('wkof.ItemData.get_items() - Failed for config "'+cfg_name+'"');
  68. remaining--;
  69. if (!remaining) fetch_promise.resolve(items);
  70. });
  71. }
  72. if (remaining === 0) fetch_promise.resolve(items);
  73. return fetch_promise;
  74. }
  75.  
  76. //------------------------------
  77. // Get the wk_items specified by the configuration.
  78. //------------------------------
  79. function get_wk_items(config, options) {
  80. var cfg_options = config.options || {};
  81. options = options || {};
  82. var now = new Date().getTime();
  83.  
  84. // Endpoints that we can fetch (subjects MUST BE FIRST!!)
  85. var available_endpoints = ['subjects','assignments','review_statistics','study_materials'];
  86. var spec = wkof.ItemData.registry.sources.wk_items;
  87. for (var filter_name in config.filters) {
  88. var filter_spec = spec.filters[filter_name];
  89. if (!filter_spec || typeof filter_spec.set_options !== 'function') continue;
  90. var filter_cfg = config.filters[filter_name];
  91. filter_spec.set_options(options, filter_cfg.value);
  92. }
  93.  
  94. // Fetch all of the endpoints
  95. var ep_promises = [];
  96. for (var idx in available_endpoints) {
  97. var ep_name = available_endpoints[idx];
  98. if (ep_name === 'subjects' || cfg_options[ep_name] === true)
  99. ep_promises.push(
  100. wkof.Apiv2.get_endpoint(ep_name, options)
  101. .then(process_data.bind(null, ep_name))
  102. );
  103. }
  104. return Promise.all(ep_promises)
  105. .then(function(all_data){
  106. return all_data[0];
  107. });
  108.  
  109. //============
  110. function process_data(ep_name, ep_data) {
  111. if (ep_name === 'subjects') return ep_data;
  112. // Merge with 'subjects' when 'subjects' is done fetching.
  113. return ep_promises[0].then(cross_link.bind(null, ep_name, ep_data));
  114. }
  115.  
  116. //============
  117. function cross_link(ep_name, ep_data, subjects) {
  118. for (var id in ep_data) {
  119. var record = ep_data[id];
  120. var subject_id = record.data.subject_id;
  121. subjects[subject_id][ep_name] = record.data;
  122. }
  123. }
  124. }
  125.  
  126. //------------------------------
  127. // Filter the items array according to the specified filters and options.
  128. //------------------------------
  129. function apply_filters(items, config, spec) {
  130. var options = config.options || {};
  131. var filters = [];
  132. for (var filter_name in config.filters) {
  133. var filter_cfg = config.filters[filter_name];
  134. if (typeof filter_cfg !== 'object' || filter_cfg.value === undefined)
  135. filter_cfg = {value:filter_cfg};
  136. var filter_value = filter_cfg.value;
  137. var filter_spec = spec.filters[filter_name];
  138. if (filter_spec === undefined) throw new Error('wkof.ItemData.get_item() - Invalid filter "'+filter_name+'"');
  139. if (typeof filter_spec.filter_func !== 'function' ||
  140. (typeof filter_spec.option_req === 'function' && filter_spec.option_req(options) !== true))
  141. continue;
  142. if (typeof filter_spec.filter_value_map === 'function')
  143. filter_value = filter_spec.filter_value_map(filter_cfg.value);
  144. filters.push({
  145. name: filter_name,
  146. func: filter_spec.filter_func,
  147. filter_value: filter_value,
  148. invert: (filter_cfg.invert === true)
  149. });
  150. }
  151. var result = [];
  152. for (var item_idx in items) {
  153. var keep = true;
  154. var item = items[item_idx];
  155. for (var filter_idx in filters) {
  156. var filter = filters[filter_idx];
  157. try {
  158. keep = filter.func(filter.filter_value, item);
  159. if (filter.invert) keep = !keep;
  160. if (!keep) break;
  161. } catch(e) {
  162. keep = false;
  163. break;
  164. }
  165. }
  166. if (keep) result.push(item);
  167. }
  168. return result;
  169. }
  170.  
  171. //------------------------------
  172. // Return the items indexed by an indexing function.
  173. //------------------------------
  174. function get_index(items, index_name) {
  175. var index_func = wkof.ItemData.registry.indices[index_name];
  176. if (typeof index_func !== 'function') throw new Error('wkof.ItemData.index_by() - Invalid index function "'+index_name+'"');
  177. return index_func(items);
  178. }
  179.  
  180. //------------------------------
  181. // Register wk_items data source.
  182. //------------------------------
  183. wkof.ItemData.registry.sources['wk_items'] = {
  184. description: 'Wanikani',
  185. fetcher: get_wk_items,
  186. options: {
  187. assignments: {
  188. type: 'checkbox',
  189. label: 'Assignments',
  190. default: false,
  191. hover_tip: 'Include the "/assignments" endpoint (SRS status, burn status, progress dates)'
  192. },
  193. review_statistics: {
  194. type: 'checkbox',
  195. label: 'Review Statistics',
  196. default: false,
  197. hover_tip: 'Include the "/review_statistics" endpoint:\n * Per-item review count\n *Correct/incorrect count\n * Longest streak'
  198. },
  199. study_materials: {
  200. type: 'checkbox',
  201. label: 'Study Materials',
  202. default: false,
  203. hover_tip: 'Include the "/study_materials" endpoint:\n * User synonyms\n * User notes'
  204. },
  205. },
  206. filters: {
  207. item_type: {
  208. type: 'multi',
  209. label: 'Item type',
  210. content: {radical:'Radicals',kanji:'Kanji',vocabulary:'Vocabulary'},
  211. default: [],
  212. filter_value_map: item_type_to_arr,
  213. filter_func: function(filter_value, item){return filter_value[item.object] === true;},
  214. hover_tip: 'Filter by item type (radical, kanji, vocabulary)',
  215. },
  216. level: {
  217. type: 'text',
  218. label: 'Level',
  219. placeholder: '(e.g. "1-3,5")',
  220. default: '',
  221. filter_value_map: levels_to_arr,
  222. filter_func: function(filter_value, item){return filter_value[item.data.level] === true;},
  223. 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)',
  224. },
  225. srs: {
  226. type: 'multi',
  227. label: 'SRS Level',
  228. 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'},
  229. default: [],
  230. set_options: function(options){options.assignments = true;},
  231. filter_value_map: srs_to_arr,
  232. filter_func: function(filter_value, item){return filter_value[item.assignments.srs_stage] === true;},
  233. hover_tip: 'Filter by SRS level (Apprentice 1, Apprentice 2, ..., Burn)',
  234. },
  235. have_burned: {
  236. type: 'checkbox',
  237. label: 'Have burned',
  238. default: true,
  239. set_options: function(options){options.assignments = true;},
  240. filter_func: function(filter_value, item){return (item.assignments.burned_at !== null) === filter_value;},
  241. 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',
  242. },
  243. }
  244. };
  245.  
  246. //------------------------------
  247. // Macro to build a function to index by a specific field.
  248. // Set make_subarrays to true if more than one item can share the same field value (e.g. same item_type).
  249. //------------------------------
  250. function make_index_func(name, field, entry_type) {
  251. var fn = '';
  252. fn +=
  253. 'var index = {}, value;\n'+
  254. 'for (var idx in items) {\n'+
  255. ' var item = items[idx];\n'+
  256. ' try {\n'+
  257. ' value = '+field+';\n'+
  258. ' } catch(e) {continue;}\n'+
  259. ' if (value === null || value === undefined) continue;\n';
  260. if (entry_type === 'array') {
  261. fn +=
  262. ' if (index[value] === undefined) {\n'+
  263. ' index[value] = [item];\n'+
  264. ' continue;\n'+
  265. ' }\n';
  266. } else {
  267. fn +=
  268. ' if (index[value] === undefined) {\n'+
  269. ' index[value] = item;\n'+
  270. ' continue;\n'+
  271. ' }\n';
  272. if (entry_type === 'single_or_array') {
  273. fn +=
  274. ' if (!Array.isArray(index[value]))\n'+
  275. ' index[value] = [index[value]];\n';
  276. }
  277. }
  278. fn +=
  279. ' index[value].push(item);\n'+
  280. '}\n'+
  281. 'return index;'
  282. wkof.ItemData.registry.indices[name] = new Function('items', fn);
  283. }
  284.  
  285. // Build some index functions.
  286. make_index_func('item_type', 'item.object', 'array');
  287. make_index_func('level', 'item.data.level', 'array');
  288. make_index_func('slug', 'item.data.slug', 'single_or_array');
  289. make_index_func('srs_stage', 'item.assignments.srs_stage', 'array');
  290. make_index_func('srs_stage_name', 'item.assignments.srs_stage_name', 'array');
  291. make_index_func('subject_id', 'item.id', 'single');
  292.  
  293. //------------------------------
  294. // Index by reading
  295. //------------------------------
  296. wkof.ItemData.registry.indices['reading'] = function(items) {
  297. var index = {};
  298. for (var idx in items) {
  299. var item = items[idx];
  300. if (!item.hasOwnProperty('data') || !item.data.hasOwnProperty('readings')) continue;
  301. if (!Array.isArray(item.data.readings)) continue;
  302. var readings = item.data.readings;
  303. for (var idx2 in readings) {
  304. var reading = readings[idx2].reading;
  305. if (reading === 'None') continue;
  306. if (!index[reading]) index[reading] = [];
  307. index[reading].push(item);
  308. }
  309. }
  310. return index;
  311. }
  312.  
  313. //------------------------------
  314. // Given an array of item type criteria (e.g. ['rad', 'kan', 'voc']), return
  315. // an array containing 'true' for each item type contained in the criteria.
  316. //------------------------------
  317. function item_type_to_arr(filter_value) {
  318. if (typeof filter_value === 'string') {
  319. if (filter_value.indexOf(',') >= 0) {
  320. filter_value = split_list(filter_value);
  321. } else {
  322. filter_value = [filter_value];
  323. }
  324. }
  325. return {
  326. radical: (filter_value.indexOf('rad') >= 0),
  327. kanji: (filter_value.indexOf('kan') >= 0),
  328. vocabulary: (filter_value.indexOf('voc') >= 0)
  329. }
  330. }
  331.  
  332. //------------------------------
  333. // Given an array of srs criteria (e.g. ['mast', 'enli', 'burn']), return an
  334. // array containing 'true' for each srs level contained in the criteria.
  335. //------------------------------
  336. function srs_to_arr(filter_value) {
  337. if (typeof filter_value === 'string') {
  338. if (filter_value.indexOf(',') >= 0) {
  339. filter_value = split_list(filter_value);
  340. } else {
  341. filter_value = [filter_value];
  342. }
  343. }
  344. return ['init','appr1','appr2','appr3','appr4','guru1','guru2','mast','enli','burn']
  345. .map(function(name){
  346. return filter_value.indexOf(name) >= 0;
  347. });
  348. }
  349.  
  350. //------------------------------
  351. // Given an level criteria string (e.g. '1-3,5,8'), return an array containing
  352. // 'true' for each level contained in the criteria.
  353. //------------------------------
  354. function levels_to_arr(filter_value) {
  355. var levels = [], crit_idx, start, stop, lvl;
  356.  
  357. // Process each comma-separated criteria separately.
  358. var criteria = filter_value.split(',');
  359. for (crit_idx = 0; crit_idx < criteria.length; crit_idx++) {
  360. var crit = criteria[crit_idx];
  361. var value = true;
  362.  
  363. // Match '*' = all levels
  364. var match = crit.match(/^\s*(\*)\s*$/);
  365. if (match !== null) {
  366. start = to_num('1');
  367. stop = to_num('9999'); // All levels
  368. for (lvl = start; lvl <= stop; lvl++)
  369. levels[lvl] = value;
  370. continue;
  371. }
  372.  
  373. // Match 'a-b' = range of levels (or exclude if preceded by '!')
  374. match = crit.match(/^\s*(\!?)\s*((\+|-)?\d+)\s*-\s*((\+|-)?\d+)\s*$/);
  375. if (match !== null) {
  376. start = to_num(match[2]);
  377. stop = to_num(match[4]);
  378. if (match[1] === '!') value = false;
  379. for (lvl = start; lvl <= stop; lvl++)
  380. levels[lvl] = value;
  381. continue;
  382. }
  383.  
  384. // Match 'a' = specific level (or exclude if preceded by '!')
  385. match = crit.match(/^\s*(\!?)\s*((\+|-)?\d+)\s*$/);
  386. if (match !== null) {
  387. lvl = to_num(match[2]);
  388. if (match[1] === '!') value = false;
  389. levels[lvl] = value;
  390. continue;
  391. }
  392. var err = 'wkof.ItemData::levels_to_arr() - Bad filter criteria "'+filter_value+'"';
  393. console.log(err);
  394. throw err;
  395. }
  396. return levels;
  397.  
  398. //============
  399. function to_num(num) {
  400. num = (num[0] < '0' ? wkof.user.level : 0) + Number(num)
  401. return Math.min(Math.max(1, num), wkof.user.max_level_granted_by_subscription);
  402. }
  403. }
  404.  
  405. //------------------------------
  406. // Notify listeners that we are ready.
  407. //------------------------------
  408. function notify_ready() {
  409. // Delay guarantees include() callbacks are called before ready() callbacks.
  410. setTimeout(function(){wkof.set_state('wkof.ItemData', 'ready');},0);
  411. }
  412. wkof.include('Apiv2');
  413. wkof.ready('Apiv2').then(notify_ready);
  414.  
  415. })(this);