AtCoder Listing Tasks

Click on the "Tasks" tab to open a drop-down list that takes you to the page for each problem in the contest.

As of 2023-07-30. See the latest version.

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