comfortable-yukicoder

yukicoder にいくつかの機能を追加します.主に動線を増やします.

ของเมื่อวันที่ 21-08-2021 ดู เวอร์ชันล่าสุด

  1. // ==UserScript==
  2. // @name comfortable-yukicoder
  3. // @namespace iilj
  4. // @version 1.0.0
  5. // @description yukicoder にいくつかの機能を追加します.主に動線を増やします.
  6. // @author iilj
  7. // @license MIT
  8. // @supportURL https://github.com/iilj/comfortable-yukicoder/issues
  9. // @match https://yukicoder.me/contests/*
  10. // @match https://yukicoder.me/contests/*/*
  11. // @match https://yukicoder.me/problems/no/*
  12. // @match https://yukicoder.me/problems/*
  13. // @match https://yukicoder.me/submissions/*
  14. // @grant GM_addStyle
  15. // ==/UserScript==
  16. var css$1 = "div#js-cy-timer {\n position: fixed;\n right: 10px;\n bottom: 10px;\n width: 140px;\n height: 70px;\n margin: 0;\n text-align: center;\n line-height: 20px;\n font-size: 15px;\n z-index: 50;\n border: 7px solid #36353a;\n border-radius: 7px;\n background-color: #bdc4bd;\n padding: 8px 0;\n}";
  17.  
  18. const pad = (num, length = 2) => `00${num}`.slice(-length);
  19. const days = ['日', '月', '火', '水', '木', '金', '土'];
  20. const formatDate = (date, format = '%Y-%m-%d (%a) %H:%M:%S.%f %z') => {
  21. const offset = date.getTimezoneOffset();
  22. const offsetSign = offset < 0 ? '+' : '-';
  23. const offsetHours = Math.floor(Math.abs(offset) / 60);
  24. const offsetMinutes = Math.abs(offset) % 60;
  25. let ret = format.replace(/%Y/g, String(date.getFullYear()));
  26. ret = ret.replace(/%m/g, pad(date.getMonth() + 1));
  27. ret = ret.replace(/%d/g, pad(date.getDate()));
  28. ret = ret.replace(/%a/g, days[date.getDay()]);
  29. ret = ret.replace(/%H/g, pad(date.getHours()));
  30. ret = ret.replace(/%M/g, pad(date.getMinutes()));
  31. ret = ret.replace(/%S/g, pad(date.getSeconds()));
  32. ret = ret.replace(/%f/g, pad(date.getMilliseconds(), 3));
  33. ret = ret.replace(/%z/g, `${offsetSign}${pad(offsetHours)}:${pad(offsetMinutes)}`);
  34. return ret;
  35. };
  36. const formatTime = (hours, minutes, seconds) => {
  37. return `${pad(hours)}:${pad(minutes)}:${pad(seconds)}`;
  38. };
  39.  
  40. const diffMsToString = (diffMs) => {
  41. const diffWholeSecs = Math.ceil(diffMs / 1000);
  42. const diffSecs = diffWholeSecs % 60;
  43. const diffMinutes = Math.floor(diffWholeSecs / 60) % 60;
  44. const diffHours = Math.floor(diffWholeSecs / 3600) % 24;
  45. const diffDate = Math.floor(diffWholeSecs / (3600 * 24));
  46. const diffDateText = diffDate > 0 ? `${diffDate}日と` : '';
  47. return diffDateText + formatTime(diffHours, diffMinutes, diffSecs);
  48. };
  49. class Timer {
  50. constructor() {
  51. GM_addStyle(css$1);
  52. this.element = document.createElement('div');
  53. this.element.id = Timer.ELEMENT_ID;
  54. document.body.appendChild(this.element);
  55. this.top = document.createElement('div');
  56. this.element.appendChild(this.top);
  57. this.bottom = document.createElement('div');
  58. this.element.appendChild(this.bottom);
  59. this.prevSeconds = -1;
  60. this.startDate = undefined;
  61. this.endDate = undefined;
  62. this.intervalID = window.setInterval(() => {
  63. this.updateTime();
  64. }, 100);
  65. }
  66. updateTime() {
  67. const d = new Date();
  68. const seconds = d.getSeconds();
  69. if (seconds === this.prevSeconds)
  70. return;
  71. this.prevSeconds = seconds;
  72. if (this.startDate !== undefined && this.endDate !== undefined) {
  73. if (d < this.startDate) {
  74. this.top.textContent = '開始まであと';
  75. const diffMs = this.startDate.getTime() - d.getTime();
  76. this.bottom.textContent = diffMsToString(diffMs);
  77. }
  78. else if (d < this.endDate) {
  79. this.top.textContent = '残り時間';
  80. const diffMs = this.endDate.getTime() - d.getTime();
  81. this.bottom.textContent = diffMsToString(diffMs);
  82. }
  83. else {
  84. this.top.textContent = formatDate(d, '%Y-%m-%d (%a)');
  85. this.bottom.textContent = formatDate(d, '%H:%M:%S %z');
  86. }
  87. }
  88. else {
  89. this.top.textContent = formatDate(d, '%Y-%m-%d (%a)');
  90. this.bottom.textContent = formatDate(d, '%H:%M:%S %z');
  91. }
  92. }
  93. registerContest(contest) {
  94. this.startDate = new Date(contest.Date);
  95. this.endDate = new Date(contest.EndDate);
  96. }
  97. }
  98. Timer.ELEMENT_ID = 'js-cy-timer';
  99.  
  100. var css = "#toplinks > div#cy-tabs-container > a {\n position: relative;\n background: linear-gradient(to bottom, white 0%, #fff2f3 100%);\n}\n#toplinks > div#cy-tabs-container > a ul.js-cy-contest-problems-ul {\n margin: 0;\n padding: 0;\n list-style-type: none;\n overflow: hidden;\n position: absolute;\n left: 0;\n top: 33px;\n width: max-content;\n min-height: 0;\n height: 0;\n z-index: 3;\n transition: min-height 0.4s;\n}\n#toplinks > div#cy-tabs-container > a ul.js-cy-contest-problems-ul > li > a {\n width: 100%;\n height: 100%;\n display: block;\n margin: 0;\n padding: 0.3rem;\n padding-left: 0.6rem;\n padding-right: 0.6rem;\n font-size: 16px;\n color: #fff;\n line-height: 1.75;\n background-color: #428bca;\n}\n#toplinks > div#cy-tabs-container > a ul.js-cy-contest-problems-ul > li > a:hover {\n background-color: #3071a9;\n}\n#toplinks > div#cy-tabs-container > a:hover {\n opacity: 1;\n}\n#toplinks > div#cy-tabs-container > a:hover ul.js-cy-contest-problems-ul {\n height: auto;\n}";
  101.  
  102. const header = [
  103. 'A',
  104. 'B',
  105. 'C',
  106. 'D',
  107. 'E',
  108. 'F',
  109. 'G',
  110. 'H',
  111. 'I',
  112. 'J',
  113. 'K',
  114. 'L',
  115. 'M',
  116. 'N',
  117. 'O',
  118. 'P',
  119. 'Q',
  120. 'R',
  121. 'S',
  122. 'T',
  123. 'U',
  124. 'V',
  125. 'W',
  126. 'X',
  127. 'Y',
  128. 'Z',
  129. ];
  130. const getHeaderFromNum = (num) => {
  131. const idx = num - 1;
  132. if (idx < header.length) {
  133. return header[idx];
  134. }
  135. else {
  136. const r = idx % header.length;
  137. return getHeaderFromNum(Math.floor(idx / header.length)) + header[r];
  138. }
  139. };
  140. const getHeader = (idx) => getHeaderFromNum(idx + 1);
  141.  
  142. class TopLinksManager {
  143. constructor() {
  144. GM_addStyle(css);
  145. const toplinks = document.querySelector('div#toplinks');
  146. if (toplinks === null) {
  147. throw Error('div#toplinks が見つかりません');
  148. }
  149. this.tabContainer = document.createElement('div');
  150. this.tabContainer.classList.add('left');
  151. this.tabContainer.id = TopLinksManager.TAB_CONTAINER_ID;
  152. toplinks.insertAdjacentElement('beforeend', this.tabContainer);
  153. this.id2element = new Map();
  154. }
  155. initLink(txt, id, href = '#') {
  156. const newtab = document.createElement('a');
  157. newtab.innerText = txt;
  158. newtab.id = id;
  159. newtab.setAttribute('href', href);
  160. this.tabContainer.appendChild(newtab);
  161. this.id2element.set(id, newtab);
  162. return newtab;
  163. }
  164. confirmLink(id, href) {
  165. const tab = this.id2element.get(id);
  166. if (tab === undefined) {
  167. throw new Error(`不明な id: ${id}`);
  168. }
  169. tab.href = href;
  170. }
  171. initContestSubmissions() {
  172. this.initLink('自分の提出', TopLinksManager.ID_CONTEST_SUBMISSION);
  173. }
  174. confirmContestSubmissions(contestId) {
  175. this.confirmLink(TopLinksManager.ID_CONTEST_SUBMISSION, `/contests/${contestId}/submissions?my_submission=enabled`);
  176. }
  177. initContestProblems() {
  178. this.initLink('コンテスト問題一覧', TopLinksManager.ID_CONTEST);
  179. }
  180. confirmContestProblems(contestId, contestProblems) {
  181. this.confirmLink(TopLinksManager.ID_CONTEST, `/contests/${contestId}`);
  182. this.addContestProblems(contestProblems);
  183. }
  184. initContestLinks() {
  185. this.initContestProblems();
  186. this.initLink('コンテスト順位表', TopLinksManager.ID_CONTEST_TABLE);
  187. this.initContestSubmissions();
  188. }
  189. confirmContestLinks(contestId, contestProblems) {
  190. this.confirmLink(TopLinksManager.ID_CONTEST_TABLE, `/contests/${contestId}/table`);
  191. this.confirmContestSubmissions(contestId);
  192. this.confirmContestProblems(contestId, contestProblems);
  193. }
  194. addContestProblems(contestProblems) {
  195. const tab = this.id2element.get(TopLinksManager.ID_CONTEST);
  196. if (tab === undefined) {
  197. throw new Error(`id=${TopLinksManager.ID_CONTEST} の要素が追加される前に更新が要求されました`);
  198. }
  199. const ul = document.createElement('ul');
  200. ul.classList.add('js-cy-contest-problems-ul');
  201. console.log(contestProblems);
  202. contestProblems.forEach((problem, index) => {
  203. console.log(problem);
  204. const li = document.createElement('li');
  205. const link = document.createElement('a');
  206. const header = getHeader(index);
  207. link.textContent = `${header} - ${problem.Title}`;
  208. if (problem.No !== null) {
  209. link.href = `/problems/no/${problem.No}`;
  210. }
  211. else {
  212. link.href = `/problems/${problem.ProblemId}`;
  213. }
  214. li.appendChild(link);
  215. ul.appendChild(li);
  216. });
  217. // add caret
  218. const caret = document.createElement('span');
  219. caret.classList.add('caret');
  220. tab.appendChild(caret);
  221. tab.insertAdjacentElement('beforeend', ul);
  222. }
  223. confirmWithoutContest(problem) {
  224. [TopLinksManager.ID_CONTEST, TopLinksManager.ID_CONTEST_TABLE].forEach((id) => {
  225. const tab = this.id2element.get(id);
  226. if (tab !== undefined)
  227. tab.remove();
  228. });
  229. // https://yukicoder.me/problems/no/5000/submissions?my_submission=enabled
  230. if (problem.No !== null) {
  231. this.confirmLink(TopLinksManager.ID_CONTEST_SUBMISSION, `/problems/no/${problem.No}/submissions?my_submission=enabled`);
  232. }
  233. else {
  234. this.confirmLink(TopLinksManager.ID_CONTEST_SUBMISSION, `/problems/${problem.ProblemId}/submissions?my_submission=enabled`);
  235. }
  236. }
  237. }
  238. TopLinksManager.TAB_CONTAINER_ID = 'cy-tabs-container';
  239. TopLinksManager.ID_CONTEST = 'js-cy-contest';
  240. TopLinksManager.ID_CONTEST_TABLE = 'js-cy-contest-table';
  241. TopLinksManager.ID_CONTEST_SUBMISSION = 'js-cy-contest-submissions';
  242.  
  243. const onContestPage = async (contestId, APIClient) => {
  244. const toplinksManager = new TopLinksManager();
  245. toplinksManager.initContestSubmissions();
  246. toplinksManager.confirmContestSubmissions(contestId);
  247. const timer = new Timer();
  248. const contest = await APIClient.fetchContestById(contestId);
  249. timer.registerContest(contest);
  250. };
  251.  
  252. const getContestProblems = (contest, problems) => {
  253. const pid2problem = new Map();
  254. problems.forEach((problem) => {
  255. pid2problem.set(problem.ProblemId, problem);
  256. });
  257. const contestProblems = contest.ProblemIdList.map((problemId) => {
  258. const problem = pid2problem.get(problemId);
  259. if (problem !== undefined)
  260. return problem;
  261. return {
  262. No: null,
  263. ProblemId: problemId,
  264. Title: '',
  265. AuthorId: -1,
  266. TesterId: -1,
  267. TesterIds: '',
  268. Level: 0,
  269. ProblemType: 0,
  270. Tags: '',
  271. Date: null,
  272. Statistics: {
  273. //
  274. },
  275. };
  276. });
  277. return contestProblems;
  278. };
  279.  
  280. const onLeaderboardPage = async (contestId, APIClient) => {
  281. const myRankTableRow = document.querySelector('table.table tbody tr.my_rank');
  282. if (myRankTableRow !== null) {
  283. const myRankTableRowCloned = myRankTableRow.cloneNode(true);
  284. const tbody = document.querySelector('table.table tbody');
  285. if (tbody === null) {
  286. throw new Error('順位表テーブルが見つかりません');
  287. }
  288. tbody.insertAdjacentElement('afterbegin', myRankTableRowCloned);
  289. // const myRankTableFirstRow: HTMLTableRowElement | null =
  290. // document.querySelector<HTMLTableRowElement>('table.table tbody tr.my_rank');
  291. // myRankTableFirstRow.style.borderBottom = '2px solid #ddd';
  292. myRankTableRowCloned.style.borderBottom = '2px solid #ddd';
  293. }
  294. const toplinksManager = new TopLinksManager();
  295. toplinksManager.initContestProblems();
  296. toplinksManager.initContestSubmissions();
  297. toplinksManager.confirmContestSubmissions(contestId);
  298. const timer = new Timer();
  299. const [problems, contest] = await Promise.all([APIClient.fetchProblems(), APIClient.fetchContestById(contestId)]);
  300. timer.registerContest(contest);
  301. const contestProblems = getContestProblems(contest, problems);
  302. toplinksManager.confirmContestProblems(contest.Id, contestProblems);
  303. };
  304.  
  305. const createCard = () => {
  306. const newdiv = document.createElement('div');
  307. // styling newdiv
  308. newdiv.style.display = 'inline-block';
  309. newdiv.style.borderRadius = '2px';
  310. newdiv.style.padding = '10px';
  311. newdiv.style.margin = '10px 0px';
  312. newdiv.style.border = '1px solid rgb(59, 173, 214)';
  313. newdiv.style.backgroundColor = 'rgba(120, 197, 231, 0.1)';
  314. const newdivWrapper = document.createElement('div');
  315. newdivWrapper.appendChild(newdiv);
  316. return [newdiv, newdivWrapper];
  317. };
  318.  
  319. class ContestInfoCard {
  320. constructor(isProblemPage = true) {
  321. this.isProblemPage = isProblemPage;
  322. const [card, cardWrapper] = createCard();
  323. this.card = card;
  324. {
  325. // create newdiv
  326. this.contestDiv = document.createElement('div');
  327. // add contest info
  328. this.contestLnk = document.createElement('a');
  329. this.contestLnk.innerText = '(fetching contest info...)';
  330. this.contestLnk.href = '#';
  331. this.contestDiv.appendChild(this.contestLnk);
  332. this.contestSuffix = document.createTextNode(` (id=---)`);
  333. this.contestDiv.appendChild(this.contestSuffix);
  334. // add problem info
  335. if (isProblemPage) {
  336. const space = document.createTextNode(` `);
  337. this.contestDiv.appendChild(space);
  338. this.problemLnk = document.createElement('a');
  339. this.problemLnk.innerText = '#?';
  340. this.problemLnk.href = '#';
  341. this.contestDiv.appendChild(this.problemLnk);
  342. this.problemSuffix = document.createTextNode(' (No.---)');
  343. this.contestDiv.appendChild(this.problemSuffix);
  344. }
  345. this.dateDiv = document.createElement('div');
  346. this.dateDiv.textContent = 'xxxx-xx-xx xx:xx:xx 〜 xxxx-xx-xx xx:xx:xx';
  347. // newdiv.innerText = `${contest.Name} (id=${contest.Id}) #${label} (No.${problem.No})`;
  348. card.appendChild(this.contestDiv);
  349. card.appendChild(this.dateDiv);
  350. if (isProblemPage) {
  351. this.prevNextProblemLinks = document.createElement('div');
  352. this.prevNextProblemLinks.textContent = '(情報取得中)';
  353. card.appendChild(this.prevNextProblemLinks);
  354. }
  355. }
  356. const content = document.querySelector('div#content');
  357. if (content === null) {
  358. throw new Error('div#content が見つかりませんでした');
  359. }
  360. content.insertAdjacentElement('afterbegin', cardWrapper);
  361. }
  362. confirmContest(contest) {
  363. this.contestLnk.innerText = `${contest.Name}`;
  364. this.contestLnk.href = `/contests/${contest.Id}`;
  365. this.contestSuffix.textContent = ` (id=${contest.Id})`;
  366. const format = '%Y-%m-%d (%a) %H:%M:%S';
  367. const start = formatDate(new Date(contest.Date), format);
  368. const end = formatDate(new Date(contest.EndDate), format);
  369. this.dateDiv.textContent = `${start} ${end}`;
  370. }
  371. confirmContestAndProblem(contest, problem, suffix = '') {
  372. this.confirmContest(contest);
  373. if (this.isProblemPage) {
  374. if (this.prevNextProblemLinks === undefined) {
  375. throw new ErrorEvent('prevNextProblemLinks が undefined です');
  376. }
  377. if (this.problemLnk === undefined) {
  378. throw new ErrorEvent('problemLnk が undefined です');
  379. }
  380. if (this.problemSuffix === undefined) {
  381. throw new ErrorEvent('problemSuffix が undefined です');
  382. }
  383. const idx = contest.ProblemIdList.findIndex((problemId) => problemId === problem.ProblemId);
  384. const label = getHeader(idx);
  385. this.problemLnk.innerText = `#${label}`;
  386. if (problem.No !== null) {
  387. this.problemLnk.href = `/problems/no/${problem.No}`;
  388. this.problemSuffix.textContent = ` (No.${problem.No})`;
  389. }
  390. else {
  391. this.problemLnk.href = `/problems/${problem.ProblemId}`;
  392. }
  393. this.prevNextProblemLinks.textContent = ' / ';
  394. if (idx > 0) {
  395. // prev
  396. const lnk = document.createElement('a');
  397. lnk.innerText = `←前の問題 (#${getHeader(idx - 1)})`;
  398. lnk.href = `/problems/${contest.ProblemIdList[idx - 1]}${suffix}`;
  399. this.prevNextProblemLinks.insertAdjacentElement('afterbegin', lnk);
  400. }
  401. if (idx + 1 < contest.ProblemIdList.length) {
  402. // next
  403. const lnk = document.createElement('a');
  404. lnk.innerText = `次の問題 (#${getHeader(idx + 1)})→`;
  405. lnk.href = `/problems/${contest.ProblemIdList[idx + 1]}${suffix}`;
  406. this.prevNextProblemLinks.insertAdjacentElement('beforeend', lnk);
  407. }
  408. }
  409. }
  410. confirmContestIsNotFound() {
  411. var _a, _b;
  412. this.contestLnk.remove();
  413. this.contestSuffix.remove();
  414. (_a = this.problemLnk) === null || _a === void 0 ? void 0 : _a.remove();
  415. (_b = this.problemSuffix) === null || _b === void 0 ? void 0 : _b.remove();
  416. this.dateDiv.remove();
  417. if (this.prevNextProblemLinks !== undefined) {
  418. this.prevNextProblemLinks.textContent = '(どのコンテストにも属さない問題です)';
  419. }
  420. }
  421. onProblemFetchFailed() {
  422. this.contestLnk.innerText = '???';
  423. if (this.prevNextProblemLinks !== undefined) {
  424. this.prevNextProblemLinks.textContent = '(情報が取得できませんでした)';
  425. }
  426. }
  427. }
  428.  
  429. const onProblemPage = async (fetchProblem, suffix, APIClient) => {
  430. const toplinksManager = new TopLinksManager();
  431. toplinksManager.initContestLinks();
  432. const contestInfoCard = new ContestInfoCard();
  433. const timer = new Timer();
  434. try {
  435. const [problem, problems, currentContest, pastContest, futureContests] = await Promise.all([
  436. fetchProblem(),
  437. APIClient.fetchProblems(),
  438. APIClient.fetchCurrentContests(),
  439. APIClient.fetchPastContests(),
  440. APIClient.fetchFutureContests(),
  441. ]);
  442. const contests = currentContest.concat(pastContest);
  443. let contest = contests.find((contest) => contest.ProblemIdList.includes(problem.ProblemId));
  444. if (contest === undefined) {
  445. // 未来のコンテストから探してみる
  446. if (problem.ProblemId !== undefined) {
  447. const futureContest = futureContests.find((contest) => contest.ProblemIdList.includes(problem.ProblemId));
  448. if (futureContest !== undefined) {
  449. contest = futureContest;
  450. // print contest info
  451. // contestInfoCard.confirmContestAndProblem(futureContest, problem, suffix);
  452. // return null;
  453. }
  454. else {
  455. contestInfoCard.confirmContestIsNotFound();
  456. toplinksManager.confirmWithoutContest(problem);
  457. return null;
  458. }
  459. }
  460. else {
  461. contestInfoCard.confirmContestIsNotFound();
  462. toplinksManager.confirmWithoutContest(problem);
  463. return null;
  464. }
  465. }
  466. const contestProblems = getContestProblems(contest, problems);
  467. // print contest info
  468. contestInfoCard.confirmContestAndProblem(contest, problem, suffix);
  469. // add tabs
  470. toplinksManager.confirmContestLinks(contest.Id, contestProblems);
  471. timer.registerContest(contest);
  472. return problem;
  473. }
  474. catch (error) {
  475. contestInfoCard.onProblemFetchFailed();
  476. return null;
  477. }
  478. };
  479. const onProblemPageByNo = async (problemNo, suffix, APIClient) => {
  480. return onProblemPage(() => APIClient.fetchProblemByNo(problemNo), suffix, APIClient);
  481. };
  482. const onProblemPageById = async (problemId, suffix, APIClient) => {
  483. return onProblemPage(() => APIClient.fetchProblemById(problemId), suffix, APIClient);
  484. };
  485.  
  486. const anchorToUserID = (anchor) => {
  487. const userLnkMatchArray = /^https:\/\/yukicoder\.me\/users\/(\d+)/.exec(anchor.href);
  488. if (userLnkMatchArray === null)
  489. return -1;
  490. const userId = Number(userLnkMatchArray[1]);
  491. return userId;
  492. };
  493. const colorSubmissionRow = (row, authorId, testerIds, yourId) => {
  494. const userLnk = row.querySelector('td.table_username a');
  495. if (userLnk === null) {
  496. throw new Error('テーブル行内にユーザへのリンクが見つかりませんでした');
  497. }
  498. const userId = anchorToUserID(userLnk);
  499. if (userId === -1)
  500. return;
  501. if (userId === authorId) {
  502. row.style.backgroundColor = 'honeydew';
  503. const label = document.createElement('div');
  504. label.textContent = '[作問者]';
  505. userLnk.insertAdjacentElement('afterend', label);
  506. }
  507. else if (testerIds.includes(userId)) {
  508. row.style.backgroundColor = 'honeydew';
  509. const label = document.createElement('div');
  510. label.textContent = '[テスター]';
  511. userLnk.insertAdjacentElement('afterend', label);
  512. }
  513. if (userId === yourId) {
  514. row.style.backgroundColor = 'aliceblue';
  515. const label = document.createElement('div');
  516. label.textContent = '[あなた]';
  517. userLnk.insertAdjacentElement('afterend', label);
  518. }
  519. };
  520. const getYourUserId = () => {
  521. const yourIdLnk = document.querySelector('#header #usermenu-btn');
  522. if (yourIdLnk === null)
  523. return -1; // ログインしていない場合
  524. return anchorToUserID(yourIdLnk);
  525. };
  526. const onProblemSubmissionsPage = (problem) => {
  527. const yourId = getYourUserId();
  528. const testerIds = problem.TesterIds.split(',').map((testerIdString) => Number(testerIdString));
  529. const rows = document.querySelectorAll('table.table tbody tr');
  530. rows.forEach((row) => {
  531. colorSubmissionRow(row, problem.AuthorId, testerIds, yourId);
  532. });
  533. };
  534. const onContestSubmissionsPage = async (contestId, APIClient) => {
  535. const toplinksManager = new TopLinksManager();
  536. toplinksManager.initContestProblems();
  537. toplinksManager.initContestSubmissions();
  538. const contestInfoCard = new ContestInfoCard(false);
  539. const yourId = getYourUserId();
  540. const [contest, problems] = await Promise.all([APIClient.fetchContestById(contestId), APIClient.fetchProblems()]);
  541. // print contest info
  542. contestInfoCard.confirmContest(contest);
  543. // add tabs
  544. const contestProblems = getContestProblems(contest, problems);
  545. toplinksManager.confirmContestProblems(contest.Id, contestProblems);
  546. toplinksManager.confirmContestSubmissions(contest.Id);
  547. const problemId2Label = contest.ProblemIdList.reduce((curMap, problemId, idx) => curMap.set(problemId, getHeader(idx)), new Map());
  548. const problemNo2ProblemMap = problems.reduce((curMap, problem) => {
  549. if (problem.No !== null)
  550. curMap.set(problem.No, problem);
  551. return curMap;
  552. }, new Map());
  553. // collect problemNos
  554. const rows = document.querySelectorAll('table.table tbody tr');
  555. for (let i = 0; i < rows.length; i++) {
  556. const row = rows[i];
  557. // add label to each problem link
  558. const lnk = row.querySelector('td a[href^="/problems/no/"]');
  559. if (lnk === null) {
  560. throw new Error('テーブル行内に問題へのリンクが見つかりませんでした');
  561. }
  562. const contestSubmissionsPageProblemLnkMatchArray = /^https:\/\/yukicoder\.me\/problems\/no\/(\d+)/.exec(lnk.href);
  563. if (contestSubmissionsPageProblemLnkMatchArray === null) {
  564. throw new Error('テーブル行内に含まれる問題リンク先が不正です');
  565. }
  566. const problemNo = Number(contestSubmissionsPageProblemLnkMatchArray[1]);
  567. if (!problemNo2ProblemMap.has(problemNo)) {
  568. try {
  569. const problem = await APIClient.fetchProblemByNo(problemNo);
  570. problemNo2ProblemMap.set(problemNo, problem);
  571. }
  572. catch (error) {
  573. problemNo2ProblemMap.set(problemNo, null);
  574. }
  575. }
  576. const problem = problemNo2ProblemMap.get(problemNo);
  577. if (problem === null || problem === undefined)
  578. return;
  579. const label = problemId2Label.get(problem.ProblemId);
  580. if (label !== undefined)
  581. lnk.insertAdjacentText('afterbegin', `#${label} `);
  582. // color authors and testers
  583. const testerIds = problem.TesterIds.split(',').map((testerIdString) => Number(testerIdString));
  584. colorSubmissionRow(row, problem.AuthorId, testerIds, yourId);
  585. }
  586. };
  587.  
  588. const SUBMISSION_STATUSES = ['AC', 'WA', 'TLE', '--', 'MLE', 'OLE', 'QLE', 'RE', 'CE', 'IE'];
  589. const stringToStatus = (resultText) => {
  590. for (let i = 0; i < SUBMISSION_STATUSES.length; ++i) {
  591. if (SUBMISSION_STATUSES[i] == resultText)
  592. return SUBMISSION_STATUSES[i];
  593. }
  594. throw new Error(`未知のジャッジステータスです: ${resultText}`);
  595. };
  596. const onSubmissionResultPage = async (APIClient) => {
  597. const toplinksManager = new TopLinksManager();
  598. const contestInfoCard = new ContestInfoCard();
  599. const [resultCard, resultCardWrapper] = createCard();
  600. {
  601. // count
  602. const resultCountMap = SUBMISSION_STATUSES.reduce((prevMap, label) => prevMap.set(label, 0), new Map());
  603. // ジャッジ中(提出直後)は,このテーブルは存在しない
  604. const testTable = document.getElementById('test_table');
  605. if (testTable !== null) {
  606. const results = testTable.querySelectorAll('tbody tr td span.label');
  607. results.forEach((span) => {
  608. var _a;
  609. const resultText = span.textContent;
  610. if (resultText === null) {
  611. throw new Error('ジャッジ結果テキストが空です');
  612. }
  613. const resultLabel = stringToStatus(resultText.trim());
  614. const cnt = (_a = resultCountMap.get(resultLabel)) !== null && _a !== void 0 ? _a : 0;
  615. resultCountMap.set(resultLabel, cnt + 1);
  616. });
  617. }
  618. const content = document.querySelector('div#testcase_table h4');
  619. // 提出直後,ジャッジ中は null
  620. if (content !== null) {
  621. content.insertAdjacentElement('afterend', resultCardWrapper);
  622. // print result
  623. const addResultRow = (cnt, label) => {
  624. const resultEntry = document.createElement('div');
  625. const labelSpan = document.createElement('span');
  626. labelSpan.textContent = label;
  627. labelSpan.classList.add('label');
  628. labelSpan.classList.add(label === 'AC' ? 'label-success' : label === 'IE' ? 'label-danger' : 'label-warning');
  629. resultEntry.appendChild(labelSpan);
  630. const countSpan = document.createTextNode(` × ${cnt}`);
  631. resultEntry.appendChild(countSpan);
  632. resultCard.appendChild(resultEntry);
  633. };
  634. resultCountMap.forEach((cnt, label) => {
  635. if (cnt > 0)
  636. addResultRow(cnt, label);
  637. });
  638. }
  639. }
  640. const lnk = document.querySelector('div#content a[href^="/problems/no/"]');
  641. if (lnk === null) {
  642. throw new Error('結果ページ中に問題ページへのリンクが見つかりませんでした');
  643. }
  644. toplinksManager.initLink('問題', 'js-cy-problem', lnk.href);
  645. toplinksManager.initContestLinks();
  646. const submissionPageProblemLnkMatchArray = /^https:\/\/yukicoder\.me\/problems\/no\/(\d+)/.exec(lnk.href);
  647. if (submissionPageProblemLnkMatchArray === null) {
  648. throw new Error('結果ページに含まれる問題ページへのリンク先が不正です');
  649. }
  650. // get problems/contests info
  651. const problemNo = Number(submissionPageProblemLnkMatchArray[1]);
  652. const [problem, problems, currentContest, pastContest] = await Promise.all([
  653. APIClient.fetchProblemByNo(problemNo),
  654. APIClient.fetchProblems(),
  655. APIClient.fetchCurrentContests(),
  656. APIClient.fetchPastContests(),
  657. ]);
  658. const contests = currentContest.concat(pastContest);
  659. const contest = contests.find((contest) => contest.ProblemIdList.includes(problem.ProblemId));
  660. // add tabs
  661. if (contest !== undefined) {
  662. const contestProblems = getContestProblems(contest, problems);
  663. toplinksManager.confirmContestLinks(contest.Id, contestProblems);
  664. // print contest info
  665. contestInfoCard.confirmContestAndProblem(contest, problem);
  666. }
  667. };
  668.  
  669. const BASE_URL = 'https://yukicoder.me';
  670. const STATIC_API_BASE_URL = `${BASE_URL}/api/v1`;
  671. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  672. const assertResultIsValid = (obj) => {
  673. if ('Message' in obj)
  674. throw new Error(obj.Message);
  675. };
  676. const fetchJson = async (url) => {
  677. const res = await fetch(url);
  678. if (!res.ok) {
  679. throw new Error(res.statusText);
  680. }
  681. const obj = (await res.json());
  682. assertResultIsValid(obj);
  683. return obj;
  684. };
  685. // TODO pid/no->contest, の変換も受け持つほうが良い?(html 解析絡みをこのクラスに隠蔽できる)
  686. // 「現在のコンテスト」
  687. class CachedAPIClient {
  688. constructor() {
  689. this.pastContestsMap = new Map();
  690. this.currentContestsMap = new Map();
  691. this.futureContestsMap = new Map();
  692. this.problemsMapById = new Map();
  693. this.problemsMapByNo = new Map();
  694. }
  695. async fetchPastContests() {
  696. if (this.pastContests === undefined) {
  697. this.pastContests = await fetchJson(`${STATIC_API_BASE_URL}/contest/past`);
  698. this.pastContests.forEach((contest) => {
  699. if (!this.pastContestsMap.has(contest.Id))
  700. this.pastContestsMap.set(contest.Id, contest);
  701. });
  702. }
  703. return this.pastContests;
  704. }
  705. async fetchCurrentContests() {
  706. if (this.currentContests === undefined) {
  707. this.currentContests = await fetchJson(`${STATIC_API_BASE_URL}/contest/current`);
  708. this.currentContests.forEach((contest) => {
  709. if (!this.currentContestsMap.has(contest.Id))
  710. this.currentContestsMap.set(contest.Id, contest);
  711. });
  712. }
  713. return this.currentContests;
  714. }
  715. async fetchFutureContests() {
  716. if (this.futureContests === undefined) {
  717. this.futureContests = await fetchJson(`${STATIC_API_BASE_URL}/contest/future`);
  718. this.futureContests.forEach((contest) => {
  719. if (!this.futureContestsMap.has(contest.Id))
  720. this.futureContestsMap.set(contest.Id, contest);
  721. });
  722. }
  723. return this.futureContests;
  724. }
  725. async fetchContestById(contestId) {
  726. if (this.pastContestsMap.has(contestId)) {
  727. return this.pastContestsMap.get(contestId);
  728. }
  729. if (this.currentContestsMap.has(contestId)) {
  730. return this.currentContestsMap.get(contestId);
  731. }
  732. if (this.futureContestsMap.has(contestId)) {
  733. return this.futureContestsMap.get(contestId);
  734. }
  735. const contest = await fetchJson(`${STATIC_API_BASE_URL}/contest/id/${contestId}`);
  736. const currentDate = new Date();
  737. const startDate = new Date(contest.Date);
  738. const endDate = new Date(contest.EndDate);
  739. if (currentDate > endDate) {
  740. this.pastContestsMap.set(contestId, contest);
  741. }
  742. else if (currentDate > startDate) {
  743. this.currentContestsMap.set(contestId, contest);
  744. }
  745. return contest;
  746. }
  747. async fetchProblems() {
  748. if (this.problems === undefined) {
  749. this.problems = await fetchJson(`${STATIC_API_BASE_URL}/problems`);
  750. this.problems.forEach((problem) => {
  751. if (!this.problemsMapById.has(problem.ProblemId))
  752. this.problemsMapById.set(problem.ProblemId, problem);
  753. if (problem.No !== null && !this.problemsMapByNo.has(problem.No))
  754. this.problemsMapByNo.set(problem.No, problem);
  755. });
  756. }
  757. return this.problems;
  758. }
  759. async fetchProblemById(problemId) {
  760. if (this.problemsMapById.has(problemId)) {
  761. return this.problemsMapById.get(problemId);
  762. }
  763. try {
  764. const problem = await fetchJson(`${STATIC_API_BASE_URL}/problems/${problemId}`);
  765. this.problemsMapById.set(problem.ProblemId, problem);
  766. if (problem.No !== null)
  767. this.problemsMapByNo.set(problem.No, problem);
  768. return problem;
  769. }
  770. catch (_a) {
  771. await this.fetchProblems();
  772. if (this.problemsMapById.has(problemId)) {
  773. return this.problemsMapById.get(problemId);
  774. }
  775. // 問題一覧には載っていない -> 未来のコンテストの問題
  776. // ProblemId なので,未来のコンテスト一覧に載っている pid リストから,
  777. // コンテストは特定可能.
  778. return { ProblemId: problemId, No: null };
  779. }
  780. }
  781. async fetchProblemByNo(problemNo) {
  782. if (this.problemsMapByNo.has(problemNo)) {
  783. return this.problemsMapByNo.get(problemNo);
  784. }
  785. try {
  786. const problem = await fetchJson(`${STATIC_API_BASE_URL}/problems/no/${problemNo}`);
  787. this.problemsMapById.set(problem.ProblemId, problem);
  788. if (problem.No !== null)
  789. this.problemsMapByNo.set(problem.No, problem);
  790. return problem;
  791. }
  792. catch (_a) {
  793. await this.fetchProblems();
  794. if (this.problemsMapByNo.has(problemNo)) {
  795. return this.problemsMapByNo.get(problemNo);
  796. }
  797. // 問題一覧には載っていない -> 未来のコンテストの問題
  798. return { No: problemNo };
  799. }
  800. }
  801. }
  802.  
  803. void (async () => {
  804. const href = location.href;
  805. const hrefMatchArray = /^https:\/\/yukicoder\.me(.+)/.exec(href);
  806. if (hrefMatchArray === null)
  807. return;
  808. const path = hrefMatchArray[1];
  809. const APIClient = new CachedAPIClient();
  810. // on problem page (ProblemNo)
  811. // e.g. https://yukicoder.me/problems/no/1313
  812. const problemPageMatchArray = /^\/problems\/no\/(\d+)(.*)/.exec(path);
  813. if (problemPageMatchArray !== null) {
  814. // get contest info
  815. const problemNo = Number(problemPageMatchArray[1]);
  816. const suffix = problemPageMatchArray[2];
  817. const problem = await onProblemPageByNo(problemNo, suffix, APIClient);
  818. if (problem === null)
  819. return;
  820. const problemSubmissionsPageMatchArray = /^\/problems\/no\/(\d+)\/submissions/.exec(path);
  821. if (problemSubmissionsPageMatchArray !== null) {
  822. onProblemSubmissionsPage(problem);
  823. }
  824. return;
  825. }
  826. // on problem page (ProblemId)
  827. // e.g. https://yukicoder.me/problems/5191
  828. const problemPageByIdMatchArray = /^\/problems\/(\d+)(.*)/.exec(path);
  829. if (problemPageByIdMatchArray !== null) {
  830. // get contest info
  831. const problemId = Number(problemPageByIdMatchArray[1]);
  832. const suffix = problemPageByIdMatchArray[2];
  833. const problem = await onProblemPageById(problemId, suffix, APIClient);
  834. if (problem === null)
  835. return;
  836. const problemSubmissionsPageMatchArray = /^\/problems\/(\d+)\/submissions/.exec(path);
  837. if (problemSubmissionsPageMatchArray !== null) {
  838. onProblemSubmissionsPage(problem);
  839. }
  840. return;
  841. }
  842. // on contest submissions page / statistics page
  843. // e.g. https://yukicoder.me/contests/300/submissions, https://yukicoder.me/contests/300/statistics
  844. const contestSubmissionsPageMatchArray = /^\/contests\/(\d+)\/(submissions|statistics)/.exec(path);
  845. if (contestSubmissionsPageMatchArray !== null) {
  846. const contestId = Number(contestSubmissionsPageMatchArray[1]);
  847. await onContestSubmissionsPage(contestId, APIClient);
  848. return;
  849. }
  850. // on submission result page
  851. // e.g. https://yukicoder.me/submissions/591424
  852. const submissionPageMatchArray = /^\/submissions\/\d+/.exec(path);
  853. if (submissionPageMatchArray !== null) {
  854. await onSubmissionResultPage(APIClient);
  855. return;
  856. }
  857. // on contest leaderboard page
  858. // e.g. https://yukicoder.me/contests/300/table
  859. const leaderboardPageMatchArray = /^\/contests\/(\d+)\/(table|all)/.exec(path);
  860. if (leaderboardPageMatchArray !== null) {
  861. const contestId = Number(leaderboardPageMatchArray[1]);
  862. await onLeaderboardPage(contestId, APIClient);
  863. return;
  864. }
  865. // on contest problem list page
  866. // e.g. https://yukicoder.me/contests/300
  867. const contestPageMatchArray = /^\/contests\/(\d+)$/.exec(path);
  868. if (contestPageMatchArray !== null) {
  869. const contestId = Number(contestPageMatchArray[1]);
  870. await onContestPage(contestId, APIClient);
  871. return;
  872. }
  873. })();