Greasy Fork is available in English.

AtCoder Easy Test v2

Make testing sample cases easy

Od 23.10.2021.. Pogledajte najnovija verzija.

  1. // ==UserScript==
  2. // @name AtCoder Easy Test v2
  3. // @namespace https://atcoder.jp/
  4. // @version 2.5.1
  5. // @description Make testing sample cases easy
  6. // @author magurofly
  7. // @license MIT
  8. // @supportURL https://github.com/magurofly/atcoder-easy-test/
  9. // @match https://atcoder.jp/contests/*/tasks/*
  10. // @match https://yukicoder.me/problems/no/*
  11. // @match http://codeforces.com/contest/*/problem/*
  12. // @match http://codeforces.com/gym/*/problem/*
  13. // @match http://codeforces.com/problemset/problem/*
  14. // @match http://codeforces.com/group/*/contest/*/problem/*
  15. // @match http://*.contest.codeforces.com/group/*/contest/*/problem/*
  16. // @match https://codeforces.com/contest/*/problem/*
  17. // @match https://codeforces.com/gym/*/problem/*
  18. // @match https://codeforces.com/problemset/problem/*
  19. // @match https://codeforces.com/group/*/contest/*/problem/*
  20. // @match https://*.contest.codeforces.com/group/*/contest/*/problem/*
  21. // @grant unsafeWindow
  22. // ==/UserScript==
  23. (function() {
  24. const codeSaver = {
  25. LIMIT: 10,
  26. get() {
  27. // `json` は、ソースコード文字列またはJSON文字列
  28. let json = unsafeWindow.localStorage.AtCoderEasyTest$lastCode;
  29. let data = [];
  30. try {
  31. if (typeof json == "string") {
  32. data.push(...JSON.parse(json));
  33. }
  34. else {
  35. data = [];
  36. }
  37. }
  38. catch (e) {
  39. data.push({
  40. path: unsafeWindow.localStorage.AtCoderEasyTset$lastPage,
  41. code: json,
  42. });
  43. }
  44. return data;
  45. },
  46. set(data) {
  47. unsafeWindow.localStorage.AtCoderEasyTest$lastCode = JSON.stringify(data);
  48. },
  49. save(code) {
  50. let data = codeSaver.get();
  51. const idx = data.findIndex(({ path }) => path == location.pathname);
  52. if (idx != -1)
  53. data.splice(idx, idx + 1);
  54. data.push({
  55. path: location.pathname,
  56. code,
  57. });
  58. while (data.length > codeSaver.LIMIT)
  59. data.shift();
  60. codeSaver.set(data);
  61. },
  62. restore() {
  63. const data = codeSaver.get();
  64. const idx = data.findIndex(({ path }) => path == location.pathname);
  65. if (idx == -1 || !(data[idx] instanceof Object))
  66. return Promise.reject(`No saved code found for ${location.pathname}`);
  67. return Promise.resolve(data[idx].code);
  68. }
  69. };
  70.  
  71. function similarLangs(targetLang, candidateLangs) {
  72. const [targetName, targetDetail] = targetLang.split(" ", 2);
  73. const selectedLangs = candidateLangs.filter(candidateLang => {
  74. const [name, _] = candidateLang.split(" ", 2);
  75. return name == targetName;
  76. }).map(candidateLang => {
  77. const [_, detail] = candidateLang.split(" ", 2);
  78. return [candidateLang, similarity(detail, targetDetail)];
  79. });
  80. return selectedLangs.sort((a, b) => a[1] - b[1]).map(([lang, _]) => lang);
  81. }
  82. function similarity(s, t) {
  83. const n = s.length, m = t.length;
  84. let dp = new Array(m + 1).fill(0);
  85. for (let i = 0; i < n; i++) {
  86. const dp2 = new Array(m + 1).fill(0);
  87. for (let j = 0; j < m; j++) {
  88. const cost = (s.charCodeAt(i) - t.charCodeAt(j)) ** 2;
  89. dp2[j + 1] = Math.min(dp[j] + cost, dp[j + 1] + cost * 0.25, dp2[j] + cost * 0.25);
  90. }
  91. dp = dp2;
  92. }
  93. return dp[m];
  94. }
  95.  
  96. class CodeRunner {
  97. get label() {
  98. return this._label;
  99. }
  100. constructor(label, site) {
  101. this._label = `${label} [${site}]`;
  102. }
  103. async test(sourceCode, input, expectedOutput, options) {
  104. const result = await this.run(sourceCode, input);
  105. if (expectedOutput != null)
  106. result.expectedOutput = expectedOutput;
  107. if (result.status != "OK" || typeof expectedOutput != "string")
  108. return result;
  109. let output = result.output || "";
  110. if (options.trim) {
  111. expectedOutput = expectedOutput.trim();
  112. output = output.trim();
  113. }
  114. let equals = (x, y) => x === y;
  115. if (options.allowableError) {
  116. const floatPattern = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/;
  117. const superEquals = equals;
  118. equals = (x, y) => {
  119. if (floatPattern.test(x) && floatPattern.test(y))
  120. return Math.abs(parseFloat(x) - parseFloat(y)) <= options.allowableError;
  121. return superEquals(x, y);
  122. };
  123. }
  124. if (options.split) {
  125. const superEquals = equals;
  126. equals = (x, y) => {
  127. const xs = x.split(/\s+/);
  128. const ys = y.split(/\s+/);
  129. if (xs.length != ys.length)
  130. return false;
  131. const len = xs.length;
  132. for (let i = 0; i < len; i++) {
  133. if (!superEquals(xs[i], ys[i]))
  134. return false;
  135. }
  136. return true;
  137. };
  138. }
  139. result.status = equals(output, expectedOutput) ? "AC" : "WA";
  140. return result;
  141. }
  142. }
  143.  
  144. class CustomRunner extends CodeRunner {
  145. run;
  146. constructor(label, run) {
  147. super(label, "Browser");
  148. this.run = run;
  149. }
  150. }
  151.  
  152. function buildParams(data) {
  153. return Object.entries(data).map(([key, value]) => encodeURIComponent(key) + "=" + encodeURIComponent(value)).join("&");
  154. }
  155. function sleep(ms) {
  156. return new Promise(done => setTimeout(done, ms));
  157. }
  158. function doneOrFail(p) {
  159. return p.then(() => Promise.resolve(), () => Promise.resolve());
  160. }
  161. function html2element(html) {
  162. const template = document.createElement("template");
  163. template.innerHTML = html;
  164. return template.content.firstChild;
  165. }
  166. function newElement(tagName, attrs = {}) {
  167. const e = document.createElement(tagName);
  168. for (const [key, value] of Object.entries(attrs)) {
  169. e[key] = value;
  170. }
  171. return e;
  172. }
  173. async function loadScript(src, ctx = null, env = {}) {
  174. const js = await fetch(src).then(res => res.text());
  175. const keys = [];
  176. const values = [];
  177. for (const [key, value] of Object.entries(env)) {
  178. keys.push(key);
  179. values.push(value);
  180. }
  181. unsafeWindow["Function"](keys.join(), js).apply(ctx, values);
  182. }
  183. const eventListeners = {};
  184. const events = {
  185. on(name, listener) {
  186. const listeners = (name in eventListeners ? eventListeners[name] : eventListeners[name] = []);
  187. listeners.push(listener);
  188. },
  189. trig(name) {
  190. if (name in eventListeners) {
  191. for (const listener of eventListeners[name])
  192. listener();
  193. }
  194. },
  195. };
  196. class ObservableValue {
  197. _value;
  198. _listeners;
  199. constructor(value) {
  200. this._value = value;
  201. this._listeners = new Set();
  202. }
  203. get value() {
  204. return this._value;
  205. }
  206. set value(value) {
  207. this._value = value;
  208. for (const listener of this._listeners)
  209. listener(value);
  210. }
  211. addListener(listener) {
  212. this._listeners.add(listener);
  213. listener(this._value);
  214. }
  215. removeListener(listener) {
  216. this._listeners.delete(listener);
  217. }
  218. map(f) {
  219. const y = new ObservableValue(f(this.value));
  220. this.addListener(x => {
  221. y.value = f(x);
  222. });
  223. return y;
  224. }
  225. }
  226.  
  227. let waitAtCoderCustomTest = Promise.resolve();
  228. const AtCoderCustomTestBase = location.href.replace(/\/tasks\/.+$/, "/custom_test");
  229. const AtCoderCustomTestResultAPI = AtCoderCustomTestBase + "/json?reload=true";
  230. const AtCoderCustomTestSubmitAPI = AtCoderCustomTestBase + "/submit/json";
  231. class AtCoderRunner extends CodeRunner {
  232. languageId;
  233. constructor(languageId, label) {
  234. super(label, "AtCoder");
  235. this.languageId = languageId;
  236. }
  237. async run(sourceCode, input) {
  238. const promise = this.submit(sourceCode, input);
  239. waitAtCoderCustomTest = promise;
  240. return await promise;
  241. }
  242. async submit(sourceCode, input) {
  243. try {
  244. await waitAtCoderCustomTest;
  245. }
  246. catch (error) {
  247. console.error(error);
  248. }
  249. const error = await fetch(AtCoderCustomTestSubmitAPI, {
  250. method: "POST",
  251. credentials: "include",
  252. headers: {
  253. "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  254. },
  255. body: buildParams({
  256. "data.LanguageId": String(this.languageId),
  257. sourceCode,
  258. input,
  259. csrf_token: unsafeWindow.csrfToken,
  260. }),
  261. }).then(r => r.text());
  262. if (error) {
  263. throw new Error(error);
  264. }
  265. await sleep(100);
  266. for (;;) {
  267. const data = await fetch(AtCoderCustomTestResultAPI, {
  268. method: "GET",
  269. credentials: "include",
  270. }).then(r => r.json());
  271. if (!("Result" in data))
  272. continue;
  273. const result = data.Result;
  274. if ("Interval" in data) {
  275. await sleep(data.Interval);
  276. continue;
  277. }
  278. return {
  279. status: (result.ExitCode == 0) ? "OK" : (result.TimeConsumption == -1) ? "CE" : "RE",
  280. exitCode: result.ExitCode,
  281. execTime: result.TimeConsumption,
  282. memory: result.MemoryConsumption,
  283. input,
  284. output: data.Stdout,
  285. error: data.Stderr,
  286. };
  287. }
  288. }
  289. }
  290.  
  291. class PaizaIORunner extends CodeRunner {
  292. name;
  293. constructor(name, label) {
  294. super(label, "PaizaIO");
  295. this.name = name;
  296. }
  297. async run(sourceCode, input) {
  298. let id, status, error;
  299. try {
  300. const res = await fetch("https://api.paiza.io/runners/create?" + buildParams({
  301. source_code: sourceCode,
  302. language: this.name,
  303. input,
  304. longpoll: "true",
  305. longpoll_timeout: "10",
  306. api_key: "guest",
  307. }), {
  308. method: "POST",
  309. mode: "cors",
  310. }).then(r => r.json());
  311. id = res.id;
  312. status = res.status;
  313. error = res.error;
  314. }
  315. catch (error) {
  316. return {
  317. status: "IE",
  318. input,
  319. error: String(error),
  320. };
  321. }
  322. while (status == "running") {
  323. const res = await fetch("https://api.paiza.io/runners/get_status?" + buildParams({
  324. id,
  325. api_key: "guest",
  326. }), {
  327. mode: "cors",
  328. }).then(res => res.json());
  329. status = res.status;
  330. error = res.error;
  331. }
  332. const res = await fetch("https://api.paiza.io/runners/get_details?" + buildParams({
  333. id,
  334. api_key: "guest",
  335. }), {
  336. mode: "cors",
  337. }).then(r => r.json());
  338. const result = {
  339. status: "OK",
  340. exitCode: String(res.exit_code),
  341. execTime: +res.time * 1e3,
  342. memory: +res.memory * 1e-3,
  343. input,
  344. };
  345. if (res.build_result == "failure") {
  346. result.status = "CE";
  347. result.exitCode = res.build_exit_code;
  348. result.output = res.build_stdout;
  349. result.error = res.build_stderr;
  350. }
  351. else {
  352. result.status = (res.result == "timeout") ? "TLE" : (res.result == "failure") ? "RE" : "OK";
  353. result.exitCode = res.exit_code;
  354. result.output = res.stdout;
  355. result.error = res.stderr;
  356. }
  357. return result;
  358. }
  359. }
  360.  
  361. class WandboxRunner extends CodeRunner {
  362. name;
  363. options;
  364. constructor(name, label, options = {}) {
  365. super(label, "Wandbox");
  366. this.name = name;
  367. this.options = options;
  368. }
  369. getOptions(sourceCode, input) {
  370. if (typeof this.options == "function")
  371. return this.options(sourceCode, input);
  372. return this.options;
  373. }
  374. run(sourceCode, input) {
  375. const options = this.getOptions(sourceCode, input);
  376. return this.request(Object.assign({
  377. compiler: this.name,
  378. code: sourceCode,
  379. stdin: input,
  380. }, options));
  381. }
  382. async request(body) {
  383. const startTime = Date.now();
  384. let res;
  385. try {
  386. res = await fetch("https://wandbox.org/api/compile.json", {
  387. method: "POST",
  388. mode: "cors",
  389. headers: {
  390. "Content-Type": "application/json",
  391. },
  392. body: JSON.stringify(body),
  393. }).then(r => r.json());
  394. }
  395. catch (error) {
  396. console.error(error);
  397. return {
  398. status: "IE",
  399. input: body.stdin,
  400. error: String(error),
  401. };
  402. }
  403. const endTime = Date.now();
  404. const result = {
  405. status: "OK",
  406. exitCode: String(res.status),
  407. execTime: endTime - startTime,
  408. input: body.stdin,
  409. output: String(res.program_output || ""),
  410. error: String(res.program_error || ""),
  411. };
  412. // 正常終了以外の場合
  413. if (res.status != 0) {
  414. if (res.signal) {
  415. result.exitCode += ` (${res.signal})`;
  416. }
  417. result.output = String(res.compiler_output || "") + String(result.output || "");
  418. result.error = String(res.compiler_error || "") + String(result.error || "");
  419. if (res.compiler_output || res.compiler_error) {
  420. result.status = "CE";
  421. }
  422. else {
  423. result.status = "RE";
  424. }
  425. }
  426. return result;
  427. }
  428. }
  429.  
  430. class WandboxCppRunner extends WandboxRunner {
  431. async run(sourceCode, input) {
  432. // ACL を結合する
  433. const ACLBase = "https://cdn.jsdelivr.net/gh/atcoder/ac-library/";
  434. const files = new Map();
  435. const includeHeader = async (source) => {
  436. const pattern = /^#\s*include\s*[<"]atcoder\/([^>"]+)[>"]/gm;
  437. const loaded = [];
  438. let match;
  439. while (match = pattern.exec(source)) {
  440. const file = "atcoder/" + match[1];
  441. if (files.has(file))
  442. continue;
  443. files.set(file, null);
  444. loaded.push([file, fetch(ACLBase + file, { mode: "cors", cache: "force-cache", }).then(r => r.text())]);
  445. }
  446. const included = await Promise.all(loaded.map(async ([file, r]) => {
  447. const source = await r;
  448. files.set(file, source);
  449. return source;
  450. }));
  451. for (const source of included) {
  452. await includeHeader(source);
  453. }
  454. };
  455. await includeHeader(sourceCode);
  456. const codes = [];
  457. for (const [file, code] of files) {
  458. codes.push({ file, code, });
  459. }
  460. const options = this.getOptions(sourceCode, input);
  461. return await this.request(Object.assign({
  462. compiler: this.name,
  463. code: sourceCode,
  464. stdin: input,
  465. codes,
  466. "compiler-option-raw": "-I.",
  467. }, options));
  468. }
  469. }
  470.  
  471. let brythonRunnerLoaded = false;
  472. const brythonRunner = new CustomRunner("Brython", async (sourceCode, input) => {
  473. if (!brythonRunnerLoaded) {
  474. // BrythonRunner を読み込む
  475. await new Promise((resolve) => {
  476. const script = document.createElement("script");
  477. script.src = "https://cdn.jsdelivr.net/gh/pythonpad/brython-runner/lib/brython-runner.bundle.js";
  478. script.onload = () => {
  479. brythonRunnerLoaded = true;
  480. resolve(null);
  481. };
  482. document.head.appendChild(script);
  483. });
  484. }
  485. let stdout = "";
  486. let stderr = "";
  487. let stdinOffset = 0;
  488. const BrythonRunner = unsafeWindow.BrythonRunner;
  489. const runner = new BrythonRunner({
  490. stdout: { write(content) { stdout += content; }, flush() { } },
  491. stderr: { write(content) { stderr += content; }, flush() { } },
  492. stdin: { async readline() {
  493. let index = input.indexOf("\n", stdinOffset) + 1;
  494. if (index == 0)
  495. index = input.length;
  496. const text = input.slice(stdinOffset, index);
  497. stdinOffset = index;
  498. return text;
  499. } },
  500. });
  501. const timeStart = Date.now();
  502. await runner.runCode(sourceCode);
  503. const timeEnd = Date.now();
  504. return {
  505. status: "OK",
  506. exitCode: "0",
  507. execTime: (timeEnd - timeStart),
  508. input,
  509. output: stdout,
  510. error: stderr,
  511. };
  512. });
  513.  
  514. function pairs(list) {
  515. const pairs = [];
  516. const len = list.length >> 1;
  517. for (let i = 0; i < len; i++)
  518. pairs.push([list[i * 2], list[i * 2 + 1]]);
  519. return pairs;
  520. }
  521. async function init$3() {
  522. if (location.host != "atcoder.jp")
  523. throw "Not AtCoder";
  524. const doc = unsafeWindow.document;
  525. const eLanguage = unsafeWindow.$("#select-lang>select");
  526. const langMap = {
  527. 4001: "C GCC 9.2.1",
  528. 4002: "C Clang 10.0.0",
  529. 4003: "C++ GCC 9.2.1",
  530. 4004: "C++ Clang 10.0.0",
  531. 4005: "Java OpenJDK 11.0.6",
  532. 4006: "Python3 CPython 3.8.2",
  533. 4007: "Bash 5.0.11",
  534. 4008: "bc 1.07.1",
  535. 4009: "Awk GNU Awk 4.1.4",
  536. 4010: "C# .NET Core 3.1.201",
  537. 4011: "C# Mono-mcs 6.8.0.105",
  538. 4012: "C# Mono-csc 3.5.0",
  539. 4013: "Clojure 1.10.1.536",
  540. 4014: "Crystal 0.33.0",
  541. 4015: "D DMD 2.091.0",
  542. 4016: "D GDC 9.2.1",
  543. 4017: "D LDC 1.20.1",
  544. 4018: "Dart 2.7.2",
  545. 4019: "dc 1.4.1",
  546. 4020: "Erlang 22.3",
  547. 4021: "Elixir 1.10.2",
  548. 4022: "F# .NET Core 3.1.201",
  549. 4023: "F# Mono 10.2.3",
  550. 4024: "Forth gforth 0.7.3",
  551. 4025: "Fortran GNU Fortran 9.2.1",
  552. 4026: "Go 1.14.1",
  553. 4027: "Haskell GHC 8.8.3",
  554. 4028: "Haxe 4.0.3",
  555. 4029: "Haxe 4.0.3",
  556. 4030: "JavaScript Node.js 12.16.1",
  557. 4031: "Julia 1.4.0",
  558. 4032: "Kotlin 1.3.71",
  559. 4033: "Lua Lua 5.3.5",
  560. 4034: "Lua LuaJIT 2.1.0",
  561. 4035: "Dash 0.5.8",
  562. 4036: "Nim 1.0.6",
  563. 4037: "Objective-C Clang 10.0.0",
  564. 4038: "Lisp SBCL 2.0.3",
  565. 4039: "OCaml 4.10.0",
  566. 4040: "Octave 5.2.0",
  567. 4041: "Pascal FPC 3.0.4",
  568. 4042: "Perl 5.26.1",
  569. 4043: "Raku Rakudo 2020.02.1",
  570. 4044: "PHP 7.4.4",
  571. 4045: "Prolog SWI-Prolog 8.0.3",
  572. 4046: "Python PyPy2 7.3.0",
  573. 4047: "Python3 PyPy3 7.3.0",
  574. 4048: "Racket 7.6",
  575. 4049: "Ruby 2.7.1",
  576. 4050: "Rust 1.42.0",
  577. 4051: "Scala 2.13.1",
  578. 4052: "Java OpenJDK 1.8.0",
  579. 4053: "Scheme Gauche 0.9.9",
  580. 4054: "ML MLton 20130715",
  581. 4055: "Swift 5.2.1",
  582. 4056: "Text cat 8.28",
  583. 4057: "TypeScript 3.8",
  584. 4058: "Basic .NET Core 3.1.101",
  585. 4059: "Zsh 5.4.2",
  586. 4060: "COBOL Fixed OpenCOBOL 1.1.0",
  587. 4061: "COBOL Free OpenCOBOL 1.1.0",
  588. 4062: "Brainfuck bf 20041219",
  589. 4063: "Ada Ada2012 GNAT 9.2.1",
  590. 4064: "Unlambda 2.0.0",
  591. 4065: "Cython 0.29.16",
  592. 4066: "Sed 4.4",
  593. 4067: "Vim 8.2.0460",
  594. };
  595. const languageId = new ObservableValue(eLanguage.val());
  596. eLanguage.change(() => {
  597. languageId.value = eLanguage.val();
  598. });
  599. const language = languageId.map(lang => langMap[lang]);
  600. function getTestCases() {
  601. const selectors = [
  602. ["#task-statement p+pre.literal-block", ".section"],
  603. ["#task-statement pre.source-code-for-copy", ".part"],
  604. ["#task-statement .lang>*:nth-child(1) .div-btn-copy+pre", ".part"],
  605. ["#task-statement .div-btn-copy+pre", ".part"],
  606. ["#task-statement>.part pre.linenums", ".part"],
  607. ["#task-statement>.part:not(.io-style)>h3+section>pre", ".part"],
  608. ["#task-statement pre", ".part"],
  609. ];
  610. for (const [selector, closestSelector] of selectors) {
  611. let e = [...doc.querySelectorAll(selector)];
  612. e = e.filter(e => !e.closest(".io-style")); // practice2
  613. if (e.length == 0)
  614. continue;
  615. return pairs(e).map(([input, output], index) => ({
  616. title: `Sample ${index + 1}`,
  617. input: input.textContent,
  618. output: output.textContent,
  619. anchor: (input.closest(closestSelector) || input.parentElement).querySelector(".btn-copy"),
  620. }));
  621. }
  622. { // maximum_cup_2018_d
  623. let e = [...doc.querySelectorAll("#task-statement .div-btn-copy+pre")];
  624. e = e.filter(f => !f.childElementCount);
  625. if (e.length) {
  626. return pairs(e).map(([input, output], index) => ({
  627. title: `Sample ${index + 1}`,
  628. input: input.textContent,
  629. output: output.textContent,
  630. anchor: (input.closest(".part") || input.parentElement).querySelector(".btn-copy"),
  631. }));
  632. }
  633. }
  634. return [];
  635. }
  636. return {
  637. name: "AtCoder",
  638. language,
  639. get sourceCode() {
  640. return unsafeWindow.getSourceCode();
  641. },
  642. set sourceCode(sourceCode) {
  643. doc.querySelector(".plain-textarea").value = sourceCode;
  644. unsafeWindow.$(".editor").data("editor").doc.setValue(sourceCode);
  645. },
  646. submit() {
  647. doc.querySelector("#submit").click();
  648. },
  649. get testButtonContainer() {
  650. return doc.querySelector("#submit").parentElement;
  651. },
  652. get sideButtonContainer() {
  653. return doc.querySelector(".editor-buttons");
  654. },
  655. get bottomMenuContainer() {
  656. return doc.getElementById("main-div");
  657. },
  658. get resultListContainer() {
  659. return doc.querySelector(".form-code-submit");
  660. },
  661. get testCases() {
  662. return getTestCases();
  663. },
  664. get jQuery() {
  665. return unsafeWindow["jQuery"];
  666. },
  667. };
  668. }
  669.  
  670. async function init$2() {
  671. if (location.host != "yukicoder.me")
  672. throw "Not yukicoder";
  673. const $ = unsafeWindow.$;
  674. const doc = unsafeWindow.document;
  675. const editor = unsafeWindow.ace.edit("rich_source");
  676. const eSourceObject = $("#source");
  677. const eLang = $("#lang");
  678. const eSamples = $(".sample");
  679. const langMap = {
  680. "cpp14": "C++ C++14 GCC 11.1.0 + Boost 1.77.0",
  681. "cpp17": "C++ C++17 GCC 11.1.0 + Boost 1.77.0",
  682. "cpp-clang": "C++ C++17 Clang 10.0.0 + Boost 1.76.0",
  683. "cpp23": "C++ C++11 GCC 8.4.1",
  684. "c11": "C++ C++11 GCC 11.1.0",
  685. "c": "C C90 GCC 8.4.1",
  686. "java8": "Java Java16 OpenJDK 16.0.1",
  687. "csharp": "C# CSC 3.9.0",
  688. "csharp_mono": "C# Mono 6.12.0.147",
  689. "csharp_dotnet": "C# .NET 5.0",
  690. "perl": "Perl 5.26.3",
  691. "raku": "Raku Rakudo v2021-07-2-g74d7ff771",
  692. "php": "PHP 7.2.24",
  693. "php7": "PHP 8.0.8",
  694. "python3": "Python3 3.9.6 + numpy 1.14.5 + scipy 1.1.0",
  695. "pypy2": "Python PyPy2 7.3.5",
  696. "pypy3": "Python3 PyPy3 7.3.5",
  697. "ruby": "Ruby 3.0.2p107",
  698. "d": "D DMD 2.097.1",
  699. "go": "Go 1.16.6",
  700. "haskell": "Haskell 8.10.5",
  701. "scala": "Scala 2.13.6",
  702. "nim": "Nim 1.4.8",
  703. "rust": "Rust 1.53.0",
  704. "kotlin": "Kotlin 1.5.21",
  705. "scheme": "Scheme Gauche 0.9.10",
  706. "crystal": "Crystal 1.1.1",
  707. "swift": "Swift 5.4.2",
  708. "ocaml": "OCaml 4.12.0",
  709. "clojure": "Clojure 1.10.2.790",
  710. "fsharp": "F# 5.0",
  711. "elixir": "Elixir 1.7.4",
  712. "lua": "Lua LuaJIT 2.0.5",
  713. "fortran": "Fortran gFortran 8.4.1",
  714. "node": "JavaScript Node.js 15.5.0",
  715. "typescript": "TypeScript 4.3.5",
  716. "lisp": "Lisp Common Lisp sbcl 2.1.6",
  717. "sml": "ML Standard ML MLton 20180207-6",
  718. "kuin": "Kuin KuinC++ v.2021.7.17",
  719. "vim": "Vim v8.2",
  720. "sh": "Bash 4.4.19",
  721. "nasm": "Assembler nasm 2.13.03",
  722. "clay": "cLay 20210917-1",
  723. "bf": "Brainfuck BFI 1.1",
  724. "Whitespace": "Whitespace 0.3",
  725. "text": "Text cat 8.3",
  726. };
  727. const language = new ObservableValue(langMap[eLang.val()]);
  728. eLang.on("change", () => {
  729. language.value = langMap[eLang.val()];
  730. });
  731. return {
  732. name: "yukicoder",
  733. language,
  734. get sourceCode() {
  735. if (eSourceObject.is(":visible"))
  736. return eSourceObject.val();
  737. return editor.getSession().getValue();
  738. },
  739. set sourceCode(sourceCode) {
  740. eSourceObject.val(sourceCode);
  741. editor.getSession().setValue(sourceCode);
  742. },
  743. submit() {
  744. doc.querySelector(`#submit_form input[type="submit"]`).click();
  745. },
  746. get testButtonContainer() {
  747. return doc.querySelector("#submit_form");
  748. },
  749. get sideButtonContainer() {
  750. return doc.querySelector("#toggle_source_editor").parentElement;
  751. },
  752. get bottomMenuContainer() {
  753. return doc.body;
  754. },
  755. get resultListContainer() {
  756. return doc.querySelector("#content");
  757. },
  758. get testCases() {
  759. const testCases = [];
  760. let sampleId = 1;
  761. for (let i = 0; i < eSamples.length; i++) {
  762. const eSample = eSamples.eq(i);
  763. const [eInput, eOutput] = eSample.find("pre");
  764. const anchorContainer = $(`<span>`);
  765. const anchor = $(`<span>`);
  766. anchorContainer.append(anchor);
  767. eSample.find("h6").eq(0).appendTo(anchorContainer);
  768. anchorContainer.insertAfter(eSample.find("button").eq(0));
  769. testCases.push({
  770. title: `Sample ${sampleId++}`,
  771. input: eInput.textContent,
  772. output: eOutput.textContent,
  773. anchor: anchor[0],
  774. });
  775. }
  776. return testCases;
  777. },
  778. get jQuery() {
  779. return $;
  780. },
  781. };
  782. }
  783.  
  784. let data = {};
  785. function toString() {
  786. return JSON.stringify(data);
  787. }
  788. function save() {
  789. localStorage.setItem("AtCoderEasyTest", toString());
  790. }
  791. function load() {
  792. if ("AtCoderEasyTest" in localStorage) {
  793. data = JSON.parse(localStorage.getItem("AtCoderEasyTest"));
  794. }
  795. }
  796. load();
  797. /** プロパティ名は camelCase にすること */
  798. const config = {
  799. getString(key, defaultValue = "") {
  800. if (!(key in data))
  801. config.setString(key, defaultValue);
  802. return data[key];
  803. },
  804. setString(key, value) {
  805. data[key] = value;
  806. save();
  807. },
  808. has(key) {
  809. return key in data;
  810. },
  811. get(key, defaultValue = null) {
  812. if (!(key in data))
  813. config.set(key, defaultValue);
  814. return JSON.parse(data[key]);
  815. },
  816. set(key, value) {
  817. config.setString(key, JSON.stringify(value));
  818. },
  819. save,
  820. load,
  821. toString,
  822. };
  823.  
  824. class Editor {
  825. _element;
  826. constructor(lang) {
  827. this._element = document.createElement("textarea");
  828. this._element.style.fontFamily = "monospace";
  829. this._element.style.width = "100%";
  830. this._element.style.minHeight = "5em";
  831. }
  832. get element() {
  833. return this._element;
  834. }
  835. get sourceCode() {
  836. return this._element.value;
  837. }
  838. set sourceCode(sourceCode) {
  839. this._element.value = sourceCode;
  840. }
  841. setLanguage(lang) {
  842. }
  843. }
  844.  
  845. async function init$1() {
  846. if (location.host != "codeforces.com")
  847. throw "not Codeforces";
  848. //TODO: m1.codeforces.com, m2.codeforces.com, m3.codeforces.com に対応する
  849. const doc = unsafeWindow.document;
  850. const eLang = doc.querySelector("select[name='programTypeId']");
  851. doc.head.appendChild(newElement("link", {
  852. rel: "stylesheet",
  853. href: "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css",
  854. }));
  855. const eButtons = newElement("span");
  856. doc.querySelector(".submitForm").appendChild(eButtons);
  857. await loadScript("https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js");
  858. const jQuery = unsafeWindow["jQuery"].noConflict();
  859. unsafeWindow["jQuery"] = unsafeWindow["$"];
  860. unsafeWindow["jQuery11"] = jQuery;
  861. await loadScript("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js", null, { jQuery, $: jQuery });
  862. const langMap = {
  863. 3: "Delphi 7",
  864. 4: "Pascal Free Pascal 3.0.2",
  865. 6: "PHP 7.2.13",
  866. 7: "Python 2.7.18",
  867. 9: "C# Mono 6.8",
  868. 12: "Haskell GHC 8.10.1",
  869. 13: "Perl 5.20.1",
  870. 19: "OCaml 4.02.1",
  871. 20: "Scala 2.12.8",
  872. 28: "D DMD32 v2.091.0",
  873. 31: "Python3 3.8.10",
  874. 32: "Go 1.15.6",
  875. 34: "JavaScript V8 4.8.0",
  876. 36: "Java 1.8.0_241",
  877. 40: "Python PyPy2 2.7 (7.3.0)",
  878. 41: "Python3 PyPy3 3.7 (7.3.0)",
  879. 43: "C C11 GCC 5.1.0",
  880. 48: "Kotlin 1.5.31",
  881. 49: "Rust 1.49.0",
  882. 50: "C++ C++14 G++ 6.4.0",
  883. 51: "Pascal PascalABC.NET 3.4.1",
  884. 52: "C++ C++17 Clang++",
  885. 54: "C++ C++17 G++ 7.3.0",
  886. 55: "JavaScript Node.js 12.6.3",
  887. 59: "C++ Microsoft Visual C++ 2017",
  888. 60: "Java 11.0.6",
  889. 61: "C++ C++17 9.2.0 (64 bit, msys 2)",
  890. 65: "C# 8, .NET Core 3.1",
  891. 67: "Ruby 3.0.0",
  892. 70: "Python3 PyPy 3.7 (7.3.5, 64bit)",
  893. 72: "Kotlin 1.5.31",
  894. 73: "C++ GNU G++ 11.2.0 (64 bit, winlibs)",
  895. };
  896. const language = new ObservableValue(langMap[eLang.value]);
  897. eLang.addEventListener("change", () => {
  898. language.value = langMap[eLang.value];
  899. });
  900. let _sourceCode = "";
  901. const eFile = doc.querySelector(".submitForm").elements["sourceFile"];
  902. eFile.addEventListener("change", async () => {
  903. if (eFile.files[0]) {
  904. _sourceCode = await eFile.files[0].text();
  905. if (editor)
  906. editor.sourceCode = _sourceCode;
  907. }
  908. });
  909. let editor = null;
  910. let waitCfFastSubmitCount = 0;
  911. const waitCfFastSubmit = setInterval(() => {
  912. if (document.getElementById("editor")) {
  913. // cf-fast-submit
  914. if (editor && editor.element)
  915. editor.element.style.display = "none";
  916. // 言語セレクトを同期させる
  917. const eLang2 = doc.querySelector(".submit-form select[name='programTypeId']");
  918. if (eLang2) {
  919. eLang.addEventListener("change", () => {
  920. eLang2.value = eLang.value;
  921. });
  922. eLang2.addEventListener("change", () => {
  923. eLang.value = eLang2.value;
  924. language.value = langMap[eLang.value];
  925. });
  926. }
  927. // TODO: 選択されたファイルをどうかする
  928. // エディタを使う
  929. const aceEditor = unsafeWindow["ace"].edit("editor");
  930. editor = {
  931. get sourceCode() {
  932. return aceEditor.getValue();
  933. },
  934. set sourceCode(sourceCode) {
  935. aceEditor.setValue(sourceCode);
  936. },
  937. setLanguage(lang) { },
  938. };
  939. // ボタンを追加する
  940. const buttonContainer = doc.querySelector(".submit-form .submit").parentElement;
  941. buttonContainer.appendChild(newElement("a", {
  942. className: "btn btn-info",
  943. textContent: "Test & Submit",
  944. onclick: () => events.trig("testAndSubmit"),
  945. }));
  946. buttonContainer.appendChild(newElement("a", {
  947. className: "btn btn-default",
  948. textContent: "Test All Samples",
  949. onclick: () => events.trig("testAllSamples"),
  950. }));
  951. clearInterval(waitCfFastSubmit);
  952. }
  953. else {
  954. waitCfFastSubmitCount++;
  955. if (waitCfFastSubmitCount >= 100)
  956. clearInterval(waitCfFastSubmit);
  957. }
  958. }, 100);
  959. if (config.get("codeforcesEditor", true)) {
  960. editor = new Editor(langMap[eLang.value].split(" ")[0]);
  961. doc.getElementById("pageContent").appendChild(editor.element);
  962. language.addListener(lang => {
  963. editor.setLanguage(lang);
  964. });
  965. }
  966. return {
  967. name: "Codeforces",
  968. language,
  969. get sourceCode() {
  970. if (editor)
  971. return editor.sourceCode;
  972. return _sourceCode;
  973. },
  974. set sourceCode(sourceCode) {
  975. const container = new DataTransfer();
  976. container.items.add(new File([sourceCode], "prog.txt", { type: "text/plain" }));
  977. const eFile = doc.querySelector(".submitForm").elements["sourceFile"];
  978. eFile.files = container.files;
  979. _sourceCode = sourceCode;
  980. if (editor)
  981. editor.sourceCode = sourceCode;
  982. },
  983. submit() {
  984. if (editor)
  985. _sourceCode = editor.sourceCode;
  986. this.sourceCode = _sourceCode;
  987. doc.querySelector(`.submitForm .submit`).click();
  988. },
  989. get testButtonContainer() {
  990. return eButtons;
  991. },
  992. get sideButtonContainer() {
  993. return eButtons;
  994. },
  995. get bottomMenuContainer() {
  996. return doc.body;
  997. },
  998. get resultListContainer() {
  999. return doc.querySelector("#pageContent");
  1000. },
  1001. get testCases() {
  1002. return [...doc.querySelectorAll(".sample-test")].map((e, i) => ({
  1003. title: `Sample ${i + 1}`,
  1004. input: e.querySelector(".input pre").textContent,
  1005. output: e.querySelector(".output pre").textContent,
  1006. anchor: e.querySelector(".input .title"),
  1007. }));
  1008. },
  1009. get jQuery() {
  1010. return jQuery;
  1011. },
  1012. };
  1013. }
  1014.  
  1015. var pSite = Promise.any([init$3(), init$2(), init$1()]);
  1016.  
  1017. const runners = {
  1018. "C GCC 10.1.0 Wandbox": new WandboxRunner("gcc-10.1.0-c", "C (GCC 10.1.0)"),
  1019. "C C17 Clang 10.0.0 paiza.io": new PaizaIORunner("c", "C (C17 / Clang 10.0.0)"),
  1020. "C++ GCC 10.1.0 + Boost 1.73.0 + ACL Wandbox": new WandboxCppRunner("gcc-10.1.0", "C++ (GCC 10.1.0) + ACL", { options: "warning,boost-1.73.0-gcc-9.2.0,gnu++17" }),
  1021. "C++ Clang 10.0.0 + ACL Wandbox": new WandboxCppRunner("clang-10.0.0", "C++ (Clang 10.0.0) + ACL", { options: "warning,boost-nothing-clang-10.0.0,c++17" }),
  1022. "Python3 CPython 3.8.2 paiza.io": new PaizaIORunner("python3", "Python (3.8.2)"),
  1023. "Python3 Brython": brythonRunner,
  1024. "Bash 5.0.17 paiza.io": new PaizaIORunner("bash", "Bash (5.0.17)"),
  1025. "C# .NET Core 6.0.100-alpha.1.20562.2 Wandbox": new WandboxRunner("csharp", "C# (.NET Core 6.0.100-alpha.1.20562.2)"),
  1026. "C# Mono-mcs HEAD Wandbox": new WandboxRunner("mono-head", "C# (Mono-mcs HEAD)"),
  1027. "Clojure 1.10.1-1 paiza.io": new PaizaIORunner("clojure", "Clojure (1.10.1-1)"),
  1028. "D LDC 1.23.0 paiza.io": new PaizaIORunner("d", "D (LDC 1.23.0)"),
  1029. "Erlang 10.6.4 paiza.io": new PaizaIORunner("erlang", "Erlang (10.6.4)"),
  1030. "Elixir 1.10.4 paiza.io": new PaizaIORunner("elixir", "Elixir (1.10.4)"),
  1031. "F# Interactive 4.0 paiza.io": new PaizaIORunner("fsharp", "F# (Interactive 4.0)"),
  1032. "Go 1.14.1 Wandbox": new WandboxRunner("go-1.14.1", "Go (1.14.1)"),
  1033. "Haskell GHC HEAD Wandbox": new WandboxRunner("ghc-head", "Haskell (GHC HEAD)"),
  1034. "JavaScript Node.js paiza.io": new PaizaIORunner("javascript", "JavaScript (Node.js 12.18.3)"),
  1035. "Kotlin 1.4.0 paiza.io": new PaizaIORunner("kotlin", "Kotlin (1.4.0)"),
  1036. "Lua 5.3.4 Wandbox": new WandboxRunner("lua-5.3.4", "Lua (Lua 5.3.4)"),
  1037. "Lua LuaJIT HEAD Wandbox": new WandboxRunner("luajit-head", "Lua (LuaJIT HEAD)"),
  1038. "Nim 1.0.6 Wandbox": new WandboxRunner("nim-1.0.6", "Nim (1.0.6)"),
  1039. "Objective-C Clang 10.0.0 paiza.io": new PaizaIORunner("objective-c", "Objective-C (Clang 10.0.0)"),
  1040. "Ocaml HEAD Wandbox": new WandboxRunner("ocaml-head", "OCaml (HEAD)"),
  1041. "Pascal FPC 3.0.2 Wandbox": new WandboxRunner("fpc-3.0.2", "Pascal (FPC 3.0.2)"),
  1042. "Perl 5.30.0 paiza.io": new PaizaIORunner("perl", "Perl (5.30.0)"),
  1043. "PHP 7.4.10 paiza.io": new PaizaIORunner("php", "PHP (7.4.10)"),
  1044. "PHP 7.3.3 Wandbox": new WandboxRunner("php-7.3.3", "PHP (7.3.3)"),
  1045. "Python PyPy HEAD Wandbox": new WandboxRunner("pypy-head", "PyPy2 (HEAD)"),
  1046. "Python3 PyPy3 7.2.0 Wandbox": new WandboxRunner("pypy-7.2.0-3", "PyPy3 (7.2.0)"),
  1047. "Ruby 2.7.1 paiza.io": new PaizaIORunner("ruby", "Ruby (2.7.1)"),
  1048. "Ruby HEAD Wandbox": new WandboxRunner("ruby-head", "Ruby (HEAD)"),
  1049. "Ruby 2.7.1 Wandbox": new WandboxRunner("ruby-2.7.1", "Ruby (2.7.1)"),
  1050. "Rust 1.42.0 AtCoder": new AtCoderRunner("4050", "Rust (1.42.0)"),
  1051. "Rust HEAD Wandbox": new WandboxRunner("rust-head", "Rust (HEAD)"),
  1052. "Rust 1.43.0 paiza.io": new PaizaIORunner("rust", "Rust (1.43.0)"),
  1053. "Scala 2.13.3 paiza": new PaizaIORunner("scala", "Scala (2.13.3)"),
  1054. "Scheme Gauche 0.9.6 paiza.io": new PaizaIORunner("scheme", "Scheme (Gauche 0.9.6)"),
  1055. "Swift 5.2.5 paiza.io": new PaizaIORunner("swift", "Swift (5.2.5)"),
  1056. "Text local": new CustomRunner("Text", async (sourceCode, input) => {
  1057. return {
  1058. status: "OK",
  1059. exitCode: "0",
  1060. input,
  1061. output: sourceCode,
  1062. };
  1063. }),
  1064. "Basic Visual Basic .NET Core 4.0.1 paiza.io": new PaizaIORunner("vb", "Visual Basic (.NET Core 4.0.1)"),
  1065. "COBOL Free OpenCOBOL 2.2.0 paiza.io": new PaizaIORunner("cobol", "COBOL - Free (OpenCOBOL 2.2.0)"),
  1066. "COBOL Fixed OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4060", "COBOL - Fixed (OpenCOBOL 1.1.0)"),
  1067. "COBOL Free OpenCOBOL 1.1.0 AtCoder": new AtCoderRunner("4061", "COBOL - Free (OpenCOBOL 1.1.0)"),
  1068. "C++ GCC 9.2.0 + ACL Wandbox": new WandboxCppRunner("gcc-9.2.0", "C++ (GCC 9.2.0) + ACL"),
  1069. };
  1070. if (pSite.name == "AtCoder") {
  1071. // AtCoderRunner がない場合は、追加する
  1072. for (const e of document.querySelectorAll("#select-lang option[value]")) {
  1073. const m = e.textContent.match(/([^ ]+) \(([^)]+)\)/);
  1074. if (m) {
  1075. const name = `${m[1]} ${m[2]} AtCoder`;
  1076. const languageId = e.value;
  1077. runners[name] = new AtCoderRunner(languageId, e.textContent);
  1078. }
  1079. }
  1080. }
  1081. console.info("AtCoder Easy Test: codeRunner OK");
  1082. var codeRunner = {
  1083. // 指定した環境でコードを実行する
  1084. run(languageId, sourceCode, input, expectedOutput, options = { trim: true, split: true }) {
  1085. // CodeRunner が存在しない言語ID
  1086. if (!(languageId in runners))
  1087. return Promise.reject("Language not supported");
  1088. // 最後に実行したコードを保存
  1089. if (sourceCode.length > 0)
  1090. codeSaver.save(sourceCode);
  1091. // 実行
  1092. return runners[languageId].test(sourceCode, input, expectedOutput, options);
  1093. },
  1094. // 環境の名前の一覧を取得する
  1095. async getEnvironment(languageId) {
  1096. const langs = similarLangs(languageId, Object.keys(runners));
  1097. if (langs.length == 0)
  1098. throw `Undefined language: ${languageId}`;
  1099. return langs.map(lang => [lang, runners[lang].label]);
  1100. },
  1101. };
  1102.  
  1103. var hBottomMenu = "<div id=\"bottom-menu-wrapper\" class=\"navbar navbar-default navbar-fixed-bottom\">\n <div class=\"container\">\n <div class=\"navbar-header\">\n <button id=\"bottom-menu-key\" type=\"button\" class=\"navbar-toggle collapsed glyphicon glyphicon-menu-down\" data-toggle=\"collapse\" data-target=\"#bottom-menu\"></button>\n </div>\n <div id=\"bottom-menu\" class=\"collapse navbar-collapse\">\n <ul id=\"bottom-menu-tabs\" class=\"nav nav-tabs\"></ul>\n <div id=\"bottom-menu-contents\" class=\"tab-content\"></div>\n </div>\n </div>\n</div>";
  1104.  
  1105. var hStyle$1 = "<style>\n#bottom-menu-wrapper {\n background: transparent;\n border: none;\n pointer-events: none;\n padding: 0;\n}\n\n#bottom-menu-wrapper>.container {\n position: absolute;\n bottom: 0;\n width: 100%;\n padding: 0;\n}\n\n#bottom-menu-wrapper>.container>.navbar-header {\n float: none;\n}\n\n#bottom-menu-key {\n display: block;\n float: none;\n margin: 0 auto;\n padding: 10px 3em;\n border-radius: 5px 5px 0 0;\n background: #000;\n opacity: 0.5;\n color: #FFF;\n cursor: pointer;\n pointer-events: auto;\n text-align: center;\n}\n\n@media screen and (max-width: 767px) {\n #bottom-menu-key {\n opacity: 0.25;\n }\n}\n\n#bottom-menu-key.collapsed:before {\n content: \"\\e260\";\n}\n\n#bottom-menu-tabs {\n padding: 3px 0 0 10px;\n cursor: n-resize;\n}\n\n#bottom-menu-tabs a {\n pointer-events: auto;\n}\n\n#bottom-menu {\n pointer-events: auto;\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n max-height: unset;\n}\n\n#bottom-menu.collapse:not(.in) {\n display: none !important;\n}\n\n#bottom-menu-tabs>li>a {\n background: rgba(150, 150, 150, 0.5);\n color: #000;\n border: solid 1px #ccc;\n filter: brightness(0.75);\n}\n\n#bottom-menu-tabs>li>a:hover {\n background: rgba(150, 150, 150, 0.5);\n border: solid 1px #ccc;\n color: #111;\n filter: brightness(0.9);\n}\n\n#bottom-menu-tabs>li.active>a {\n background: #eee;\n border: solid 1px #ccc;\n color: #333;\n filter: none;\n}\n\n.bottom-menu-btn-close {\n font-size: 8pt;\n vertical-align: baseline;\n padding: 0 0 0 6px;\n margin-right: -6px;\n}\n\n#bottom-menu-contents {\n padding: 5px 15px;\n max-height: 50vh;\n overflow-y: auto;\n}\n\n#bottom-menu-contents .panel {\n color: #333;\n}\n</style>";
  1106.  
  1107. async function init() {
  1108. const site = await pSite;
  1109. const style = html2element(hStyle$1);
  1110. const bottomMenu = html2element(hBottomMenu);
  1111. unsafeWindow.document.head.appendChild(style);
  1112. site.bottomMenuContainer.appendChild(bottomMenu);
  1113. const bottomMenuKey = bottomMenu.querySelector("#bottom-menu-key");
  1114. const bottomMenuTabs = bottomMenu.querySelector("#bottom-menu-tabs");
  1115. const bottomMenuContents = bottomMenu.querySelector("#bottom-menu-contents");
  1116. // メニューのリサイズ
  1117. {
  1118. let resizeStart = null;
  1119. const onStart = (event) => {
  1120. const target = event.target;
  1121. const pageY = event.pageY;
  1122. if (target.id != "bottom-menu-tabs")
  1123. return;
  1124. resizeStart = { y: pageY, height: bottomMenuContents.getBoundingClientRect().height };
  1125. };
  1126. const onMove = (event) => {
  1127. if (!resizeStart)
  1128. return;
  1129. event.preventDefault();
  1130. bottomMenuContents.style.height = `${resizeStart.height - (event.pageY - resizeStart.y)}px`;
  1131. };
  1132. const onEnd = () => {
  1133. resizeStart = null;
  1134. };
  1135. bottomMenuTabs.addEventListener("mousedown", onStart);
  1136. bottomMenuTabs.addEventListener("mousemove", onMove);
  1137. bottomMenuTabs.addEventListener("mouseup", onEnd);
  1138. bottomMenuTabs.addEventListener("mouseleave", onEnd);
  1139. }
  1140. let tabs = new Set();
  1141. let selectedTab = null;
  1142. /** 下メニューの操作 */
  1143. const menuController = {
  1144. /** タブを選択 */
  1145. selectTab(tabId) {
  1146. const tab = site.jQuery(`#bottom-menu-tab-${tabId}`);
  1147. if (tab && tab[0]) {
  1148. tab.tab("show"); // Bootstrap 3
  1149. selectedTab = tabId;
  1150. }
  1151. },
  1152. /** 下メニューにタブを追加する */
  1153. addTab(tabId, tabLabel, paneContent, options = {}) {
  1154. console.log(`AtCoder Easy Test: addTab: ${tabLabel} (${tabId})`, paneContent);
  1155. // タブを追加
  1156. const tab = document.createElement("a");
  1157. tab.textContent = tabLabel;
  1158. tab.id = `bottom-menu-tab-${tabId}`;
  1159. tab.href = "#";
  1160. tab.dataset.target = `#bottom-menu-pane-${tabId}`;
  1161. tab.dataset.toggle = "tab";
  1162. tab.addEventListener("click", event => {
  1163. event.preventDefault();
  1164. menuController.selectTab(tabId);
  1165. });
  1166. const tabLi = document.createElement("li");
  1167. tabLi.appendChild(tab);
  1168. bottomMenuTabs.appendChild(tabLi);
  1169. // 内容を追加
  1170. const pane = document.createElement("div");
  1171. pane.className = "tab-pane";
  1172. pane.id = `bottom-menu-pane-${tabId}`;
  1173. pane.appendChild(paneContent);
  1174. bottomMenuContents.appendChild(pane);
  1175. const controller = {
  1176. get id() {
  1177. return tabId;
  1178. },
  1179. close() {
  1180. bottomMenuTabs.removeChild(tabLi);
  1181. bottomMenuContents.removeChild(pane);
  1182. tabs.delete(tab);
  1183. if (selectedTab == tabId) {
  1184. selectedTab = null;
  1185. if (tabs.size > 0) {
  1186. menuController.selectTab(tabs.values().next().value.id);
  1187. }
  1188. }
  1189. },
  1190. show() {
  1191. menuController.show();
  1192. menuController.selectTab(tabId);
  1193. },
  1194. set color(color) {
  1195. tab.style.backgroundColor = color;
  1196. },
  1197. };
  1198. // 閉じるボタン
  1199. if (options.closeButton) {
  1200. const btn = document.createElement("a");
  1201. btn.className = "bottom-menu-btn-close btn btn-link glyphicon glyphicon-remove";
  1202. btn.addEventListener("click", () => {
  1203. controller.close();
  1204. });
  1205. tab.appendChild(btn);
  1206. }
  1207. // 選択されているタブがなければ選択
  1208. if (!selectedTab)
  1209. menuController.selectTab(tabId);
  1210. return controller;
  1211. },
  1212. /** 下メニューを表示する */
  1213. show() {
  1214. if (bottomMenuKey.classList.contains("collapsed"))
  1215. bottomMenuKey.click();
  1216. },
  1217. /** 下メニューの表示/非表示を切り替える */
  1218. toggle() {
  1219. bottomMenuKey.click();
  1220. },
  1221. };
  1222. console.info("AtCoder Easy Test: bottomMenu OK");
  1223. return menuController;
  1224. }
  1225.  
  1226. var hRowTemplate = "<div class=\"atcoder-easy-test-cases-row alert alert-dismissible\">\n <button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">\n <span aria-hidden=\"true\">×</span>\n </button>\n <div class=\"progress\">\n <div class=\"progress-bar\" style=\"width: 0%;\">0 / 0</div>\n </div>\n <!--div class=\"label label-default label-warning\" style=\"margin: 3px; cursor: pointer;\">WA</div>\n <div class=\"label label-default label-warning\" style=\"margin: 3px; cursor: pointer;\">WA</div>\n <div class=\"label label-default label-warning\" style=\"margin: 3px; cursor: pointer;\">WA</div-->\n</div>";
  1227.  
  1228. class ResultRow {
  1229. _tabs;
  1230. _element;
  1231. _promise;
  1232. constructor(pairs) {
  1233. this._tabs = pairs.map(([_, tab]) => tab);
  1234. this._element = html2element(hRowTemplate);
  1235. const numCases = pairs.length;
  1236. let numFinished = 0;
  1237. let numAccepted = 0;
  1238. const progressBar = this._element.querySelector(".progress-bar");
  1239. progressBar.textContent = `${numFinished} / ${numCases}`;
  1240. this._promise = Promise.all(pairs.map(([pResult, tab]) => {
  1241. const button = html2element(`<div class="label label-default" style="margin: 3px; cursor: pointer;">WJ</div>`);
  1242. button.addEventListener("click", async () => {
  1243. (await tab).show();
  1244. });
  1245. this._element.appendChild(button);
  1246. return pResult.then(result => {
  1247. button.textContent = result.status;
  1248. if (result.status == "AC") {
  1249. button.classList.add("label-success");
  1250. }
  1251. else if (result.status != "OK") {
  1252. button.classList.add("label-warning");
  1253. }
  1254. numFinished++;
  1255. if (result.status == "AC")
  1256. numAccepted++;
  1257. progressBar.textContent = `${numFinished} / ${numCases}`;
  1258. progressBar.style.width = `${100 * numFinished / numCases}%`;
  1259. if (numFinished == numCases) {
  1260. if (numAccepted == numCases)
  1261. this._element.classList.add("alert-success");
  1262. else
  1263. this._element.classList.add("alert-warning");
  1264. }
  1265. }).catch(reason => {
  1266. button.textContent = "IE";
  1267. button.classList.add("label-danger");
  1268. console.error(reason);
  1269. });
  1270. }));
  1271. }
  1272. get element() {
  1273. return this._element;
  1274. }
  1275. onFinish(listener) {
  1276. this._promise.then(listener);
  1277. }
  1278. remove() {
  1279. for (const pTab of this._tabs)
  1280. pTab.then(tab => tab.close());
  1281. const parent = this._element.parentElement;
  1282. if (parent)
  1283. parent.removeChild(this._element);
  1284. }
  1285. }
  1286.  
  1287. var hResultList = "<div class=\"row\"></div>";
  1288.  
  1289. const eResultList = html2element(hResultList);
  1290. pSite.then(site => site.resultListContainer.appendChild(eResultList));
  1291. const resultList = {
  1292. addResult(pairs) {
  1293. const result = new ResultRow(pairs);
  1294. eResultList.insertBefore(result.element, eResultList.firstChild);
  1295. return result;
  1296. },
  1297. };
  1298.  
  1299. var hPage = "<!DOCTYPE html>\n<html>\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\n <title>AtCoder Easy Test</title>\n <link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css\" rel=\"stylesheet\">\n </head>\n <body>\n <div class=\"container\">\n <div class=\"panel panel-default\">\n <div class=\"panel-heading\">Settings</div>\n <div class=\"panel-body\">\n <form>\n <div class=\"checkbox\">\n <label><input id=\"useKeyboardShortcut\" type=\"checkbox\">Use Keyboard Shortcuts</label>\n </div>\n <div class=\"checkbox\">\n <label><input id=\"codeforcesShowEditor\" type=\"checkbox\">Show Editor in Codeforces Problem Page</label>\n </div>\n </form>\n </div>\n </div>\n </div>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js\"></script>\n </body>\n</html>";
  1300.  
  1301. const settings = {
  1302. /** 設定ページを開く
  1303. * クリックなどのイベント時にしか正しく実行できない
  1304. */
  1305. open() {
  1306. const win = window.open("about:blank");
  1307. const doc = win.document;
  1308. doc.open();
  1309. doc.write(hPage);
  1310. doc.close();
  1311. const bindCheckbox = (key, defaultValue) => {
  1312. const element = doc.getElementById(key);
  1313. element.checked = config.get(key, defaultValue);
  1314. element.addEventListener("change", () => {
  1315. config.set(key, element.checked);
  1316. });
  1317. };
  1318. bindCheckbox("useKeyboardShortcut", true);
  1319. bindCheckbox("codeforcesShowEditor", false);
  1320. }
  1321. };
  1322.  
  1323. var hTabTemplate = "<div class=\"atcoder-easy-test-result container\">\n <div class=\"row\">\n <div class=\"atcoder-easy-test-result-col-input col-xs-12\" data-if-expected-output=\"col-sm-6 col-sm-push-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Input\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-input form-control\" rows=\"3\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n <div class=\"atcoder-easy-test-result-col-expected-output col-xs-12 col-sm-6 hidden\" data-if-expected-output=\"!hidden col-sm-pull-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Expected Output\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-expected-output form-control\" rows=\"3\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n </div>\n <div class=\"row\"><div class=\"col-sm-6 col-sm-offset-3\">\n <div class=\"panel panel-default\">\n <table class=\"table table-condensed\">\n <tbody>\n <tr>\n <th class=\"text-center\">Exit Code</th>\n <th class=\"text-center\">Exec Time</th>\n <th class=\"text-center\">Memory</th>\n </tr>\n <tr>\n <td class=\"atcoder-easy-test-result-exit-code text-center\"></td>\n <td class=\"atcoder-easy-test-result-exec-time text-center\"></td>\n <td class=\"atcoder-easy-test-result-memory text-center\"></td>\n </tr>\n </tbody>\n </table>\n </div>\n </div></div>\n <div class=\"row\">\n <div class=\"atcoder-easy-test-result-col-output col-xs-12\" data-if-error=\"col-md-6\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Output\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-output form-control\" rows=\"5\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n <div class=\"atcoder-easy-test-result-col-error col-xs-12 col-md-6 hidden\" data-if-error=\"!hidden\">\n <div class=\"form-group\">\n <label class=\"control-label col-xs-12\">\n Standard Error\n <div class=\"col-xs-12\">\n <textarea class=\"atcoder-easy-test-result-error form-control\" rows=\"5\" readonly=\"readonly\"></textarea>\n </div>\n </label>\n </div>\n </div>\n </div>\n</div>";
  1324.  
  1325. function setClassFromData(element, name) {
  1326. const classes = element.dataset[name].split(/\s+/);
  1327. for (let className of classes) {
  1328. let flag = true;
  1329. if (className[0] == "!") {
  1330. className = className.slice(1);
  1331. flag = false;
  1332. }
  1333. element.classList.toggle(className, flag);
  1334. }
  1335. }
  1336. class ResultTabContent {
  1337. _title;
  1338. _uid;
  1339. _element;
  1340. _result;
  1341. constructor() {
  1342. this._uid = Date.now().toString(16);
  1343. this._result = null;
  1344. this._element = html2element(hTabTemplate);
  1345. this._element.id = `atcoder-easy-test-result-${this._uid}`;
  1346. }
  1347. set result(result) {
  1348. this._result = result;
  1349. if (result.status == "AC") {
  1350. this.outputStyle.backgroundColor = "#dff0d8";
  1351. }
  1352. else if (result.status != "OK") {
  1353. this.outputStyle.backgroundColor = "#fcf8e3";
  1354. }
  1355. this.input = result.input;
  1356. if ("expectedOutput" in result)
  1357. this.expectedOutput = result.expectedOutput;
  1358. this.exitCode = result.exitCode;
  1359. if ("execTime" in result)
  1360. this.execTime = `${result.execTime} ms`;
  1361. if ("memory" in result)
  1362. this.memory = `${result.memory} KB`;
  1363. if ("output" in result)
  1364. this.output = result.output;
  1365. if (result.error)
  1366. this.error = result.error;
  1367. }
  1368. get result() {
  1369. return this._result;
  1370. }
  1371. get uid() {
  1372. return this._uid;
  1373. }
  1374. get element() {
  1375. return this._element;
  1376. }
  1377. set title(title) {
  1378. this._title = title;
  1379. }
  1380. get title() {
  1381. return this._title;
  1382. }
  1383. set input(input) {
  1384. this._get("input").value = input;
  1385. }
  1386. get inputStyle() {
  1387. return this._get("input").style;
  1388. }
  1389. set expectedOutput(output) {
  1390. this._get("expected-output").value = output;
  1391. setClassFromData(this._get("col-input"), "ifExpectedOutput");
  1392. setClassFromData(this._get("col-expected-output"), "ifExpectedOutput");
  1393. }
  1394. get expectedOutputStyle() {
  1395. return this._get("expected-output").style;
  1396. }
  1397. set output(output) {
  1398. this._get("output").value = output;
  1399. }
  1400. get outputStyle() {
  1401. return this._get("output").style;
  1402. }
  1403. set error(error) {
  1404. this._get("error").value = error;
  1405. setClassFromData(this._get("col-output"), "ifError");
  1406. setClassFromData(this._get("col-error"), "ifError");
  1407. }
  1408. set exitCode(code) {
  1409. const element = this._get("exit-code");
  1410. element.textContent = code;
  1411. const isSuccess = code == "0";
  1412. element.classList.toggle("bg-success", isSuccess);
  1413. element.classList.toggle("bg-danger", !isSuccess);
  1414. }
  1415. set execTime(time) {
  1416. this._get("exec-time").textContent = time;
  1417. }
  1418. set memory(memory) {
  1419. this._get("memory").textContent = memory;
  1420. }
  1421. _get(name) {
  1422. return this._element.querySelector(`.atcoder-easy-test-result-${name}`);
  1423. }
  1424. }
  1425.  
  1426. var hRoot = "<form id=\"atcoder-easy-test-container\" class=\"form-horizontal\">\n <div class=\"row\">\n <div class=\"col-xs-12 col-lg-8\">\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\">Test Environment</label>\n <div class=\"col-sm-10\">\n <select class=\"form-control\" id=\"atcoder-easy-test-language\"></select>\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-input\">Standard Input</label>\n <div class=\"col-sm-10\">\n <textarea id=\"atcoder-easy-test-input\" name=\"input\" class=\"form-control\" rows=\"3\"></textarea>\n </div>\n </div>\n </div>\n <div class=\"col-xs-12 col-lg-4\">\n <details close>\n <summary>Expected Output</summary>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-allowable-error-check\">Allowable Error</label>\n <div class=\"col-sm-10\">\n <div class=\"input-group\">\n <span class=\"input-group-addon\">\n <input id=\"atcoder-easy-test-allowable-error-check\" type=\"checkbox\" checked=\"checked\">\n </span>\n <input id=\"atcoder-easy-test-allowable-error\" type=\"text\" class=\"form-control\" value=\"1e-6\">\n </div>\n </div>\n </div>\n <div class=\"form-group\">\n <label class=\"control-label col-sm-2\" for=\"atcoder-easy-test-output\">Expected Output</label>\n <div class=\"col-sm-10\">\n <textarea id=\"atcoder-easy-test-output\" name=\"output\" class=\"form-control\" rows=\"3\"></textarea>\n </div>\n </div>\n </details>\n </div>\n <div class=\"col-xs-12 col-md-6\">\n <div class=\"col-xs-11 col-xs-offset=1\">\n <div class=\"form-group\">\n <a id=\"atcoder-easy-test-run\" class=\"btn btn-primary\">Run</a>\n </div>\n </div>\n </div>\n <div class=\"col-xs-12 col-md-6\">\n <div class=\"col-xs-11 col-xs-offset=1\">\n <div class=\"form-group text-right\">\n <small>AtCoder Easy Test v<span id=\"atcoder-easy-test-version\"></span></small>\n <a id=\"atcoder-easy-test-setting\" class=\"btn btn-xs btn-default\">Setting</a>\n </div>\n </div>\n </div>\n </div>\n <style>\n #atcoder-easy-test-language {\n border: none;\n background: transparent;\n font: inherit;\n color: #fff;\n }\n #atcoder-easy-test-language option {\n border: none;\n color: #333;\n font: inherit;\n }\n </style>\n</form>";
  1427.  
  1428. var hStyle = "<style>\n.atcoder-easy-test-result textarea {\n font-family: monospace;\n font-weight: normal;\n}\n</style>";
  1429.  
  1430. var hRunButton = "<a class=\"btn btn-primary btn-sm\" style=\"vertical-align: top; margin-left: 0.5em\">Run</a>";
  1431.  
  1432. var hTestAndSubmit = "<a id=\"atcoder-easy-test-btn-test-and-submit\" class=\"btn btn-info btn\" style=\"margin-left: 1rem\" title=\"Ctrl+Enter\" data-toggle=\"tooltip\">Test &amp; Submit</a>";
  1433.  
  1434. var hTestAllSamples = "<a id=\"atcoder-easy-test-btn-test-all\" class=\"btn btn-default btn-sm\" style=\"margin-left: 1rem\" title=\"Alt+Enter\" data-toggle=\"tooltip\">Test All Samples</a>";
  1435.  
  1436. (async () => {
  1437. const site = await pSite;
  1438. const doc = unsafeWindow.document;
  1439. // init bottomMenu
  1440. const pBottomMenu = init();
  1441. pBottomMenu.then(bottomMenu => {
  1442. unsafeWindow.bottomMenu = bottomMenu;
  1443. });
  1444. await doneOrFail(pBottomMenu);
  1445. // external interfaces
  1446. unsafeWindow.codeRunner = codeRunner;
  1447. doc.head.appendChild(html2element(hStyle));
  1448. // interface
  1449. const atCoderEasyTest = {
  1450. config,
  1451. codeSaver,
  1452. enableButtons() {
  1453. events.trig("enable");
  1454. },
  1455. disableButtons() {
  1456. events.trig("disable");
  1457. },
  1458. runCount: 0,
  1459. runTest(title, language, sourceCode, input, output = null, options = { trim: true, split: true, }) {
  1460. this.disableButtons();
  1461. const content = new ResultTabContent();
  1462. const pTab = pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test-result-" + content.uid, `#${++this.runCount} ${title}`, content.element, { active: true, closeButton: true }));
  1463. const pResult = codeRunner.run(language, sourceCode, input, output, options);
  1464. pResult.then(result => {
  1465. content.result = result;
  1466. if (result.status == "AC") {
  1467. pTab.then(tab => tab.color = "#dff0d8");
  1468. }
  1469. else if (result.status != "OK") {
  1470. pTab.then(tab => tab.color = "#fcf8e3");
  1471. }
  1472. }).finally(() => {
  1473. this.enableButtons();
  1474. });
  1475. return [pResult, pTab];
  1476. }
  1477. };
  1478. unsafeWindow.atCoderEasyTest = atCoderEasyTest;
  1479. // place "Easy Test" tab
  1480. {
  1481. // declare const hRoot: string;
  1482. const root = html2element(hRoot);
  1483. const E = (id) => root.querySelector(`#atcoder-easy-test-${id}`);
  1484. const eLanguage = E("language");
  1485. const eInput = E("input");
  1486. const eAllowableErrorCheck = E("allowable-error-check");
  1487. const eAllowableError = E("allowable-error");
  1488. const eOutput = E("output");
  1489. const eRun = E("run");
  1490. const eSetting = E("setting");
  1491. E("version").textContent = "2.5.1";
  1492. events.on("enable", () => {
  1493. eRun.classList.remove("disabled");
  1494. });
  1495. events.on("disable", () => {
  1496. eRun.classList.remove("enabled");
  1497. });
  1498. eSetting.addEventListener("click", () => {
  1499. settings.open();
  1500. });
  1501. // 言語選択関係
  1502. {
  1503. eLanguage.addEventListener("change", async () => {
  1504. const langSelection = config.get("langSelection", {});
  1505. langSelection[site.language.value] = eLanguage.value;
  1506. config.set("langSelection", langSelection);
  1507. });
  1508. async function setLanguage() {
  1509. const languageId = site.language.value;
  1510. while (eLanguage.firstChild)
  1511. eLanguage.removeChild(eLanguage.firstChild);
  1512. try {
  1513. const langs = await codeRunner.getEnvironment(languageId);
  1514. console.log(`language: ${langs[1]} (${langs[0]})`);
  1515. // add <option>
  1516. for (const [languageId, label] of langs) {
  1517. const option = document.createElement("option");
  1518. option.value = languageId;
  1519. option.textContent = label;
  1520. eLanguage.appendChild(option);
  1521. }
  1522. // load
  1523. const langSelection = config.get("langSelection", {});
  1524. if (languageId in langSelection) {
  1525. const prev = langSelection[languageId];
  1526. const [lang, _] = langs.find(([lang, label]) => lang == prev);
  1527. if (lang)
  1528. eLanguage.value = lang;
  1529. }
  1530. events.trig("enable");
  1531. }
  1532. catch (error) {
  1533. console.log(`language: ? (${languageId})`);
  1534. console.error(error);
  1535. const option = document.createElement("option");
  1536. option.className = "fg-danger";
  1537. option.textContent = error;
  1538. eLanguage.appendChild(option);
  1539. events.trig("disable");
  1540. }
  1541. }
  1542. site.language.addListener(() => setLanguage());
  1543. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  1544. eAllowableErrorCheck.addEventListener("change", event => {
  1545. eAllowableError.disabled = !eAllowableErrorCheck.checked;
  1546. });
  1547. }
  1548. // テスト実行
  1549. function runTest(title, input, output = null) {
  1550. const options = { trim: true, split: true, };
  1551. if (eAllowableErrorCheck.checked) {
  1552. options.allowableError = parseFloat(eAllowableError.value);
  1553. }
  1554. return atCoderEasyTest.runTest(title, eLanguage.value, site.sourceCode, input, output, options);
  1555. }
  1556. function runAllCases(testcases) {
  1557. const pairs = testcases.map(testcase => runTest(testcase.title, testcase.input, testcase.output));
  1558. resultList.addResult(pairs);
  1559. return Promise.all(pairs.map(([pResult, _]) => pResult.then(result => {
  1560. if (result.status == "AC")
  1561. return Promise.resolve(result);
  1562. else
  1563. return Promise.reject(result);
  1564. })));
  1565. }
  1566. eRun.addEventListener("click", _ => {
  1567. const title = "Run";
  1568. const input = eInput.value;
  1569. const output = eOutput.value;
  1570. runTest(title, input, output || null);
  1571. });
  1572. await doneOrFail(pBottomMenu.then(bottomMenu => bottomMenu.addTab("easy-test", "Easy Test", root)));
  1573. // place "Run" button on each sample
  1574. for (const testCase of site.testCases) {
  1575. const eRunButton = html2element(hRunButton);
  1576. eRunButton.addEventListener("click", async () => {
  1577. const [pResult, pTab] = runTest(testCase.title, testCase.input, testCase.output);
  1578. await pResult;
  1579. (await pTab).show();
  1580. });
  1581. testCase.anchor.insertAdjacentElement("afterend", eRunButton);
  1582. events.on("disable", () => {
  1583. eRunButton.classList.add("disabled");
  1584. });
  1585. events.on("enable", () => {
  1586. eRunButton.classList.remove("disabled");
  1587. });
  1588. }
  1589. // place "Test & Submit" button
  1590. {
  1591. const button = html2element(hTestAndSubmit);
  1592. site.testButtonContainer.appendChild(button);
  1593. const testAndSubmit = async () => {
  1594. await runAllCases(site.testCases);
  1595. site.submit();
  1596. };
  1597. button.addEventListener("click", testAndSubmit);
  1598. events.on("testAndSubmit", testAndSubmit);
  1599. }
  1600. // place "Test All Samples" button
  1601. {
  1602. const button = html2element(hTestAllSamples);
  1603. site.testButtonContainer.appendChild(button);
  1604. const testAllSamples = () => runAllCases(site.testCases);
  1605. button.addEventListener("click", testAllSamples);
  1606. events.on("testAllSamples", testAllSamples);
  1607. }
  1608. }
  1609. // place "Restore Last Play" button
  1610. try {
  1611. const restoreButton = doc.createElement("a");
  1612. restoreButton.className = "btn btn-danger btn-sm";
  1613. restoreButton.textContent = "Restore Last Play";
  1614. restoreButton.addEventListener("click", async () => {
  1615. try {
  1616. const lastCode = await codeSaver.restore();
  1617. if (site.sourceCode.length == 0 || confirm("Your current code will be replaced. Are you sure?")) {
  1618. site.sourceCode = lastCode;
  1619. }
  1620. }
  1621. catch (reason) {
  1622. alert(reason);
  1623. }
  1624. });
  1625. site.sideButtonContainer.appendChild(restoreButton);
  1626. }
  1627. catch (e) {
  1628. console.error(e);
  1629. }
  1630. // キーボードショートカット
  1631. unsafeWindow.addEventListener("keydown", (event) => {
  1632. if (config.get("useKeyboardShortcut", true)) {
  1633. if (event.key == "Enter" && event.ctrlKey) {
  1634. events.trig("testAndSubmit");
  1635. }
  1636. else if (event.key == "Enter" && event.altKey) {
  1637. events.trig("testAllSamples");
  1638. }
  1639. else if (event.key == "Escape" && event.altKey) {
  1640. pBottomMenu.then(bottomMenu => bottomMenu.toggle());
  1641. }
  1642. }
  1643. });
  1644. })();
  1645. })();