AtCoder Listing Tasks

「問題」タブをクリックすると、コンテスト内の各問題のページに移動できるドロップダウンリストを表示します。

נכון ליום 16-07-2023. ראה הגרסה האחרונה.

  1. // ==UserScript==
  2. // @name AtCoder Listing Tasks
  3. // @name:en AtCoder Listing Tasks
  4. // @namespace https://github.com/luuguas/AtCoderListingTasks
  5. // @version 1.5.2
  6. // @description 「問題」タブをクリックすると、コンテスト内の各問題のページに移動できるドロップダウンリストを表示します。
  7. // @description:en Click on the "Tasks" tab to open a drop-down list that takes you to the page for each problem in the contest.
  8. // @author luuguas
  9. // @license Apache-2.0
  10. // @supportURL https://github.com/luuguas/AtCoderListingTasks/issues
  11. // @match https://atcoder.jp/contests/*
  12. // @exclude https://atcoder.jp/contests/
  13. // @exclude https://atcoder.jp/contests/?*
  14. // @exclude https://atcoder.jp/contests/archive*
  15. // @grant none
  16. // ==/UserScript==
  17.  
  18. (function () {
  19. 'use strict';
  20.  
  21. //AtCoderに標準で読み込まれているjQueryを使用
  22. let $ = window.jQuery;
  23.  
  24. const CONTEST_URL = 'https://atcoder.jp/contests';
  25. const ID_PREFIX = 'userscript-ACLT';
  26. const PRE = 'ACLT';
  27. const CONTEST_REGULAR = ['abc', 'arc', 'agc', 'ahc', 'past', 'joi', 'jag'];
  28. const CONTEST_PERMANENT = ['practice', 'APG4b', 'abs', 'practice2', 'typical90', 'math-and-algorithm', 'tessoku-book'];
  29. const ATONCE_TAB_MAX = 20;
  30.  
  31. const CSS = `
  32. .${PRE}-dropdown {
  33. max-height: 890%;
  34. overflow: visible auto;
  35. }
  36. .${PRE}-label {
  37. width: 100%;
  38. margin: 0px;
  39. padding: 3px 10px;
  40. clear: both;
  41. font-weight: normal;
  42. white-space: nowrap;
  43. }
  44. .${PRE}-label:hover {
  45. background-color: #f5f5f5;
  46. }
  47. .${PRE}-checkbox {
  48. margin: 0px !important;
  49. vertical-align: middle;
  50. }
  51.  
  52. .${PRE}-option {
  53. margin: 5px 0px 15px 10px;
  54. }
  55. .${PRE}-flex {
  56. display: flex;
  57. align-items: center;
  58. }
  59. .${PRE}-select-all {
  60. height: 30px;
  61. }
  62. .${PRE}-select-specify {
  63. height: 35px;
  64. }
  65. .${PRE}-radio {
  66. padding-right: 15px;
  67. }
  68. .${PRE}-disabled {
  69. opacity: 0.65;
  70. }
  71. .${PRE}-caution {
  72. color: red;
  73. }
  74. .${PRE}-toggle {
  75. min-width: 55px;
  76. }
  77. .${PRE}-caret {
  78. margin-left: 5px !important;
  79. }
  80. .${PRE}-list {
  81. max-height: 800%;
  82. overflow: visible auto;
  83. }
  84. .${PRE}-target {
  85. background-color: #e0e0e0;
  86. }
  87. .${PRE}-target:hover {
  88. background-color: #e0e0e0 !important;
  89. }
  90. .${PRE}-between {
  91. padding: 0px 5px;
  92. }
  93. `;
  94. const TEXT = {
  95. newTab: { 'ja': '新しいタブで開く', 'en': 'Open in a new tab' },
  96. taskTable: { 'ja': '問題一覧', 'en': 'Task Table' },
  97. loadingFailed: { 'ja': '(読み込み失敗)', 'en': '(Loading Failed)' },
  98. atOnce: { 'ja': 'まとめて開く', 'en': 'Open at once' },
  99. modalDiscription: { 'ja': '複数の問題をまとめて開きます。', 'en': 'Open several problems at once.' },
  100. cancel: { 'ja': 'キャンセル', 'en': 'Cancel' },
  101. all: { 'ja': 'すべて', 'en': 'All' },
  102. specify: { 'ja': '範囲を指定', 'en': 'Specify the range' },
  103. caution: { 'ja': `※一度に開くことのできるタブは ${ATONCE_TAB_MAX} 個までです。`, 'en': `*Up to ${ATONCE_TAB_MAX} tabs are allowed to open at once.` },
  104. reverse: { 'ja': '逆順で開く', 'en': 'Open in reverse order' },
  105. modalInfo: { 'ja': 'が開きます。(ポップアップがブロックされた場合は許可してください。)', 'en': 'will open. (If pop-ups are blocked, please allow them.)' },
  106. aTab: { 'ja': '個のタブ', 'en': 'tab ' },
  107. tabs: { 'ja': '個のタブ', 'en': 'tabs ' },
  108. };
  109.  
  110. const DB_NAME = 'UserScript_ACLT_Database';
  111. const DB_VERSION = 1;
  112. const STORE_NAME = { option: 'option', problemList: 'problemList' };
  113. const STORE_INFO = [{ storeName: STORE_NAME.option, keyPath: 'name' }, { storeName: STORE_NAME.problemList, keyPath: 'contestName' }];
  114.  
  115. const REMOVE_INTERVAL = 1 * 60 * 60 * 1000; //1時間
  116. const REMOVE_BASE = 10 * 24 * 60 * 60 * 1000; //10日
  117. const ACCESS_INTERVAL = 5 * 60 * 1000; //5分
  118.  
  119. /*IndexedDBを扱うクラス
  120. https://github.com/luuguas/IndexedDBManager */
  121. let IDBManager = function (databaseName) { this.database = null; this.databaseName = databaseName; };
  122. IDBManager.prototype = {
  123. openDatabase(storeInfos, version) {
  124. return new Promise((resolve, reject) => {
  125. if (this.database !== null) { resolve(null); return; }
  126. if (typeof window.indexedDB === 'undefined') { reject('IndexedDB is not supported.'); return; }
  127. let openRequest = window.indexedDB.open(this.databaseName, version);
  128. openRequest.onupgradeneeded = (event) => {
  129. let database = event.target.result;
  130. let m = new Map();
  131. for (let name of database.objectStoreNames) m.set(name, { status: 1, keyPath: null });
  132. for (let info of storeInfos) {
  133. if (m.get(info.storeName)) m.set(info.storeName, { status: 2, keyPath: info.keyPath });
  134. else m.set(info.storeName, { status: 0, keyPath: info.keyPath });
  135. }
  136. for (let [name, info] of m) {
  137. if (info.status === 0) database.createObjectStore(name, { keyPath: info.keyPath });
  138. else if (info.status === 1) database.deleteObjectStore(name);
  139. }
  140. console.info('Database was created or upgraded.');
  141. };
  142. openRequest.onerror = (event) => { this.database = null; reject(`Failed to get database. (${event.target.error})`); };
  143. openRequest.onsuccess = (event) => { this.database = event.target.result; resolve(null); };
  144. });
  145. },
  146. isOpened() { return this.database !== null; },
  147. getData(storeName, key) {
  148. return new Promise((resolve, reject) => {
  149. if (!this.isOpened()) { reject('Database is not loaded.'); return; }
  150. let trans = this.database.transaction(storeName, 'readonly');
  151. let getRequest = trans.objectStore(storeName).get(key);
  152. getRequest.onerror = (event) => { reject(`Failed to get data. (${event.target.error})`); };
  153. getRequest.onsuccess = (event) => {
  154. if (event.target.result) resolve(event.target.result);
  155. else resolve(null);
  156. };
  157. });
  158. },
  159. getAllMatchedData(storeName, filter) {
  160. return new Promise((resolve, reject) => {
  161. if (!this.isOpened()) { reject('Database is not loaded.'); return; }
  162. let trans = this.database.transaction(storeName, 'readonly');
  163. let cursorRequest = trans.objectStore(storeName).openCursor();
  164. let res = [];
  165. cursorRequest.onerror = (event) => { reject(`Failed to get cursor. (${event.target.error})`); };
  166. cursorRequest.onsuccess = (event) => {
  167. let cursor = event.target.result;
  168. if (cursor) {
  169. if (filter(cursor.value)) res.push(cursor.value);
  170. cursor.continue();
  171. }
  172. else resolve(res);
  173. };
  174. });
  175. },
  176. setData(storeName, data) {
  177. return new Promise((resolve, reject) => {
  178. if (!this.isOpened()) { reject('Database is not loaded.'); return; }
  179. let trans = this.database.transaction(storeName, 'readwrite');
  180. let setRequest = trans.objectStore(storeName).put(data);
  181. setRequest.onerror = (event) => { reject(`Failed to set data. (${event.target.error})`); };
  182. setRequest.onsuccess = (event) => { resolve(null); };
  183. });
  184. },
  185. deleteData(storeName, key) {
  186. return new Promise((resolve, reject) => {
  187. if (!this.isOpened()) { reject('Database is not loaded.'); return; }
  188. let trans = this.database.transaction(storeName, 'readwrite');
  189. let deleteRequest = trans.objectStore(storeName).delete(key);
  190. deleteRequest.onerror = (event) => { reject(`Failed to delete data. (${event.target.error})`); };
  191. deleteRequest.onsuccess = (event) => { resolve(null); };
  192. });
  193. },
  194. };
  195.  
  196. /* 設定や問題リストの読み込み・保存をするクラス */
  197. let Setting = function () {
  198. this.problemList = null;
  199. this.newTab = null;
  200. this.lastRemove = null;
  201. this.reverse = null;
  202. this.atOnceSetting = null;
  203. this.atOnce = {
  204. begin: 0,
  205. end: 0,
  206. };
  207. this.lang = null;
  208. this.contestName = null;
  209. this.contestCategory = null;
  210. this.db = new IDBManager(DB_NAME);
  211. this.dbExists = false;
  212. };
  213. Setting.prototype = {
  214. openDB: async function () {
  215. try {
  216. await this.db.openDatabase(STORE_INFO, DB_VERSION);
  217. }
  218. catch (err) {
  219. console.warn('[AtCoder Listing Tasks] ' + err);
  220. }
  221. this.dbExists = this.db.isOpened();
  222. },
  223. requestList: function (contestName) {
  224. return new Promise((resolve, reject) => {
  225. let xhr = new XMLHttpRequest();
  226. xhr.responseType = 'document';
  227. xhr.onreadystatechange = function () {
  228. if (xhr.readyState === 4) {
  229. if (xhr.status === 200) {
  230. let result = $(xhr.responseXML);
  231. let problem_node = result.find('#contest-nav-tabs + .col-sm-12');
  232. let problem_list = problem_node.find('tbody tr');
  233. //問題リストを抽出して配列に格納
  234. let list = [];
  235. problem_list.each((idx, val) => {
  236. let td = $(val).children('td');
  237. list.push({
  238. url: td[0].firstChild.getAttribute('href'),
  239. diff: td[0].firstChild.textContent,
  240. name: td[1].firstChild.textContent,
  241. });
  242. });
  243. resolve(list);
  244. }
  245. else {
  246. resolve(null);
  247. }
  248. }
  249. };
  250. //https://atcoder.jp/contests/***/tasksのページ情報をリクエスト
  251. xhr.open('GET', `${CONTEST_URL}/${contestName}/tasks`, true);
  252. xhr.send(null);
  253. });
  254. },
  255. loadData: async function () {
  256. if (this.dbExists) {
  257. //データベースから情報を読み込む
  258. let resArray = await Promise.all([
  259. this.db.getData(STORE_NAME.problemList, this.contestName),
  260. this.db.getData(STORE_NAME.option, 'newTab'),
  261. this.db.getData(STORE_NAME.option, 'lastRemove'),
  262. this.db.getData(STORE_NAME.option, 'atOnce'),
  263. this.db.getData(STORE_NAME.option, 'reverse')
  264. ]);
  265. let setTasks = [];
  266. let now = Date.now();
  267. //設定を格納
  268. if (resArray[1] !== null) {
  269. this.newTab = resArray[1].value;
  270. }
  271. else {
  272. this.newTab = false;
  273. setTasks.push(this.db.setData(STORE_NAME.option, { name: 'newTab', value: this.newTab }));
  274. }
  275. if (resArray[2] !== null) {
  276. this.lastRemove = resArray[2].value;
  277. }
  278. else {
  279. this.lastRemove = now;
  280. setTasks.push(this.db.setData(STORE_NAME.option, { name: 'lastRemove', value: this.lastRemove }));
  281. }
  282. if (resArray[3] !== null) {
  283. this.atOnceSetting = resArray[3].value;
  284. }
  285. else {
  286. this.atOnceSetting = {};
  287. setTasks.push(this.db.setData(STORE_NAME.option, { name: 'atOnce', value: {} }));
  288. }
  289. if (resArray[4] !== null) {
  290. this.reverse = resArray[4].value;
  291. }
  292. else {
  293. this.reverse = false;
  294. setTasks.push(this.db.setData(STORE_NAME.option, { name: 'reverse', value: false }));
  295. }
  296. //問題リストを格納
  297. if (resArray[0] !== null) {
  298. this.problemList = resArray[0].list;
  299. //lastAccessが現在時刻からACCESS_INTERVAL以上前なら更新する
  300. if (now - resArray[0].lastAccess >= ACCESS_INTERVAL) {
  301. setTasks.push(this.db.setData(STORE_NAME.problemList, { contestName: this.contestName, list: this.problemList, lastAccess: now }));
  302. }
  303. }
  304. else {
  305. this.problemList = await this.requestList(this.contestName);
  306. if (this.problemList !== null) {
  307. setTasks.push(this.db.setData(STORE_NAME.problemList, { contestName: this.contestName, list: this.problemList, lastAccess: now }));
  308. }
  309. }
  310. //情報を更新
  311. await Promise.all(setTasks);
  312. }
  313. else {
  314. this.problemList = await this.requestList(this.contestName);
  315. this.newTab = false;
  316. this.lastRemove = null;
  317. this.atOnceSetting = {};
  318. this.reverse = false;
  319. }
  320. },
  321. saveData: async function (name, value) {
  322. if (!this.dbExists) {
  323. return;
  324. }
  325. await this.db.setData(STORE_NAME.option, { name, value });
  326. },
  327. removeOldData: async function () {
  328. if (!this.dbExists) {
  329. return;
  330. }
  331. let now = Date.now();
  332. if (now - this.lastRemove < REMOVE_INTERVAL) {
  333. return;
  334. }
  335. //最終アクセスが現在時刻より一定以上前の問題リストを削除する
  336. let oldData = await this.db.getAllMatchedData(STORE_NAME.problemList, (data) => { return now - data.lastAccess >= REMOVE_BASE; });
  337. if (oldData.length !== 0) {
  338. let deleteTasks = [];
  339. for (let data of oldData) {
  340. deleteTasks.push(this.db.deleteData(STORE_NAME.problemList, data.contestName));
  341. }
  342. await Promise.all(deleteTasks);
  343. }
  344. //lastRemoveを更新する
  345. this.lastRemove = now;
  346. await this.db.setData(STORE_NAME.option, { name: 'lastRemove', value: this.lastRemove });
  347. },
  348. getLanguage: function () {
  349. this.lang = 'ja';
  350. let content_language = $('meta[http-equiv="Content-Language"]');
  351. if (content_language.length !== 0 && content_language.attr('content') === 'en') {
  352. this.lang = 'en';
  353. }
  354. },
  355. getContestName: function () {
  356. this.contestName = window.location.href.split('/')[4];
  357. //ハッシュ(#?)があれば取り除く
  358. let hash = this.contestName.search(/[#\?]/);
  359. if (hash !== -1) {
  360. this.contestName = this.contestName.slice(0, hash);
  361. }
  362. },
  363. getContestCategoryAndAtOnce: function () {
  364. if (this.problemList === null) {
  365. return;
  366. }
  367. //コンテストの種類を取得
  368. let got = false;
  369. if (!got) {
  370. for (let category of CONTEST_REGULAR) {
  371. if (this.contestName.startsWith(category)) {
  372. this.contestCategory = category + '-' + (this.problemList.length).toString();
  373. got = true;
  374. break;
  375. }
  376. }
  377. }
  378. if (!got) {
  379. for (let category of CONTEST_PERMANENT) {
  380. if (this.contestName.startsWith(category)) {
  381. this.contestCategory = category;
  382. got = true;
  383. break;
  384. }
  385. }
  386. }
  387. if (!got) {
  388. this.contestCategory = 'other';
  389. }
  390. //atOnceの設定
  391. if (this.atOnceSetting[this.contestCategory]) {
  392. this.atOnce = this.atOnceSetting[this.contestCategory];
  393. }
  394. else {
  395. this.atOnce.begin = 0;
  396. this.atOnce.end = Math.min(ATONCE_TAB_MAX - 1, this.problemList.length - 1);
  397. }
  398. },
  399. };
  400.  
  401. /* DOM操作およびスクリプト全体の動作を管理するクラス */
  402. let Launcher = function () {
  403. this.setting = new Setting();
  404. this.dropdownList = {
  405. begin: null,
  406. end: null,
  407. };
  408. this.listChanged = {
  409. begin: true,
  410. end: true,
  411. };
  412. this.isAll = true;
  413. };
  414. Launcher.prototype = {
  415. loadSetting: async function () {
  416. this.setting.getContestName();
  417. await this.setting.openDB();
  418. await this.setting.loadData();
  419. this.setting.getLanguage();
  420. this.setting.getContestCategoryAndAtOnce();
  421. },
  422. attachId: function () {
  423. let tabs = $('#contest-nav-tabs');
  424. if (tabs.length === 0) {
  425. return false;
  426. }
  427. let tasks_tab = tabs.find('a[href$="tasks"]');
  428. if (tasks_tab.length === 0) {
  429. return false;
  430. }
  431. else {
  432. tasks_tab.attr('id', `${ID_PREFIX}-tab`);
  433. return true;
  434. }
  435. },
  436. addCss: function () {
  437. let style = $('<style>', { id: `${ID_PREFIX}-style`, html: CSS });
  438. $('head').append(style);
  439. },
  440. changeToDropdown: function () {
  441. let tasks_tab = $(`#${ID_PREFIX}-tab`);
  442. tasks_tab.attr({
  443. 'class': 'dropdown-toggle',
  444. 'data-toggle': 'dropdown',
  445. 'href': '#',
  446. 'role': 'button',
  447. 'aria-haspopup': 'true',
  448. 'aria-expanded': 'false',
  449. });
  450. tasks_tab.append($('<span>', { class: 'caret' }));
  451. tasks_tab.parent().append($('<ul>', { class: `dropdown-menu ${PRE}-dropdown` }));
  452. },
  453. addList: function () {
  454. let dropdown_menu = $(`#${ID_PREFIX}-tab`).parent().children('.dropdown-menu');
  455. /* [問題一覧]の追加 */
  456. let task_table = $('<a>', { href: `${CONTEST_URL}/${this.setting.contestName}/tasks` });
  457. task_table.append($('<span>', { class: 'glyphicon glyphicon-list', 'aria-hidden': 'true' }));
  458. task_table.append(document.createTextNode(' ' + TEXT.taskTable[this.setting.lang]));
  459. //チェックボックスにチェックが付いていたら新しいタブで開く
  460. task_table[0].addEventListener('click', { handleEvent: this.changeNewTabAttr, setting: this.setting });
  461. dropdown_menu.append($('<li>').append(task_table));
  462. /* [まとめて開く]の追加 */
  463. if (this.setting.problemList !== null) {
  464. let at_once = $('<a>');
  465. at_once.append($('<span>', { class: 'glyphicon glyphicon-sort-by-attributes-alt', 'aria-hidden': 'true' }));
  466. at_once.append(document.createTextNode(' ' + TEXT.atOnce[this.setting.lang] + '...'));
  467. at_once.on('click', (e) => {
  468. $(`#${ID_PREFIX}-modal`).modal('show');
  469. });
  470. dropdown_menu.append($('<li>').append(at_once));
  471. }
  472. /* [新しいタブで開く]の追加 */
  473. let label = $('<label>', { class: `${PRE}-label` });
  474. label.css('color', task_table.css('color')); //[問題一覧]から色情報を取得
  475. let checkbox = $('<input>', { type: 'checkbox', class: `${PRE}-checkbox` });
  476. //チェックボックスはチェック状態をストレージと同期
  477. checkbox.prop('checked', this.setting.newTab);
  478. checkbox.on('click', (e) => {
  479. this.setting.newTab = e.currentTarget.checked;
  480. if (this.setting.dbExists) {
  481. this.setting.saveData('newTab', this.setting.newTab);
  482. }
  483. });
  484. label.append(checkbox);
  485. label.append(document.createTextNode(' ' + TEXT.newTab[this.setting.lang]));
  486. dropdown_menu.prepend($('<li>').append(label));
  487. //チェックボックスが押された場合はドロップダウンリストを非表示にしない
  488. dropdown_menu.on('click', (e) => {
  489. if (e.target === label[0]) {
  490. e.stopPropagation();
  491. }
  492. });
  493. /* 分割線の追加 */
  494. dropdown_menu.append($('<li>', { class: 'divider' }));
  495. /* 各問題の追加 */
  496. if (this.setting.problemList !== null) {
  497. //リストを追加
  498. for (let data of this.setting.problemList) {
  499. let a = $('<a>', { href: data.url, text: `${data.diff} - ${data.name}` });
  500. //チェックボックスにチェックが付いていたら新しいタブで開く
  501. a[0].addEventListener('click', { handleEvent: this.changeNewTabAttr, setting: this.setting });
  502. dropdown_menu.append($('<li>').append(a));
  503. }
  504. }
  505. else {
  506. //エラー情報を追加
  507. let a = $('<a>', { text: TEXT.loadingFailed[this.setting.lang] });
  508. dropdown_menu.append($('<li>').append(a));
  509. }
  510. },
  511. changeNewTabAttr: function (e) {
  512. let a = e.currentTarget;
  513. if (this.setting.newTab) {
  514. a.target = '_blank';
  515. a.rel = 'noopener noreferrer';
  516. }
  517. else {
  518. a.target = '_self';
  519. a.rel = '';
  520. }
  521. },
  522. addModal: function () {
  523. if (this.setting.problemList === null) {
  524. return;
  525. }
  526. let modal = $('<div>', { id: `${ID_PREFIX}-modal`, class: 'modal fade', tabindex: '-1', role: 'dialog' });
  527. /* header */
  528. let header = $('<div>', { class: 'modal-header' });
  529. let x = $('<button>', { type: 'button', class: 'close', 'data-dismiss': 'modal', 'aria-label': 'Close' });
  530. x.append($('<span>', { 'aria-hidden': true, text: '×' }));
  531. header.append(x);
  532. header.append($('<h4>', { class: 'modal-title', text: TEXT.atOnce[this.setting.lang] }));
  533. /* body */
  534. let body = $('<div>', { class: 'modal-body' });
  535. body.append($('<p>', { text: TEXT.modalDiscription[this.setting.lang] }));
  536. let modalInfo = $('<p>');
  537. let option = $('<div>', { class: `${PRE}-option` });
  538. //ラジオボタン
  539. let all = $('<div>', { class: `${PRE}-flex ${PRE}-select-all` });
  540. let specify = $('<div>', { class: `${PRE}-flex ${PRE}-select-specify` });
  541. let label_all = $('<label>', { class: `${PRE}-label-radio` });
  542. let radio_all = $('<input>', { type: 'radio', name: 'open-type' });
  543. let label_specify = label_all.clone(true);
  544. let radio_specify = radio_all.clone(true);
  545. if (this.setting.atOnce.begin === 0 && this.setting.atOnce.end === this.setting.problemList.length - 1) {
  546. this.isAll = true;
  547. }
  548. else {
  549. this.isAll = false;
  550. }
  551. radio_all.prop('checked', this.isAll);
  552. radio_specify.prop('checked', !this.isAll);
  553. label_all.append(radio_all, document.createTextNode(TEXT.all[this.setting.lang]));
  554. label_specify.append(radio_specify, document.createTextNode(TEXT.specify[this.setting.lang] + ':'));
  555. let caution = $('<span>', { class: `${PRE}-caution` });
  556. if (this.setting.problemList.length > ATONCE_TAB_MAX) {
  557. radio_all.prop('disabled', true);
  558. label_all.addClass(`${PRE}-disabled`);
  559. caution.text(TEXT.caution[this.setting.lang]);
  560. }
  561. all.append($('<div>', { class: `radio ${PRE}-radio` }).append(label_all), caution);
  562. specify.append($('<div>', { class: `radio ${PRE}-radio` }).append(label_specify));
  563. //[範囲を選択]用のドロップダウン
  564. let select_begin = $('<div>', { class: `btn-group` });
  565. let begin_button = $('<button>', { class: `btn btn-default dropdown-toggle ${PRE}-toggle`, 'data-toggle': 'dropdown', 'aria-expanded': 'false', text: 'A', disabled: this.isAll });
  566. begin_button.append($('<span>', { class: `caret ${PRE}-caret` }));
  567. let begin_list = $('<ul>', { class: `dropdown-menu ${PRE}-list` });
  568. $.each(this.setting.problemList, (idx, data) => {
  569. begin_list.append($('<li>').append($('<a>', { text: `${data.diff} - ${data.name}`, 'data-index': (idx).toString() })));
  570. });
  571. select_begin.append(begin_button, begin_list);
  572. let select_end = select_begin.clone(true);
  573. let end_list = select_end.find('ul');
  574. let end_button = select_end.find('button');
  575. let between = $('<span>', { text: '−', class: `${PRE}-between` });
  576. //初期表示の設定
  577. begin_button.html(`${this.setting.problemList[this.setting.atOnce.begin].diff}<span class="caret ${PRE}-caret"></span>`);
  578. end_button.html(`${this.setting.problemList[this.setting.atOnce.end].diff}<span class="caret ${PRE}-caret"></span>`);
  579. this.dropdownList.begin = begin_list.find('a');
  580. this.dropdownList.end = end_list.find('a');
  581. this.dropdownList.begin.eq(this.setting.atOnce.begin).addClass(`${PRE}-target`);
  582. this.dropdownList.end.eq(this.setting.atOnce.end).addClass(`${PRE}-target`);
  583. this.setModalInfo(modalInfo, this.setting, this.isAll);
  584. //ラジオボタンを切り替えたときの動作
  585. radio_all.on('change', (e) => {
  586. this.isAll = true;
  587. begin_button.prop('disabled', true);
  588. end_button.prop('disabled', true);
  589. between.addClass(`${PRE}-disabled`);
  590. this.setModalInfo(modalInfo, this.setting, this.isAll);
  591. });
  592. radio_specify.on('change', (e) => {
  593. this.isAll = false;
  594. begin_button.prop('disabled', false);
  595. end_button.prop('disabled', false);
  596. between.removeClass(`${PRE}-disabled`);
  597. this.setModalInfo(modalInfo, this.setting, this.isAll);
  598. });
  599. //リストを開いたときの動作
  600. select_begin.on('shown.bs.dropdown', (e) => {
  601. if (this.listChanged.begin) {
  602. begin_list.scrollTop(26 * (this.setting.atOnce.begin - 2));
  603. this.listChanged.begin = false;
  604. }
  605. });
  606. select_end.on('shown.bs.dropdown', (e) => {
  607. if (this.listChanged.end) {
  608. end_list.scrollTop(26 * (this.setting.atOnce.end - 2));
  609. this.listChanged.end = false;
  610. }
  611. });
  612. //リストで選択したときの動作
  613. begin_list[0].addEventListener('click', { handleEvent: this.changeRange, that: this, begin_button, end_button, modalInfo, isBegin: true });
  614. end_list[0].addEventListener('click', { handleEvent: this.changeRange, that: this, begin_button, end_button, modalInfo, isBegin: false });
  615. specify.append(select_begin, between, select_end);
  616. //[逆順で開く]チェックボックス
  617. let reverse = $('<div>', { class: 'checkbox' });
  618. let label_reverse = $('<label>');
  619. let check_reverse = $('<input>', { type: 'checkbox', name: 'reverse' });
  620. check_reverse.prop('checked', this.setting.reverse);
  621. check_reverse.on('click', (e) => {
  622. this.setting.reverse = e.currentTarget.checked;
  623. });
  624. label_reverse.append(check_reverse, document.createTextNode(TEXT.reverse[this.setting.lang]));
  625. reverse.append(label_reverse);
  626. //組み立て
  627. option.append(all, specify, reverse);
  628. body.append(option);
  629. body.append(modalInfo);
  630. /* footer */
  631. let footer = $('<div>', { class: 'modal-footer' });
  632. let cancel = $('<button>', { type: 'button', class: 'btn btn-default', 'data-dismiss': 'modal', text: TEXT.cancel[this.setting.lang] });
  633. let open = $('<button>', { type: 'button', class: 'btn btn-primary', text: TEXT.atOnce[this.setting.lang] });
  634. open.on('click', (e) => {
  635. //設定を保存
  636. this.setting.saveData('reverse', this.setting.reverse);
  637. if (this.setting.contestCategory !== 'other') {
  638. this.setting.atOnceSetting[this.setting.contestCategory] = {};
  639. if (this.isAll) {
  640. this.setting.atOnceSetting[this.setting.contestCategory].begin = 0;
  641. this.setting.atOnceSetting[this.setting.contestCategory].end = this.setting.problemList.length - 1;
  642. }
  643. else {
  644. this.setting.atOnceSetting[this.setting.contestCategory] = this.setting.atOnce;
  645. }
  646. this.setting.saveData('atOnce', this.setting.atOnceSetting);
  647. }
  648. //タブを開く
  649. let blank = window.open('about:blank'); //ポップアップブロック用
  650. let idx = null;
  651. if (this.isAll) {
  652. if (!this.setting.reverse) {
  653. idx = 0;
  654. while (idx <= this.setting.problemList.length - 1) {
  655. window.open(this.setting.problemList[idx].url, '_blank', 'noopener, noreferrer');
  656. ++idx;
  657. }
  658. }
  659. else {
  660. idx = this.setting.problemList.length - 1;
  661. while (idx >= 0) {
  662. window.open(this.setting.problemList[idx].url, '_blank', 'noopener, noreferrer');
  663. --idx;
  664. }
  665. }
  666. }
  667. else {
  668. if (!this.setting.reverse) {
  669. idx = this.setting.atOnce.begin;
  670. while (idx <= this.setting.atOnce.end) {
  671. window.open(this.setting.problemList[idx].url, '_blank', 'noopener, noreferrer');
  672. ++idx;
  673. }
  674. }
  675. else {
  676. idx = this.setting.atOnce.end;
  677. while (idx >= this.setting.atOnce.begin) {
  678. window.open(this.setting.problemList[idx].url, '_blank', 'noopener, noreferrer');
  679. --idx;
  680. }
  681. }
  682. }
  683. modal.modal('hide');
  684. blank.close();
  685. });
  686. footer.append(cancel, open);
  687. /* モーダルウィンドウを追加 */
  688. let dialog = $('<div>', { class: 'modal-dialog', role: 'document' });
  689. let content = $('<div>', { class: 'modal-content' });
  690. content.append(header, body, footer);
  691. modal.append(dialog.append(content));
  692. $('#main-div').before(modal);
  693. },
  694. changeRange: function (e) {
  695. if (e.target.tagName !== 'A') {
  696. return;
  697. }
  698. let atOnce = this.that.setting.atOnce;
  699. let idx = Number($(e.target).attr('data-index'));
  700. if (this.isBegin) {
  701. this.that.changeSelect(this.that, this.begin_button, idx, true);
  702. if (atOnce.end < atOnce.begin) {
  703. this.that.changeSelect(this.that, this.end_button, idx, false);
  704. }
  705. else if (atOnce.end >= atOnce.begin + ATONCE_TAB_MAX) {
  706. this.that.changeSelect(this.that, this.end_button, idx + ATONCE_TAB_MAX - 1, false);
  707. }
  708. }
  709. else {
  710. this.that.changeSelect(this.that, this.end_button, idx, false);
  711. if (atOnce.begin > atOnce.end) {
  712. this.that.changeSelect(this.that, this.begin_button, idx, true);
  713. }
  714. if (atOnce.begin <= atOnce.end - ATONCE_TAB_MAX) {
  715. this.that.changeSelect(this.that, this.begin_button, idx - ATONCE_TAB_MAX + 1, true);
  716. }
  717. }
  718. this.that.setModalInfo(this.modalInfo, this.that.setting, this.that.isAll);
  719. },
  720. changeSelect: function (that, button, idx, isBegin) {
  721. let problemList = that.setting.problemList;
  722. let atOnce = that.setting.atOnce;
  723. let dropdownList = that.dropdownList;
  724. if (isBegin) {
  725. dropdownList.begin.eq(atOnce.begin).removeClass(`${PRE}-target`);
  726. atOnce.begin = idx;
  727. dropdownList.begin.eq(idx).addClass(`${PRE}-target`);
  728. that.listChanged.begin = true;
  729. }
  730. else {
  731. dropdownList.end.eq(atOnce.end).removeClass(`${PRE}-target`);
  732. atOnce.end = idx;
  733. dropdownList.end.eq(idx).addClass(`${PRE}-target`);
  734. that.listChanged.end = true;
  735. }
  736. button.html(`${problemList[idx].diff}<span class="caret ${PRE}-caret"></span>`);
  737. },
  738. setModalInfo: function (modalInfo, setting, isAll) {
  739. let text = '';
  740. if (isAll) {
  741. text += (setting.problemList.length).toString();
  742. text += ' ';
  743. if (setting.problemList.length === 1) {
  744. text += TEXT.aTab[setting.lang];
  745. }
  746. else {
  747. text += TEXT.tabs[setting.lang];
  748. }
  749. }
  750. else {
  751. text += (setting.atOnce.end - setting.atOnce.begin + 1).toString();
  752. text += ' ';
  753. if (setting.atOnce.end === setting.atOnce.begin) {
  754. text += TEXT.aTab[setting.lang];
  755. }
  756. else {
  757. text += TEXT.tabs[setting.lang];
  758. }
  759. }
  760. text += TEXT.modalInfo[setting.lang];
  761. modalInfo.text(text);
  762. },
  763. launch: async function () {
  764. let tabExists = this.attachId();
  765. //[問題]タブがない場合は終了
  766. if (!tabExists) {
  767. console.log('[AtCoder Listing Tasks] The "Tasks" tab does not exist.');
  768. return;
  769. }
  770. await this.loadSetting();
  771. this.addCss();
  772. this.changeToDropdown();
  773. this.addList();
  774. this.addModal();
  775. await this.setting.removeOldData();
  776. if (this.setting.problemList !== null) {
  777. console.log('[AtCoder Listing Tasks] Succeeded!');
  778. }
  779. else {
  780. console.warn('[AtCoder Listing Tasks] Failed...');
  781. }
  782. },
  783. };
  784.  
  785. /* スクリプトを実行 */
  786. let launcher = new Launcher();
  787. launcher.launch();
  788.  
  789. })();