Download app.js from GameAnything/gameanything-submit: direct link, hf CLI and curl.
- Browser
- Download file 48.2 kB
-
https://huggingface.co/spaces/GameAnything/gameanything-submit/resolve/main/app.js
- Command line
-
hf download hf://spaces/GameAnything/gameanything-submit/app.js
-
curl -L -o app.js https://huggingface.co/spaces/GameAnything/gameanything-submit/resolve/main/app.js
48.2 kB
| // GameAnything-Bench task submission page (static). Texts, choices and limits come from data.json, which | |
| // export_static.py writes from validator.py / texts.py / examples.py; the checks below mirror validator.py. | |
| // A submission becomes a pull request on the private dataset REPO. With D.submit_url set, the form is posted to | |
| // server.py, which checks it again and opens the pull request (no account needed). Without it, the person signs in | |
| // with Hugging Face and the page opens the pull request with their own token (works for organisation members only). | |
| import {oauthLoginUrl, oauthHandleRedirectIfPresent, uploadFiles} from "https://cdn.jsdelivr.net/npm/@huggingface/hub@0.18.2/+esm"; | |
| const REPO = {type: "dataset", name: "GameAnything/gameanything-submissions"}; | |
| const $ = (s, el = document) => el.querySelector(s), $$ = (s, el = document) => [...el.querySelectorAll(s)]; | |
| const esc = s => String(s).replace(/[&<>"]/g, c => ({"&": "&", "<": "<", ">": ">", '"': """}[c])); | |
| const LOCAL = { // texts only this page needs | |
| signin: ["Sign in with Hugging Face", "用 Hugging Face 登录"], | |
| signin_why: ["Needed to submit. You can fill the form first; what you type is kept.", "提交时需要登录。可以先填表,已填的内容会保留。"], | |
| signed: ["Signed in as", "已登录:"], | |
| need_signin: ["Please sign in with Hugging Face first (above the form). What you typed is kept.", "请先用 Hugging Face 登录(在表单上方)。已填的内容会保留。"], | |
| sending: ["Submitting…", "正在提交……"], | |
| no_access: ["Your account cannot write to the submissions repository yet. Ask a maintainer for access to the GameAnything organisation.", | |
| "你的账号还没有提交仓库的写权限,请联系维护者加入 GameAnything 组织。"], | |
| drop: ["Click to choose files, or drop them here", "点击选择文件,或拖到这里"], | |
| drop_sub: ["png · jpg · webp · mp4 · webm · mov · txt · md", "png · jpg · webp · mp4 · webm · mov · txt · md"], | |
| sec_ref: ["Reference", "素材"], sec_task: ["Task", "题目"], sec_you: ["Credit", "署名"], | |
| h_len: ["{a}–{b} {u}", "{a}–{b} {u}"], h_where: ["pick where the reference shows it", "请选素材里的位置"], | |
| cta_start: ["Write a challenge ↓", "开始出题 ↓"], cta_example: ["See an example first", "先看一道例题"], | |
| ex_s1: ["The reference", "带来的素材"], ex_s2: ["What the AI should build", "想让 AI 做成什么"], ex_s3: ["What counts as done", "怎样算做对"], | |
| ex_s3_more: ["{n} scoring points in all; one of each kind is shown here.", "这道题一共 {n} 条评分点,这里每类只列一条。"], | |
| exbar: ["Examples", "参考例子"], exbar_sub: ["Click into any field and the example's answer for that field appears under it.", "点进任何一栏,它下面就会出现例题在这一栏的写法。"], | |
| ex_all_open: ["Show all", "全部展开"], ex_all_close: ["Hide all", "全部收起"], ex_open: ["See the example for this field ▾", "看这一栏的例子 ▾"], | |
| ex_label: ["Example", "例子"], ex_close: ["Hide", "收起"], | |
| f_img: ["img", "图"], f_video: ["video", "视频"], f_text: ["text", "文本"], f_paras: ["{n} paragraphs", "{n} 段"], f_remove: ["Remove", "移除"], | |
| clip_a: ["Set clip start here", "设为片段开始"], clip_b: ["Set clip end here", "设为片段结束"], | |
| p_pick: ["Where the reference shows it:", "素材里哪里能看到:"], | |
| p_pick_none: ["Where the reference shows it (add your reference above and you can simply pick here):", "素材里哪里能看到(先在上面“素材”里上传文件或贴链接,这里就能直接点选):"], | |
| p_time_ph: ["time, e.g. 0:35–0:40", "时间,如 0:35–0:40"], p_now: ["Current time", "取当前时间"], p_para_add: ["+ pick a paragraph…", "+ 选段落…"], | |
| para: ["para {n}", "第 {n} 段"], strip: ["Play the clip here. “Current time” in a point fills in where the player is.", "在这里播放视频;在某条评分点里点“取当前时间”,就会填入当前播放位置。"], | |
| h_negative: ["write what must be there, not what must be absent", "请写“要有什么”,不要写“不能有什么”"], | |
| h_vague: ["name something that can be seen or tried", "请写看得到、试得出的具体内容"], | |
| ex_ref: ["Reference", "素材"], ex_fit: ["Why this game fits", "为什么适合这款游戏"], | |
| ex_idea: ["What should the AI build?", "想让 AI 做成什么"], ex_edit: ["Follow-up edit", "后续修改"], hours_ph: ["Hours played…", "玩了多久……"], | |
| }; | |
| let D, lang = "en", OA = null, screenState = null, verdictShown = false, files = [], modFiles = [], exTab = 0, exOpen = new Set(), exAuto = new Set(); | |
| // form zones: clicking into one shows the example's answer for it (once; after that the person decides) | |
| const ZONE = {fit: "#fit", ref: "#drop, #link, #time_range", category: "#category", idea: "#idea", edit: "#edit", | |
| content: "#content_rows", function: "#function_rows", visual: "#visual_rows"}; | |
| const li = () => D.langs.indexOf(lang); | |
| const fmt = (s, kw = {}) => s.replace(/\{(\w+)(?::\.(\d)f)?\}/g, (_, k, p) => p != null ? Number(kw[k]).toFixed(+p) : kw[k] ?? ""); | |
| const t = (k, kw) => fmt((D.text[k] || LOCAL[k])[li()], {u: D.unit[lang], ...kw}), msg = (k, kw) => fmt(D.msg[k][li()], {u: D.unit[lang], ...kw}); | |
| const rich = s => esc(s).replace(/\*\*(.+?)\*\*/g, "<b>$1</b>").replace(/`(.+?)`/g, "<code>$1</code>").replace(/^### (.*)$/m, "<h3>$1</h3>").replace(/\n\n/g, "<br>"); | |
| // ---------------------------------------------------------------- checks (mirror of validator.py) | |
| const CJK = /[㐀-鿿]/g, WORD = /\p{L}+|\d+/gu; | |
| const cjkN = s => (s.match(CJK) || []).length, wordN = s => (s.replace(CJK, " ").match(WORD) || []).length; | |
| const size = s => lang === "zh" ? cjkN(s) + Math.floor((3 * wordN(s) + 1) / 2) : wordN(s) + Math.floor((2 * cjkN(s) + 2) / 3); | |
| const lim = k => D.limits[k].map(x => Math.floor(x * D.scale[lang])); | |
| const WHERE = /\d{1,2}:\d{2}|图\s*\d|第\s*\d+\s*[段张页章幕]|\b(imgs?|images?|photos?|pictures?|figs?|paras?|paragraphs?|ch|chapters?|pages?|pp?)\.?\s*\d|段落|开头|结尾|\b(opening|ending|first|last) (scene|shot|line|paragraph|image)/i; | |
| const RANGE = /^\s*(\d{1,2}:)?\d{1,2}:\d{2}(\.\d+)?\s*[-–~到至]\s*(\d{1,2}:)?\d{1,2}:\d{2}(\.\d+)?\s*$/; | |
| const NEGATIVE = /^\s*(no\b|not\b|never\b|don'?t\b|must not\b|should not\b|without\b|不能|不要|不可|不许|没有|禁止)/i; | |
| const VAGUE = /\b(awesome|beautiful|realistic|faithful|accurate|high[- ]quality|looks? like the (video|image|reference|original))\b|好看|好玩|逼真|还原度高|高质量|精美|酷炫|和(原片|视频|图片|素材)一样/i; | |
| const ext = n => (n.match(/\.[^.]+$/) || [""])[0].toLowerCase(); | |
| const kind = n => D.ext.image.includes(ext(n)) ? "image" : D.ext.video.includes(ext(n)) ? "video" : D.ext.text.includes(ext(n)) ? "text" : ""; | |
| const norm = p => p.replace(/[((][^()()]*[))]/g, " ").replace(/[^\p{L}\p{N}]+/gu, " ").trim().toLowerCase(); | |
| const seconds = x => x.trim().split(":").reduce((a, b) => a * 60 + parseFloat(b), 0); | |
| const clipBounds = r => r.trim().split(/\s*[-–~到至]\s*/).map(seconds); | |
| const lowEffort = s => { const tk = [...(s.match(CJK) || []), ...(s.replace(CJK, " ").match(WORD) || [])].map(x => x.toLowerCase()); | |
| return /(.)\1{4,}/u.test(s) || (tk.length >= 10 && new Set(tk).size / tk.length < 0.34); }; | |
| const quote = xs => xs.map(x => `“${x.length <= 44 ? x : x.slice(0, 42) + "…"}”`).join(" / "); | |
| const pointIssue = p => { const [a, b] = lim("point"), n = size(p.text); return n < a || n > b ? "len" : NEGATIVE.test(p.text) ? "negative" : VAGUE.test(p.text) ? "vague" : !WHERE.test(p.where) ? "where" : ""; }; | |
| function knownGames(genres) { | |
| const ids = []; | |
| for (const [, g] of D.choices.genres.en) if (genres.includes(g)) for (const id of D.genre_games[g]) if (!ids.includes(id)) ids.push(id); | |
| if (genres.includes("other")) for (const id of D.game_ids) if (!ids.includes(id)) ids.push(id); | |
| return ids; | |
| } | |
| function screen(genres, modding) { // genres: {kind: hours band} | |
| const kinds = Object.keys(genres); | |
| if (!kinds.length) return {ok: false, message: msg("need_genre")}; | |
| if (kinds.some(g => !genres[g])) return {ok: false, message: msg("need_hours_answer")}; | |
| if (!modding) return {ok: false, message: msg("need_modding_answer")}; | |
| const first = knownGames(kinds); // nobody is turned away: every game is open, those of the ticked kinds first | |
| return {ok: true, games: [...first, ...D.game_ids.filter(id => !first.includes(id))]}; | |
| } | |
| const videoSeconds = f => new Promise(res => { const v = document.createElement("video"); v.preload = "metadata"; | |
| v.onloadedmetadata = () => { URL.revokeObjectURL(v.src); res(v.duration); }; v.onerror = () => res(NaN); v.src = URL.createObjectURL(f); }); | |
| async function check(v) { | |
| const errors = [], warnings = [], M = D.max, L = D.limits, MB = 1e6; | |
| if (!screenState) return {errors: [msg("screen_first")]}; | |
| const points = v.points; | |
| if (v.game === D.new_game) { const g = v.new_game, [na, nb] = lim("new_modding"), n = size(g.modding); | |
| if (g.name.length < 2 || g.name.length > 60) errors.push(msg("new_name")); | |
| if (!/^https?:\/\/\S+$/.test(g.link)) errors.push(msg("new_link")); | |
| if (n < na || n > nb) errors.push(msg("new_modding_len", {a: na, b: nb, n})); else if (lowEffort(g.modding)) errors.push(msg("low_effort", {x: g.modding.slice(0, 44)})); | |
| if (!g.help) errors.push(msg("new_help")); } | |
| else if (!D.game_track[v.game]) errors.push(msg("game"));; | |
| if (v.mod_link && !/^https?:\/\/\S+$/.test(v.mod_link)) errors.push(msg("mod_link")); | |
| if (modFiles.length > L.mod_files) errors.push(msg("mod_files_max", {m: L.mod_files, n: modFiles.length})); | |
| for (const f of modFiles) { const k = kind(f.name); | |
| if (k !== "image" && k !== "video") errors.push(msg("mod_file_type", {x: f.name})); else if (f.size > M[k]) errors.push(msg("file_big", {x: f.name, s: f.size / MB, c: M[k] / MB})); } | |
| if (!v.category) errors.push(msg("category")); | |
| if (!v.license) errors.push(msg("license")); | |
| if (!files.length && !v.link) errors.push(msg("no_ref")); | |
| if (v.link && !/^https?:\/\/\S+$/.test(v.link)) errors.push(msg("link")); | |
| if (v.time_range && !RANGE.test(v.time_range)) errors.push(msg("range")); | |
| if (files.length > M.files) errors.push(msg("max_files", {m: M.files, n: files.length})); | |
| let total = 0; | |
| for (const f of files) { | |
| total += f.size; const k = kind(f.name); | |
| if (!k) { errors.push(msg("file_type", {x: f.name})); continue; } | |
| if (!f.size) errors.push(msg("file_empty", {x: f.name})); | |
| if (f.size > M[k]) errors.push(msg("file_big", {x: f.name, s: f.size / MB, c: M[k] / MB})); | |
| } | |
| if (total > M.total) errors.push(msg("total_big", {s: total / MB, c: M.total / MB})); | |
| const kinds = files.map(f => kind(f.name)), hasVideo = kinds.includes("video"), [c0, c1] = L.clip_seconds; | |
| if (v.license === "third_party") { if (files.length) errors.push(msg("third_files")); if (!v.link) errors.push(msg("third_link")); } | |
| if (["public_domain", "cc"].includes(v.license) && !v.source) errors.push(msg("source")); | |
| if (v.link && !files.length && !v.time_range) warnings.push(msg("w_range_link")); | |
| let clip = null; | |
| if (v.time_range && RANGE.test(v.time_range)) { clip = clipBounds(v.time_range); const n = Math.round(clip[1] - clip[0]); if (n < c0 || n > c1) errors.push(msg("clip_len", {a: c0, b: c1, x: v.time_range, n})); } | |
| else if (hasVideo) for (const f of files.filter(f => kind(f.name) === "video")) { // a whole uploaded video is the reference | |
| const n = Math.round(await videoSeconds(f)); | |
| if (n > c1) errors.push(msg("clip_len", {a: c0, b: c1, x: f.name, n})); else if (!(n >= c0)) warnings.push(msg("w_range_video")); | |
| } | |
| if (kinds.length && kinds.every(k => k === "image") && !v.link && files.length < L.images) errors.push(msg("few_images", {m: L.images, n: files.length})); | |
| const tm = Math.floor(L.text_units * D.scale[lang]); | |
| for (const f of files) if (kind(f.name) === "text" && f.size <= M.text) { const n = size(await f.text()); if (n < tm) errors.push(msg("short_text", {x: f.name, n, m: tm})); } | |
| const length = (key, text, label) => { const [a, b] = lim(key), n = size(text); if (n < a || n > b) errors.push(msg(label, {a, b, n})); }; | |
| length("idea", v.idea, "idea_len"); length("fit", v.fit, "fit_len"); if (v.edit) length("edit", v.edit, "edit_len"); | |
| for (const d of D.dims) { const k = points[d.id].length, name = d.label[li()]; | |
| if (k < d.min) errors.push(msg("dim_min", {d: name, m: d.min, n: k})); | |
| if (k > L.points_per_dim) errors.push(msg("dim_max", {d: name, m: L.points_per_dim, n: k})); } | |
| const flat = D.dims.flatMap(d => points[d.id]), texts = flat.map(p => p.text), norms = texts.map(norm), [a, b] = lim("point"), all = [v.idea, v.fit, v.edit, ...texts].filter(Boolean); | |
| for (const [key, bad] of [["point_len", texts.filter(x => size(x) < a || size(x) > b)], ["point_where", flat.filter(p => !WHERE.test(p.where)).map(p => p.text || "…")], | |
| ["point_negative", texts.filter(x => NEGATIVE.test(x))], ["point_vague", texts.filter(x => VAGUE.test(x))], | |
| ["point_dup", [...new Set(texts.filter(x => x && norms.filter(y => y === norm(x)).length > 1))].sort()], | |
| ["low_effort", all.filter(lowEffort)], ["copied", all.filter(x => D.copied.includes(norm(x)))]]) | |
| if (bad.length) errors.push(msg(key, {a, b, x: quote(bad)})); | |
| const nImg = kinds.filter(k => k === "image").length; | |
| if (nImg && !v.link) { const cited = flat.flatMap(p => [...p.where.matchAll(/(?:imgs?|images?|photos?|pictures?|图)\.?\s*(\d+)/gi)].map(m => +m[1])); | |
| if (cited.length && Math.max(...cited) > nImg) errors.push(msg("where_img", {n: Math.max(...cited), m: nImg})); } | |
| if (clip) for (const p of flat) { const out = (p.where.match(/\d{1,2}:\d{2}(?::\d{2})?/g) || []).filter(x => !((clip[0] - 1 <= seconds(x) && seconds(x) <= clip[1] + 1) || seconds(x) <= clip[1] - clip[0] + 1)); | |
| if (out.length) { errors.push(msg("where_time", {x: out[0], r: v.time_range})); break; } } | |
| const visibility = v.license === "third_party" ? "private" : "public"; | |
| if (visibility === "private") warnings.push(msg("w_private")); | |
| if (!v.ack) errors.push(msg("ack")); | |
| if (v.nickname.length < 1 || v.nickname.length > 40) errors.push(msg("nickname")); | |
| if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email)) errors.push(msg("email")); | |
| if (!v.consent) errors.push(msg("consent")); | |
| if (errors.length) return {errors}; | |
| const ks = new Set(kinds); | |
| if (v.link && (v.time_range || !ks.size)) ks.add("video"); | |
| return {errors, warnings, points, visibility, modality: ks.size > 1 ? "hybrid" : [...ks][0] || "video"}; | |
| } | |
| // ---------------------------------------------------------------- reading the form | |
| const radio = name => ($(`input[name=${name}]:checked`) || {}).value || ""; | |
| const boxes = name => $$(`input[name=${name}]:checked`).map(x => x.value); | |
| const val = id => $("#" + id).value.trim(); | |
| const genreHours = () => Object.fromEntries(boxes("genres").map(g => [g, ($(`#hours select[data-g=${g}]`) || {}).value || ""])); | |
| const readPoints = () => Object.fromEntries(D.dims.map(d => [d.id, $$(`#${d.id}_rows .point`).map(r => ({text: $("textarea", r).value.trim(), where: whereOf(r)})) | |
| .filter(p => p.text || p.where)])); | |
| const draftPoints = () => Object.fromEntries(D.dims.map(d => [d.id, $$(`#${d.id}_rows .point`).map(r => ({text: $("textarea", r).value, imgs: r._ref.imgs, paras: r._ref.paras, extra: $("input", r).value}))])); | |
| // the reference, by kind; images are numbered in upload order (img 1, img 2 ...), paragraphs run through the text files | |
| const imgFiles = () => files.filter(f => kind(f.name) === "image"), vidFiles = () => files.filter(f => kind(f.name) === "video"); | |
| const paras = () => files.filter(f => kind(f.name) === "text").flatMap(f => f._paras || []); | |
| const clock = s => `${Math.floor(s / 60)}:${String(Math.floor(s % 60)).padStart(2, "0")}`; | |
| const splitParas = s => { const a = s.replace(/\r/g, "").split(/\n\s*\n/).map(x => x.trim()).filter(Boolean); return a.length > 1 ? a : s.split(/\n/).map(x => x.trim()).filter(Boolean); }; | |
| function whereOf(row) { // the location as text, e.g. "img 2; img 3" or "0:35–0:40" | |
| const r = row._ref, nI = imgFiles().length, nP = paras().length, tp = $(".timepick", row); | |
| return [...r.imgs.filter(n => n <= nI).sort((a, b) => a - b).map(n => `${t("f_img")} ${n}`), ...r.paras.filter(n => n <= nP).sort((a, b) => a - b).map(n => t("para", {n})), | |
| ...(tp.hidden ? [] : [$("input", tp).value.trim()])].filter(Boolean).join(lang === "zh" ? ";" : "; "); | |
| } | |
| const isMaker = () => D.makers.includes(radio("modding")); | |
| const form = () => ({game: radio("game"), new_game: {name: val("new_name"), link: val("new_link"), modding: val("new_modding"), help: radio("new_help")}, | |
| mod_link: isMaker() ? val("mod_link") : "", mod_note: isMaker() ? val("mod_note").slice(0, 300) : "", category: radio("category"), link: val("link"), time_range: val("time_range"), license: radio("license"), | |
| source: val("source"), fit: val("fit"), idea: val("idea"), points: readPoints(), edit: val("edit"), nickname: val("nickname"), email: val("email"), | |
| ack: $("#ack").checked, consent: $("#consent").checked}); | |
| // ---------------------------------------------------------------- rendering | |
| function options(el, name, type, key) { // radio / checkbox group that keeps its answers across languages | |
| const keep = type === "radio" ? [radio(name)] : boxes(name); | |
| el.innerHTML = D.choices[key][lang].map(([label, id]) => { | |
| const [a, b] = label.split(" → "); | |
| return `<label class="opt"><input type="${type}" name="${name}" value="${id}"${keep.includes(id) ? " checked" : ""}><span>${esc(a)}${b ? ` <em>→ ${esc(b)}</em>` : ""}</span></label>`; | |
| }).join(""); | |
| } | |
| function renderHours(preset) { // one hours question per ticked kind | |
| const keep = preset || genreHours(), label = Object.fromEntries(D.choices.genres[lang].map(([l, id]) => [id, l.split(" → ")[0]])); | |
| const kinds = boxes("genres"); | |
| $("#hours").innerHTML = kinds.length ? kinds.map(g => `<label class="hrow"><span>${esc(label[g])}</span><select data-g="${g}" aria-label="${esc(label[g])}">` + | |
| `<option value="">${t("hours_ph")}</option>${D.choices.hours[lang].map(([l, id]) => `<option value="${id}"${keep[g] === id ? " selected" : ""}>${esc(l)}</option>`).join("")}</select></label>`).join("") | |
| : `<p class="info">${t("q_hours_none")}</p>`; | |
| } | |
| function pointRow(d, p = {}) { | |
| const row = document.createElement("div"); row.className = "point"; row._ref = {imgs: [...(p.imgs || [])], paras: [...(p.paras || [])]}; | |
| row.innerHTML = `<span class="pn"></span><div class="pbody"><textarea rows="2"></textarea>` + | |
| `<div class="pwhere"><span class="plab"></span><div class="imgpick"></div><div class="parapick"></div>` + | |
| `<span class="timepick"><input type="text"><button type="button" class="now"></button></span><button type="button" class="x">×</button></div><div class="count"></div></div>`; | |
| $("textarea", row).value = p.text || ""; $("input", row).value = p.extra ?? p.where ?? ""; | |
| $(".x", row).onclick = () => { row.remove(); labelRows(); counters(); stale(); }; | |
| $(".now", row).onclick = () => { // the player's position goes into the time field: first click a start, second click the end | |
| const v = $("#refstrip video"); if (!v) return; | |
| const inp = $("input", row), now = clock(v.currentTime), cur = inp.value.trim(); | |
| inp.value = !/^\d{1,2}:\d{2}$/.test(cur) ? now : seconds(cur) <= v.currentTime ? `${cur}–${now}` : `${now}–${cur}`; counters(); stale(); }; | |
| return row; | |
| } | |
| function renderPicks(row) { // what a point can cite follows the reference: image tiles, paragraphs, a time | |
| const r = row._ref, imgs = imgFiles(), ps = paras(), hasVid = vidFiles().length > 0, timed = hasVid || !!val("link"), none = !files.length && !val("link"); | |
| const act = () => { renderPicks(row); counters(); stale(); }; | |
| $(".plab", row).textContent = t(none ? "p_pick_none" : "p_pick"); | |
| $(".imgpick", row).innerHTML = imgs.map((f, k) => { const on = r.imgs.includes(k + 1); | |
| return `<button type="button" class="imgtile${on ? " on" : ""}" data-n="${k + 1}" aria-pressed="${on}" aria-label="${t("f_img")} ${k + 1}"><img src="${f._url}" alt=""><span>${t("f_img")} ${k + 1}</span></button>`; }).join(""); | |
| $$(".imgtile", row).forEach(b => b.onclick = () => { const n = +b.dataset.n; r.imgs = r.imgs.includes(n) ? r.imgs.filter(x => x !== n) : [...r.imgs, n]; act(); }); | |
| const chosen = r.paras.filter(n => n <= ps.length).sort((a, b) => a - b); | |
| $(".parapick", row).innerHTML = !ps.length ? "" : chosen.map(n => `<button type="button" class="parachip" data-n="${n}" title="${esc(ps[n - 1].slice(0, 200))}">${t("para", {n})} ×</button>`).join("") + | |
| `<select aria-label="${t("p_para_add")}"><option value="">${t("p_para_add")}</option>${ps.map((p, k) => `<option value="${k + 1}"${r.paras.includes(k + 1) ? " disabled" : ""}>${t("para", {n: k + 1})}: ${esc(p.slice(0, 36))}${p.length > 36 ? "…" : ""}</option>`).join("")}</select>`; | |
| $$(".parachip", row).forEach(b => b.onclick = () => { r.paras = r.paras.filter(x => x !== +b.dataset.n); act(); }); | |
| const sel = $("select", row); if (sel) sel.onchange = () => { if (sel.value) r.paras.push(+sel.value); act(); }; | |
| const tp = $(".timepick", row), inp = $("input", tp); tp.hidden = !(timed || (!imgs.length && !ps.length)); | |
| inp.placeholder = t(timed ? "p_time_ph" : "p_where_ph"); inp.setAttribute("aria-label", t("p_where")); | |
| $(".now", row).hidden = !hasVid; $(".now", row).textContent = "⏱ " + t("p_now"); | |
| } | |
| function labelRows() { | |
| for (const d of D.dims) { | |
| const rows = $$(`#${d.id}_rows .point`); | |
| rows.forEach((r, i) => { $(".pn", r).textContent = i + 1; const ta = $("textarea", r); | |
| ta.placeholder = i === 0 ? t(d.id + "_ph") : ""; ta.setAttribute("aria-label", `${d.label[li()]} · ${t("p_n", {i: i + 1})}`); | |
| renderPicks(r); $(".x", r).setAttribute("aria-label", t("p_remove")); $(".x", r).title = t("p_remove"); | |
| $(".x", r).hidden = rows.length <= d.min; }); | |
| $(`#${d.id}_add`).hidden = rows.length >= D.limits.points_per_dim; | |
| } | |
| } | |
| function setPoints(points) { | |
| for (const d of D.dims) { const box = $(`#${d.id}_rows`); box.innerHTML = ""; | |
| const ps = [...(points?.[d.id] || [])]; while (ps.length < d.min) ps.push({}); | |
| ps.forEach(p => box.appendChild(pointRow(d, p))); } | |
| labelRows(); | |
| } | |
| function fillGames(preferred) { // every game as a tile, the games of the ticked kinds first | |
| const cur = preferred || radio("game"), order = screenState ? screenState.games : D.game_ids; | |
| $("#game").innerHTML = order.map(id => { | |
| const label = D.choices.games[lang].find(([, g]) => g === id)[0], m = label.match(/[((](.*)[))]/); | |
| const note = (m ? m[1] : "").replace(/^(open source|开源)[,,]\s*/, ""); | |
| return `<label class="tile"><input type="radio" name="game" value="${id}"${cur === id ? " checked" : ""}>` + | |
| `<img src="data/games/${id}.jpg" alt="" loading="lazy"><div><b>${esc(D.game_short[lang][id])}</b><span>${esc(note)}</span>` + | |
| `<i>${D.game_track[id] === "core" ? t("open_source") : ""}</i></div></label>`; | |
| }).join("") + `<label class="tile new"><input type="radio" name="game" value="${D.new_game}"${cur === D.new_game ? " checked" : ""}>` + | |
| `<span class="plus" aria-hidden="true">+</span><div><b>${t("game_new")}</b><span>${t("game_new_sub")}</span><i>${t("game_new_tag")}</i></div></label>`; | |
| showNew(); | |
| } | |
| const showNew = () => { $("#newgame").hidden = radio("game") !== D.new_game; }; | |
| const showMod = () => { $("#modbox").hidden = !isMaker(); }; | |
| function renderModFiles() { | |
| $("#mod_filelist").innerHTML = modFiles.map((f, i) => `<li><span class="kind">${kind(f.name) || "?"}</span>${esc(f.name)} <small>${(f.size / 1e6).toFixed(1)} MB</small><button type="button" data-i="${i}" aria-label="remove ${esc(f.name)}">×</button></li>`).join(""); | |
| $$("#mod_filelist button").forEach(b => b.onclick = () => { modFiles.splice(+b.dataset.i, 1); renderModFiles(); stale(); }); | |
| } | |
| function showVerdict() { | |
| const s = screen(genreHours(), radio("modding")); | |
| $("#verdict").innerHTML = s.ok ? rich(t("v_ok")) : esc(s.message); | |
| $("#verdict").className = "verdict " + (s.ok ? "ok" : "wait"); return s; | |
| } | |
| function renderFiles() { // the reference as cards; images carry the number the points cite | |
| let ni = 0; | |
| $("#filelist").innerHTML = files.map((f, i) => { const k = kind(f.name); | |
| const body = k === "image" ? `<img src="${f._url}" alt=""><span class="badge">${t("f_img")} ${++ni}</span>` | |
| : k === "video" ? `<video src="${f._url}" controls preload="metadata"></video><span class="badge">${t("f_video")}</span>` + | |
| `<div class="clipset"><button type="button" data-clip="0">${t("clip_a")}</button><button type="button" data-clip="1">${t("clip_b")}</button></div>` | |
| : `<div class="txt">${esc((f._paras || []).join("\n\n").slice(0, 240))}</div><span class="badge">${t("f_text")} · ${t("f_paras", {n: (f._paras || []).length})}</span>`; | |
| return `<figure class="refcard ${k}">${body}<figcaption><span>${esc(f.name)}</span><small>${(f.size / 1e6).toFixed(1)} MB</small>` + | |
| `<button type="button" class="rm" data-i="${i}" aria-label="${t("f_remove")} ${esc(f.name)}" title="${t("f_remove")}">×</button></figcaption></figure>`; }).join(""); | |
| $$("#filelist .rm").forEach(b => b.onclick = () => removeFile(+b.dataset.i)); | |
| $$("#filelist [data-clip]").forEach(b => b.onclick = () => { // the clip to use, taken from the player | |
| const v = $("video", b.closest(".refcard")), parts = val("time_range").split(/\s*[-–~到至]\s*/); parts[+b.dataset.clip] = clock(v.currentTime); | |
| $("#time_range").value = `${parts[0] || ""}-${parts[1] || ""}`; stale(); }); | |
| } | |
| function removeFile(i) { // the points follow: later images move up one number | |
| const f = files[i], k = kind(f.name); | |
| if (k === "image") { const n = imgFiles().indexOf(f) + 1; for (const r of $$(".point")) r._ref.imgs = r._ref.imgs.filter(x => x !== n).map(x => x > n ? x - 1 : x); } | |
| if (k === "text") for (const r of $$(".point")) r._ref.paras = []; | |
| if (f._url) URL.revokeObjectURL(f._url); | |
| files.splice(i, 1); refreshRefs(); stale(); | |
| } | |
| function renderStrip() { // an uploaded clip stays in view while the points are written | |
| const v = vidFiles()[0], box = $("#refstrip"), cur = $("video", box); | |
| box.hidden = !v; if (!v) { box.innerHTML = ""; return; } | |
| if (!cur || cur.dataset.name !== v.name) box.innerHTML = `<video src="${v._url}" controls preload="metadata" data-name="${esc(v.name)}"></video><p></p>`; | |
| $("p", box).textContent = t("strip"); | |
| } | |
| function refreshRefs() { renderFiles(); renderStrip(); $$(".point").forEach(renderPicks); counters(); } | |
| function renderAuth() { | |
| if (D.submit_url) { $("#auth").hidden = true; return; } // the submission service needs no account | |
| $("#auth").innerHTML = OA ? `<span class="who">${t("signed")} <b>${esc(OA.userInfo.preferred_username || OA.userInfo.name)}</b></span>` | |
| : `<button type="button" id="login" class="btn">${t("signin")}</button><span>${t("signin_why")}</span>`; | |
| if (!OA) $("#login").onclick = async () => { saveDraft(); window.location.href = (await oauthLoginUrl({scopes: "openid profile read-repos write-repos write-discussions"})) + "&prompt=consent"; }; | |
| } | |
| const exMedia = e => e.images.length ? `<div class="gallery">${e.images.map(([src, cap]) => `<a href="${src}" target="_blank" rel="noopener"><img src="${src}" alt="${esc(cap)}" loading="lazy"><span>${esc(cap.replace("img", t("f_img")))}</span></a>`).join("")}</div>` | |
| : e.video ? `<video src="${e.video}" controls preload="metadata"></video>` | |
| : `<figure class="quote"><figcaption>${t("ex_excerpt")}</figcaption>${e.quote.map(p => `<p>${esc(p)}</p>`).join("")}</figure>`; | |
| function renderExample() { // top of the page: reference -> what to build -> what counts as done | |
| const e = D.examples[exTab], i = li(), n = D.dims.reduce((s, d) => s + e.points[d.id].length, 0); | |
| $$("#ex_tabs button, #exf_tabs button").forEach(b => { const on = +b.dataset.i === exTab; b.classList.toggle("on", on); b.setAttribute("aria-selected", on); }); | |
| const brief = D.dims.map(d => { const p = e.points[d.id][0]; return `<div class="dim ${d.id}"><h5>${esc(d.label[i])}</h5><p>${esc(p[i])}<span class="where">${esc(p[2 + i])}</span></p></div>`; }).join(""); | |
| const head = (k, key) => `<h4><b>${k}</b>${t(key)}</h4>`; | |
| $("#ex_body").innerHTML = `<div class="flow"><div class="fcol">${head(1, "ex_s1")}${exMedia(e)}<p class="ex_ref">${esc(e.reference[i])}</p></div>` + | |
| `<div class="fcol">${head(2, "ex_s2")}<div class="chips"><span>${esc(e.game[i])}</span><span>${esc(e.category[i])}</span></div><p class="ex_idea">${esc(e.idea[i])}</p></div>` + | |
| `<div class="fcol">${head(3, "ex_s3")}<div class="dims">${brief}</div><p class="ex_ref">${t("ex_s3_more", {n})}</p></div></div>`; | |
| renderHints(); | |
| } | |
| function renderHints() { // in the form: under each field, what the chosen example wrote there | |
| const e = D.examples[exTab], i = li(), pts = d => `<ol>${e.points[d].map(p => `<li>${esc(p[i])}<span class="where">${esc(p[2 + i])}</span></li>`).join("")}</ol>`; | |
| const hint = {fit: `<p>${esc(e.game[i])}: ${esc(e.fit[i])}</p>`, ref: `${exMedia(e)}<p>${esc(e.reference[i])}</p>${e.credit ? `<p class="credit">${esc(e.credit)}</p>` : ""}`, | |
| category: `<p>${esc(e.category[i])}</p>`, idea: `<p>${esc(e.idea[i])}</p>`, edit: `<p>${esc(e.edit[i])}</p>`, content: pts("content"), function: pts("function"), visual: pts("visual")}; | |
| const segs = D.examples.map((x, n) => `<button type="button" data-i="${n}"${n === exTab ? ' class="on"' : ""}>${esc(x.tab[i])}</button>`).join(""); | |
| for (const el of $$(".exhint")) { const k = el.dataset.ex; | |
| el.innerHTML = exOpen.has(k) ? `<div class="exbox"><div class="exhead"><b>${t("ex_label")}</b><span class="segs">${segs}</span>` + | |
| `<button type="button" class="exclose" aria-label="${t("ex_close")}" title="${t("ex_close")}">×</button></div>${hint[k]}</div>` | |
| : `<button type="button" class="exopen">${t("ex_open")}</button>`; } | |
| $("#ex_all").textContent = t(exOpen.size === $$(".exhint").length ? "ex_all_close" : "ex_all_open"); | |
| } | |
| function counters() { | |
| for (const k of ["idea", "fit", "edit", "new_modding"]) { const [a, b] = lim(k), n = size($("#" + k).value), c = $(`#${k}_n`); | |
| c.textContent = n || k !== "edit" ? `${n} / ${a}–${b} ${D.unit[lang]}` : ""; c.className = "count " + (!n ? "" : n >= a && n <= b ? "good" : "bad"); } | |
| const [a, b] = lim("point"); let total = 0; | |
| for (const d of D.dims) for (const r of $$(`#${d.id}_rows .point`)) { | |
| const p = {text: $("textarea", r).value.trim(), where: whereOf(r)}, c = $(".count", r), n = size(p.text), issue = p.text ? pointIssue(p) : ""; | |
| if (p.text && !issue) total++; | |
| c.textContent = !p.text ? "" : `${n} ${D.unit[lang]}` + (issue ? ` · ${t("h_" + issue, {a, b})}` : " ✓"); c.className = "count " + (!p.text ? "" : issue ? "bad" : "good"); | |
| } | |
| const need = D.dims.reduce((s, d) => s + d.min, 0), tt = $("#pts_n"); tt.textContent = `${total} ✓`; tt.className = "pill " + (total >= need ? "good" : ""); | |
| } | |
| function render() { | |
| document.documentElement.lang = lang === "zh" ? "zh-CN" : "en"; document.title = t("title").replace(/\*/g, ""); | |
| $("#title").innerHTML = esc(t("title")).replace(/\*(.+?)\*/, "<em>$1</em>"); | |
| const home = D.links.find(([k]) => k === "l_home"); if (home) $("#brand").href = home[1]; | |
| $$("#lang button").forEach(b => { b.classList.toggle("on", b.dataset.lang === lang); b.setAttribute("aria-pressed", b.dataset.lang === lang); }); | |
| $("#links").innerHTML = D.links.filter(([k]) => k !== "l_home").map(([k, url]) => `<a href="${esc(url)}" target="_blank" rel="noopener">${t(k)}</a>`).join(""); | |
| for (const id of ["#ex_tabs", "#exf_tabs"]) $(id).innerHTML = D.examples.map((e, k) => `<button type="button" role="tab" data-i="${k}">${esc(e.tab[li()])}</button>`).join(""); | |
| renderFiles(); renderStrip(); | |
| $$("#ex_tabs button, #exf_tabs button").forEach(b => b.onclick = () => { exTab = +b.dataset.i; renderExample(); }); | |
| renderExample(); | |
| for (const el of $$("[data-t]")) el.textContent = t(el.dataset.t); | |
| for (const el of $$("[data-ph]")) el.placeholder = t(el.dataset.ph); | |
| options($("#genres"), "genres", "checkbox", "genres"); renderHours(); | |
| options($("#modding"), "modding", "radio", "modding"); options($("#category"), "category", "radio", "categories"); | |
| options($("#license"), "license", "radio", "licenses"); options($("#new_help"), "new_help", "radio", "new_help"); | |
| fillGames(); showMod(); labelRows(); $("#notes").innerHTML = D.notes[lang]; renderAuth(); counters(); | |
| if (verdictShown) showVerdict(); | |
| $("#result").innerHTML = ""; $("#result").className = ""; stale(); | |
| } | |
| const stale = () => { $("#submit").disabled = true; }; | |
| // ---------------------------------------------------------------- actions | |
| function doScreen() { | |
| const s = showVerdict(); verdictShown = true; | |
| screenState = s.ok ? {genres: genreHours(), genre_other: val("genre_other").slice(0, 200), modding: radio("modding"), profile: val("profile").slice(0, 300), games: s.games} : null; | |
| if (s.ok) fillGames(); | |
| const was = $("#form").hidden; $("#form").hidden = !s.ok; | |
| if (s.ok && (was || !radio("game"))) $("#s2").scrollIntoView({behavior: "smooth", block: "start"}); | |
| } | |
| function resync() { // the kinds or hours changed after the form was opened: the target-game list follows at once | |
| if (!screenState) return; | |
| const s = screen(genreHours(), radio("modding")); | |
| if (s.ok) { screenState = {...screenState, genres: genreHours(), modding: radio("modding"), games: s.games}; fillGames(); showVerdict(); } | |
| } | |
| async function doCheck() { | |
| const v = form(), r = await check(v), box = $("#result"); | |
| if (r.errors.length) { box.className = "bad"; box.innerHTML = `<h3>${t("problems").replace(/^#+ /, "")}</h3><ul>${r.errors.map(e => `<li>${esc(e)}</li>`).join("")}</ul>`; stale(); return null; } | |
| const ref = [files.length ? t("files_n", {n: files.length}) : "", v.link ? t("link_n") : ""].filter(Boolean).join(", "); | |
| const label = D.game_short[lang]; | |
| const counts = D.dims.map(d => `${d.label[li()]} ${r.points[d.id].length}`).join(" · "); | |
| box.className = "good"; | |
| box.innerHTML = `<h3>${t("ok").replace(/^#+ /, "")}</h3><ul><li>${t("sum_game")}: ${esc(v.game === D.new_game ? `${v.new_game.name} (${t("sum_new")})` : label[v.game])}</li><li>${t("sum_ref")}: ${ref} (${r.modality})</li>` + | |
| `<li>${t("sum_points")}: ${counts}</li><li>${t("sum_vis")}: ${t(r.visibility === "public" ? "sum_public" : "sum_private")}</li></ul>` + | |
| (r.warnings.length ? `<p>${rich(t("note"))}</p><ul>${r.warnings.map(w => `<li>${esc(w)}</li>`).join("")}</ul>` : ""); | |
| $("#submit").disabled = false; return {v, r}; | |
| } | |
| async function makeId(v, points) { | |
| const parts = [v.email, v.game, v.idea, v.link, ...D.dims.flatMap(d => points[d.id].map(p => p.text)), ...files.map(f => f.name + ":" + f.size)]; | |
| const h = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(parts.join("\0"))); | |
| const hex = [...new Uint8Array(h)].map(b => b.toString(16).padStart(2, "0")).join("").slice(0, 6); | |
| return `C-${v.game}-${new Date().toISOString().slice(0, 10).replace(/-/g, "")}-${hex}`; | |
| } | |
| // The submission service (Cloudflare Worker) in two steps, so big files go straight to Hugging Face storage: | |
| // /bench/prepare checks the form and hands back upload targets, the page uploads, /bench/commit opens the pull request. | |
| const toB64 = bytes => { let s = ""; for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); return btoa(s); }; | |
| const sha256 = async f => [...new Uint8Array(await crypto.subtle.digest("SHA-256", await f.arrayBuffer()))].map(b => b.toString(16).padStart(2, "0")).join(""); | |
| async function lfsUpload(f, up) { | |
| const h = up.header || {}; | |
| if (!h.chunk_size) { const r = await fetch(up.href, {method: "PUT", body: f}); if (!r.ok) throw new Error("upload " + r.status); return; } | |
| const size = +h.chunk_size, parts = []; // multipart: one presigned URL per part, then complete | |
| for (const key of Object.keys(h).filter(k => /^\d+$/.test(k)).sort((a, b) => +a - +b)) { | |
| const n = +key, r = await fetch(h[key], {method: "PUT", body: f.slice((n - 1) * size, n * size)}); | |
| if (!r.ok) throw new Error("upload part " + r.status); | |
| parts.push({partNumber: n, etag: r.headers.get("ETag")}); | |
| } | |
| const r = await fetch(up.href, {method: "POST", headers: {Accept: "application/vnd.git-lfs+json", "Content-Type": "application/vnd.git-lfs+json"}, | |
| body: JSON.stringify({oid: up.oid, parts})}); | |
| if (!r.ok) throw new Error("upload complete " + r.status); | |
| } | |
| async function viaService(v, box) { // the Worker checks the form again and opens the pull request | |
| const r0 = await check(v), all = [...files.map(f => ["files", f]), ...(isMaker() ? modFiles.map(f => ["mod_files", f]) : [])]; | |
| const fail = (j = {}, status = 0) => { box.className = "bad"; $("#submit").disabled = false; | |
| box.innerHTML = j.errors ? `<h3>${t("problems").replace(/^#+ /, "")}</h3><ul>${j.errors.map(e => `<li>${esc(e)}</li>`).join("")}</ul>` : rich(t(status === 429 ? "busy" : "failed")); }; | |
| const post = async (path, body) => { const r = await fetch(D.submit_url + path, {method: "POST", headers: {"Content-Type": "application/json"}, body: JSON.stringify(body)}); | |
| return [r, await r.json().catch(() => ({}))]; }; | |
| try { | |
| const metas = await Promise.all(all.map(async ([field, f]) => ({field, name: f.name, size: f.size, sha256: await sha256(f), | |
| sample: toB64(new Uint8Array(await f.slice(0, 512).arrayBuffer()))}))); | |
| const record = {...v, lang, background: screenState, track: D.game_track[v.game] || "proposed", modality: r0.modality, new_game_id: D.new_game}; | |
| const [r1, j1] = await post("/bench/prepare", {record, files: metas, website: ($("#website") || {}).value || ""}); | |
| if (!r1.ok) return fail(j1, r1.status); | |
| if (j1.honeypot) { box.className = "good"; box.innerHTML = rich(t("done", {id: j1.id, email: v.email, when: ""})); return; } | |
| const regular = []; | |
| for (const u of j1.uploads) { | |
| const f = all[u.i][1]; | |
| if (u.mode === "regular") regular.push({i: u.i, b64: toB64(new Uint8Array(await f.arrayBuffer()))}); | |
| else if (u.upload) { box.innerHTML = `<h3>${t("sending")} ${esc(f.name)}</h3>`; await lfsUpload(f, {...u.upload, oid: metas[u.i].sha256}); } | |
| } | |
| box.innerHTML = `<h3>${t("sending")}</h3>`; | |
| const [r2, j2] = await post("/bench/commit", {ticket: j1.ticket, regular}); | |
| if (!r2.ok || !j2.id) return fail(j2, r2.status); | |
| try { sessionStorage.removeItem("ga-submit-draft"); } catch (e) {} | |
| box.className = "good"; box.innerHTML = rich(t("done", {id: j2.id, email: v.email, when: D.review_days ? t("when", {d: D.review_days}) : ""})); | |
| } catch (e) { console.error(e); fail(); } | |
| } | |
| async function doSubmit() { | |
| const c = await doCheck(); if (!c) return; // the form may have changed since the check: check again | |
| const box = $("#result"), {v, r} = c; | |
| if (D.submit_url) { $("#submit").disabled = true; box.className = ""; box.innerHTML = `<h3>${t("sending")}</h3>`; return viaService(v, box); } | |
| if (!OA) { box.className = "bad"; box.innerHTML = `<h3>${t("need_signin")}</h3>`; $("#auth").scrollIntoView({behavior: "smooth", block: "center"}); return; } | |
| const user = OA.userInfo.preferred_username || "", id = await makeId(v, r.points); | |
| const stored = files.map((f, i) => `refs/${id}/${String(i + 1).padStart(2, "0")}${ext(f.name)}`); | |
| const mods = isMaker() ? modFiles : [], modStored = mods.map((f, i) => `refs/${id}/mod_${String(i + 1).padStart(2, "0")}${ext(f.name)}`); | |
| const isNew = v.game === D.new_game; | |
| const record = {submission_id: id, submitted_at: new Date().toISOString().replace(/\.\d+Z$/, "Z"), status: "pending_review", language: lang, | |
| contributor: {nickname: v.nickname, email: v.email, hf_user: user, genres: screenState.genres, genre_other: screenState.genre_other, | |
| modding: screenState.modding, profile: screenState.profile, | |
| mod: {link: v.mod_link, note: v.mod_note, files: mods.map((f, i) => ({path: modStored[i], name: f.name}))}}, | |
| target_game: v.game, track: D.game_track[v.game] || "proposed", ...(isNew ? {new_game: v.new_game} : {}), category: v.category, modality: r.modality, visibility: r.visibility, | |
| why_this_game: v.fit, idea: v.idea, points: r.points, edit_request: v.edit, | |
| reference: {files: files.map((f, i) => ({path: stored[i], name: f.name})), link: v.link, time_range: v.time_range, license: v.license, source: v.source}}; | |
| $("#submit").disabled = true; box.className = ""; box.innerHTML = `<h3>${t("sending")}</h3>`; | |
| try { | |
| await uploadFiles({repo: REPO, accessToken: OA.accessToken, isPullRequest: true, | |
| commitTitle: `submission ${id} (${v.game}, ${r.modality}) by ${v.nickname}`, | |
| files: [{path: `submissions/${id}.json`, content: new Blob([JSON.stringify(record, null, 1)])}, ...files.map((f, i) => ({path: stored[i], content: f})), ...mods.map((f, i) => ({path: modStored[i], content: f}))]}); | |
| } catch (err) { | |
| console.error(err); | |
| const denied = /401|403|404|not found|forbidden|unauthor/i.test(String(err.message || err)); | |
| box.className = "bad"; box.innerHTML = denied ? `<h3>${t("no_access")}</h3>` : rich(t("failed")); $("#submit").disabled = false; return; | |
| } | |
| try { sessionStorage.removeItem("ga-submit-draft"); } catch (e) {} | |
| box.className = "good"; box.innerHTML = rich(t("done", {id, email: v.email, when: D.review_days ? t("when", {d: D.review_days}) : ""})); | |
| } | |
| // ---------------------------------------------------------------- draft kept across the sign-in redirect (files cannot be kept) | |
| const TEXT_FIELDS = ["mod_link", "mod_note", "new_name", "new_link", "new_modding", "genre_other", "profile", "link", "time_range", "source", "fit", "idea", "edit", "nickname", "email"]; | |
| function saveDraft() { | |
| const d = {lang, genres: genreHours(), modding: radio("modding"), shown: !$("#form").hidden, game: radio("game"), points: draftPoints(), | |
| category: radio("category"), license: radio("license"), new_help: radio("new_help"), ack: $("#ack").checked, consent: $("#consent").checked}; | |
| for (const k of TEXT_FIELDS) d[k] = $("#" + k).value; | |
| try { sessionStorage.setItem("ga-submit-draft", JSON.stringify(d)); } catch (e) {} | |
| } | |
| function loadDraft() { | |
| let d; try { d = JSON.parse(sessionStorage.getItem("ga-submit-draft") || "null"); } catch (e) {} | |
| if (!d) return; | |
| lang = d.lang || lang; render(); | |
| for (const g of Object.keys(d.genres || {})) { const x = $(`input[name=genres][value=${g}]`); if (x) x.checked = true; } | |
| renderHours(d.genres || {}); | |
| for (const k of ["modding", "category", "license", "new_help"]) { const x = d[k] && $(`input[name=${k}][value=${d[k]}]`); if (x) x.checked = true; } | |
| for (const k of TEXT_FIELDS) $("#" + k).value = d[k] || ""; | |
| setPoints(d.points); $("#ack").checked = !!d.ack; $("#consent").checked = !!d.consent; counters(); | |
| showMod(); if (d.shown) { doScreen(); fillGames(d.game); } | |
| } | |
| async function auth() { | |
| try { OA = await oauthHandleRedirectIfPresent(); } catch (e) { console.error(e); } | |
| if (OA) { try { sessionStorage.setItem("ga-oauth", JSON.stringify(OA)); } catch (e) {} } | |
| else { try { const x = JSON.parse(sessionStorage.getItem("ga-oauth") || "null"); if (x && new Date(x.accessTokenExpiresAt) > new Date()) OA = x; } catch (e) {} } | |
| } | |
| async function main() { | |
| D = await (await fetch("data.json")).json(); | |
| if (!D.submit_url) await auth(); | |
| setPoints(); render(); loadDraft(); | |
| $$("#lang button").forEach(b => b.onclick = () => { lang = b.dataset.lang; render(); }); | |
| $("#continue").onclick = doScreen; $("#check").onclick = doCheck; $("#submit").onclick = doSubmit; | |
| $("#genres").addEventListener("change", () => { renderHours(); resync(); }); | |
| $("#hours").addEventListener("change", resync); $("#modding").addEventListener("change", () => { showMod(); resync(); }); | |
| $("#game").addEventListener("change", showNew); | |
| $("#mod_file").onchange = e => { for (const f of e.target.files) if (!modFiles.some(x => x.name === f.name && x.size === f.size)) modFiles.push(f); e.target.value = ""; renderModFiles(); stale(); }; | |
| for (const d of D.dims) $(`#${d.id}_add`).onclick = () => { const row = pointRow(d); $(`#${d.id}_rows`).appendChild(row); labelRows(); $("textarea", row).focus(); stale(); }; | |
| const add = async list => { // files are checked as they arrive, so a wrong one never sits in the list | |
| const M = D.max, bad = []; | |
| for (const f of list) { const k = kind(f.name); | |
| if (files.some(x => x.name === f.name && x.size === f.size)) continue; | |
| if (!k) { bad.push(msg("file_type", {x: f.name})); continue; } | |
| if (f.size > M[k]) { bad.push(msg("file_big", {x: f.name, s: f.size / 1e6, c: M[k] / 1e6})); continue; } | |
| if (files.length >= M.files) { bad.push(msg("max_files", {m: M.files, n: files.length + 1})); break; } | |
| if (k === "text") { const text = await f.text(), n = size(text), m = Math.floor(D.limits.text_units * D.scale[lang]); f._paras = splitParas(text); | |
| if (n < m) bad.push(msg("short_text", {x: f.name, n, m})); } // kept, but said at once: it will not pass the check | |
| else f._url = URL.createObjectURL(f); | |
| files.push(f); } | |
| $("#file_msg").innerHTML = bad.map(esc).join("<br>"); refreshRefs(); stale(); }; | |
| $("#link").addEventListener("input", () => $$(".point").forEach(renderPicks)); | |
| $("#form").addEventListener("click", e => { // the example boxes under the fields | |
| const h = e.target.closest(".exhint"); if (!h) return; const k = h.dataset.ex, seg = e.target.closest(".segs button"); | |
| if (e.target.closest(".exopen")) exOpen.add(k); else if (e.target.closest(".exclose")) exOpen.delete(k); else if (seg) exTab = +seg.dataset.i; else return; | |
| exAuto.add(k); renderExample(); }); | |
| $("#form").addEventListener("focusin", e => { if (e.target.closest(".exhint")) return; | |
| for (const [k, sel] of Object.entries(ZONE)) if (e.target.closest(sel) && !exAuto.has(k)) { exAuto.add(k); exOpen.add(k); renderHints(); } }); | |
| $("#ex_all").onclick = () => { const all = $$(".exhint").map(x => x.dataset.ex); exOpen = exOpen.size === all.length ? new Set() : new Set(all); all.forEach(k => exAuto.add(k)); renderHints(); }; | |
| const peek = document.createElement("img"); peek.id = "peek"; peek.alt = ""; peek.hidden = true; document.body.appendChild(peek); // a larger look at an image tile | |
| $("#form").addEventListener("mouseover", e => { const b = e.target.closest(".imgtile"); if (!b) { peek.hidden = true; return; } | |
| const r = b.getBoundingClientRect(); peek.src = $("img", b).src; peek.style.left = Math.max(8, Math.min(r.left, innerWidth - 350)) + "px"; peek.style.top = (r.top - 8) + "px"; peek.hidden = false; }); | |
| $("#form").addEventListener("mouseleave", () => { peek.hidden = true; }); | |
| $("#file").onchange = e => { add([...e.target.files]); e.target.value = ""; }; // a copy: the list empties when the input is cleared | |
| const drop = $("#drop"); | |
| drop.ondragover = e => { e.preventDefault(); drop.classList.add("over"); }; drop.ondragleave = () => drop.classList.remove("over"); | |
| drop.ondrop = e => { e.preventDefault(); drop.classList.remove("over"); add([...e.dataTransfer.files]); }; | |
| $("#form").addEventListener("input", () => { stale(); counters(); }); | |
| $("#form").addEventListener("change", stale); | |
| const nav = $$("#steps a"), secs = nav.map(a => $(a.getAttribute("href"))); // highlight the section being read | |
| const io = new IntersectionObserver(es => es.forEach(e => { if (e.isIntersecting) nav.forEach(a => a.classList.toggle("on", a.getAttribute("href") === "#" + e.target.id)); }), | |
| {rootMargin: "-30% 0px -60% 0px"}); | |
| secs.forEach(x => x && io.observe(x)); | |
| } | |
| main(); | |