Wanikani Open Framework - ItemData module

ItemData module for Wanikani Open Framework

当前为 2018-02-17 提交的版本,查看 最新版本

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