// ==UserScript== // @name NYT Crossword List View // @namespace nyt-crossword-list-view // @version 0.14 // @description Adds an optional list view to the NYT crossword web player, like the iOS app: every clue, Across and Down, as a row with its answer squares laid out horizontally. // @author Matt Ball // @match https://www.nytimes.com/crosswords/game/* // @run-at document-idle // @grant none // @updateURL https://raw.githubusercontent.com/mjball/tampermonkey-scripts/main/scripts/nyt-crossword-list-view.user.js // @downloadURL https://raw.githubusercontent.com/mjball/tampermonkey-scripts/main/scripts/nyt-crossword-list-view.user.js // ==/UserScript== // NYT Crossword List View // // The NYT iOS app can show the crossword as a list: each clue is a row with its // answer squares in a horizontal line, so Down answers read left to right too. // The web player has no such view, so this script adds one. // // The list view is a mirror of the real game, not a second copy of it. The real // board stays on the page (moved off-screen) and keeps keyboard focus, so // typing, Backspace, Tab, pencil mode, rebus, check/reveal, the timer and your // saved progress all work exactly as they do normally. The list just shows the // board's state and turns clicks and arrow keys into selections on the board. (() => { 'use strict'; // On old test puzzles the dev loader (scripts/dev/) runs the newest dev // build instead; the installed copy steps aside so the two don't both run. const isDevCopy = !!(document.currentScript && document.currentScript.dataset.xwdlvDev); if (document.documentElement.hasAttribute('data-xwdlv-dev') && !isDevCopy) return; let badge = null; if (isDevCopy) { badge = document.createElement('div'); badge.textContent = `list view dev ${document.documentElement.getAttribute('data-xwdlv-dev')}`; badge.style.cssText = 'position:fixed;left:8px;bottom:8px;z-index:99999;max-width:60vw;padding:2px 6px;background:#ffe08a;color:#000;font:12px/1.35 monospace;white-space:pre-wrap;pointer-events:none'; badge.id = 'xwdlv-dev-badge'; document.body.appendChild(badge); } const STORAGE_KEY = 'nyt-crossword-list-view:on'; const ON_CLASS = 'xwdlv-on'; let enabled = localStorage.getItem(STORAGE_KEY) === '1'; let panel = null; let toggle = null; let model = null; // { signature, cols, cells: Map(idx -> g), clues: [...] } let lastSelectedKey = null; let renderQueued = false; // --------------------------------------------------------------------------- // Reading the real board const cellG = (idx) => document.getElementById(`cell-id-${idx}`); const cellIndex = (g) => Number(g.id.replace('cell-id-', '')); const isPlayable = (g) => g.getAttribute('role') === 'gridcell'; const rectOf = (g) => g.querySelector('rect'); // The cell's own children: the clue number (if any) and the letter. // NYT puts the letter in a middle-anchored and mirrors it into a // hidden child . function readCell(g) { let label = ''; let guess = ''; for (const el of g.children) { if (el.tagName.toLowerCase() !== 'text') continue; if (el.getAttribute('text-anchor') === 'middle') { const hidden = el.querySelector('.xwd__cell--hidden'); guess = (hidden ? hidden.textContent : el.textContent) || ''; } else { label = el.textContent.trim(); } } const rect = rectOf(g); const cls = rect ? rect.classList : { contains: () => false }; const badge = g.querySelector('use'); const badgeRef = badge ? (badge.getAttribute('href') || badge.getAttribute('xlink:href') || '') : ''; return { label, guess: guess.trim(), selected: cls.contains('xwd__cell--selected'), penciled: cls.contains('xwd__cell--penciled'), shaded: cls.contains('xwd__cell--shaded'), confirmed: cls.contains('xwd__assistance--confirmed'), circled: !!g.querySelector('circle'), badge: badgeRef.replace(/^#/, ''), // "revealed", "checked" or "modified" }; } function columnCount(gs) { for (const g of gs) { const r = Number(g.getAttribute('aria-rowindex')); const c = Number(g.getAttribute('aria-colindex')); if (r > 1 && c >= 1) return (cellIndex(g) - (c - 1)) / (r - 1); } return Math.max(0, ...gs.map((g) => Number(g.getAttribute('aria-colindex')) || 0)); } function readClueLists() { const lists = []; for (const wrapper of document.querySelectorAll('.xwd__clue-list--wrapper')) { const title = (wrapper.querySelector('.xwd__clue-list--title')?.textContent || '').trim(); const dir = /^d/i.test(title) ? 'down' : /^a/i.test(title) ? 'across' : null; if (!dir) continue; const items = [...wrapper.querySelectorAll('li.xwd__clue--li')].map((li) => ({ li, dir, label: (li.querySelector('.xwd__clue--label')?.textContent || '').trim(), html: li.querySelector('.xwd__clue--text')?.innerHTML || '', })); lists.push({ dir, title, items }); } // Across first, then Down, whatever order the page uses. return lists.sort((a, b) => (a.dir === b.dir ? 0 : a.dir === 'across' ? -1 : 1)); } function buildModel() { const gs = [...document.querySelectorAll('g.xwd__cell[id^="cell-id-"]')]; const lists = readClueLists(); if (!gs.length || !lists.length) return null; const cols = columnCount(gs); const cells = new Map(gs.map((g) => [cellIndex(g), g])); const byLabel = new Map(); for (const [idx, g] of cells) { if (!isPlayable(g)) continue; const { label } = readCell(g); if (label) byLabel.set(label, idx); } const clues = []; for (const list of lists) { for (const item of list.items) { const start = byLabel.get(item.label); if (start === undefined) continue; const step = item.dir === 'across' ? 1 : cols; const run = []; for (let i = start; cells.has(i) && isPlayable(cells.get(i)); i += step) { run.push(i); if (item.dir === 'across' && (i + 1) % cols === 0) break; } clues.push({ ...item, key: `${item.dir}:${item.label}`, cells: run }); } } const signature = `${cols}|${gs.length}|${clues.map((c) => `${c.key}=${c.cells.join(',')}`).join(';')}`; return { signature, cols, cells, clues, lists }; } function selectedClueKey() { for (const wrapper of document.querySelectorAll('.xwd__clue-list--wrapper')) { const li = wrapper.querySelector('li.xwd__clue--selected'); if (!li) continue; const title = wrapper.querySelector('.xwd__clue-list--title')?.textContent || ''; const dir = /^d/i.test(title.trim()) ? 'down' : 'across'; return `${dir}:${(li.querySelector('.xwd__clue--label')?.textContent || '').trim()}`; } return null; } function relatedClueKeys() { const keys = new Set(); for (const wrapper of document.querySelectorAll('.xwd__clue-list--wrapper')) { const title = wrapper.querySelector('.xwd__clue-list--title')?.textContent || ''; const dir = /^d/i.test(title.trim()) ? 'down' : 'across'; for (const li of wrapper.querySelectorAll('li.xwd__clue--highlighted, li.xwd__clue--related')) { keys.add(`${dir}:${(li.querySelector('.xwd__clue--label')?.textContent || '').trim()}`); } } return keys; } function selectedCellIndex() { const rect = document.querySelector('rect.xwd__cell--selected'); const g = rect && rect.closest('g.xwd__cell'); return g ? cellIndex(g) : null; } // --------------------------------------------------------------------------- // Driving the real board const nextFrame = () => new Promise((r) => requestAnimationFrame(() => r())); function clickEl(el) { el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window, button: 0 })); } function focusBoard() { const idx = selectedCellIndex(); const g = idx === null ? null : cellG(idx); if (g && document.activeElement !== g) g.focus({ preventScroll: true }); } // Select one square of one clue. Clicking a square on the board selects it in // the current direction; clicking the selected square flips the direction. async function selectCell(idx, clueKey) { const g = cellG(idx); if (!g) return; if (selectedCellIndex() !== idx) { clickEl(g); await nextFrame(); } if (selectedClueKey() !== clueKey) { clickEl(g); await nextFrame(); } focusBoard(); } // Select a whole clue the way clicking it in the real clue list does. async function selectClue(clue) { clickEl(clue.li); await nextFrame(); focusBoard(); } // --------------------------------------------------------------------------- // The list view const CSS = ` .${ON_CLASS} .xwd__layout_clueBarAndBoard, .${ON_CLASS} .xwd__layout--cluelists { position: fixed !important; left: -10000px !important; top: 0 !important; } #xwdlv-panel { display: none; box-sizing: border-box; width: 100%; max-width: 900px; margin: 0 auto; padding: 0 12px 30vh; font-family: nyt-franklin, helvetica, arial, sans-serif; -webkit-user-select: none; user-select: none; } .${ON_CLASS} #xwdlv-panel { display: block; } #xwdlv-panel h3 { position: sticky; top: var(--xwdlv-sticky-top, 0px); z-index: 1; margin: 0; padding: 10px 0 6px; background: #fff; font-size: 13px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; border-bottom: 1px solid #ccc; } .xwdlv-row { display: flex; flex-direction: column; gap: 6px; padding: 10px 8px; border-bottom: 1px solid #eee; border-left: 6px solid transparent; cursor: pointer; } .xwdlv-row.xwdlv-related { background: #f4f4f4; } .xwdlv-row.xwdlv-selected { background: #dcefff; border-left-color: #4f85e5; } .xwdlv-row.xwdlv-filled .xwdlv-clue { color: #959595; } .xwdlv-clue { display: flex; gap: 8px; font-size: 16px; line-height: 1.3; } .xwdlv-num { font-weight: 700; min-width: 2.2em; text-align: right; } .xwdlv-cells { display: flex; flex-wrap: wrap; gap: 0; padding-left: calc(2.2em + 8px); } .xwdlv-cell { position: relative; box-sizing: border-box; width: 34px; height: 34px; margin: 0 -1px 0 0; border: 1px solid #555; background: #fff; display: flex; align-items: center; justify-content: center; font-size: 22px; font-weight: 400; text-transform: uppercase; } .xwdlv-cell.xwdlv-shaded { background: #dcdcdc; } .xwdlv-selected .xwdlv-cell { background: #a7d8ff; } .xwdlv-cell.xwdlv-cur { background: #ffda00 !important; } .xwdlv-cell.xwdlv-pencil { color: #959595; } .xwdlv-cell.xwdlv-rebus { display: block; overflow: hidden; white-space: nowrap; text-overflow: clip; text-align: center; line-height: 32px; letter-spacing: -0.03em; font-size: 15px; } .xwdlv-cell.xwdlv-rebus[data-len="3"] { font-size: 12px; } .xwdlv-cell.xwdlv-rebus[data-len="4"] { font-size: 11px; } .xwdlv-cell.xwdlv-rebus[data-len="5"] { font-size: 10px; } /* Like the iOS app: the text shrinks down to 9px, then the square widens to fit (never wider than the row). */ .xwdlv-cell.xwdlv-rebus[data-len="long"] { width: auto; min-width: 34px; max-width: 100%; padding: 0 2px; font-size: 9px; letter-spacing: 0; text-overflow: ellipsis; } /* NYT's rebus box opens over the hidden grid; show what you're typing in the list instead, in a box that grows to fit. */ .xwdlv-cell.xwdlv-rebus-edit { width: auto !important; min-width: 34px; max-width: 100%; padding: 0 6px; overflow: hidden; white-space: nowrap; /* If it's wider than the row, keep the end (where you're typing) in view. */ display: block; direction: rtl; font-size: 18px !important; line-height: 32px; background: #fff !important; outline: 2px solid #000; outline-offset: -1px; z-index: 2; } .xwdlv-cell.xwdlv-circled::before { content: ''; position: absolute; inset: 1px; border: 1px solid #777; border-radius: 50%; pointer-events: none; } .xwdlv-cell.xwdlv-confirmed { color: #2860d8; } .xwdlv-cell.xwdlv-revealed::after, .xwdlv-cell.xwdlv-checked::after { content: ''; position: absolute; top: 0; right: 0; border-style: solid; border-width: 0 8px 8px 0; border-color: transparent #e63333 transparent transparent; } .xwdlv-cell.xwdlv-checked::after { border: none; width: 140%; height: 1px; top: 50%; left: -20%; background: #e63333; transform: rotate(-45deg); } #xwdlv-toggle.xwdlv-floating { position: fixed; right: 16px; bottom: 16px; z-index: 1000; padding: 8px 14px; border: 1px solid #000; border-radius: 20px; background: #fff; color: #000; font: 600 14px nyt-franklin, helvetica, arial, sans-serif; cursor: pointer; box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2); } .${ON_CLASS} #xwdlv-toggle.xwdlv-floating { background: #000; color: #fff; } #xwdlv-toggle-item { display: flex; align-items: center; } `; function addStyles() { const style = document.createElement('style'); style.textContent = CSS; document.head.appendChild(style); } // The toggle goes in NYT's toolbar next to Rebus / Clear / Reveal / Check, // copying the classes of NYT's own buttons so it looks like one of them. If // the toolbar can't be found it floats in the bottom right corner instead. let toggleItem = null; function ensureToggle() { if (!toggle) { toggle = document.createElement('button'); toggle.id = 'xwdlv-toggle'; toggle.type = 'button'; toggle.addEventListener('mousedown', (e) => e.preventDefault()); // keep focus on the board toggle.addEventListener('click', () => setEnabled(!enabled)); updateToggle(); } placeToggle(); } const stateClass = /--(open|active|selected|disabled|expanded)\b/; const cleanClasses = (el) => [...el.classList].filter((c) => !stateClass.test(c)).join(' '); function placeToggle() { const tools = document.querySelector('.xwd__toolbar--tools'); const ref = tools && [...tools.querySelectorAll('button')].find((b) => /^(rebus|clear|reveal|check)$/i.test(b.textContent.trim())); if (!ref) { if (!toggle.isConnected) { toggle.className = 'xwdlv-floating'; document.body.appendChild(toggle); } return; } if (toggle.isConnected && tools.contains(toggle)) return; // The toolbar entry that holds the reference button (e.g. its
  • ). let item = ref; while (item.parentElement && item.parentElement !== tools) item = item.parentElement; toggle.className = cleanClasses(ref); if (item === ref) { tools.insertBefore(toggle, item); } else { if (!toggleItem) { toggleItem = document.createElement(item.tagName); toggleItem.id = 'xwdlv-toggle-item'; } toggleItem.className = cleanClasses(item); toggleItem.appendChild(toggle); tools.insertBefore(toggleItem, item); } } function updateToggle() { if (!toggle) return; toggle.textContent = enabled ? 'Grid' : 'List'; toggle.title = enabled ? 'Back to the grid' : 'Show the clues as a list'; toggle.setAttribute('aria-pressed', String(enabled)); } function setEnabled(on) { enabled = on; localStorage.setItem(STORAGE_KEY, on ? '1' : '0'); document.documentElement.classList.toggle(ON_CLASS, on); updateToggle(); lastSelectedKey = null; if (!on) unclampAncestors(false); scheduleRender(); if (on) fitToScreen(); focusBoard(); } // Some of NYT's page containers have a fixed height and their own scrollbar, // which turned the list into a small scrolling box inside the page. While the // list is showing, let any such container grow to fit so only the page // scrolls. The containers' own styles come back when you switch to the grid. const unclamped = new Map(); // element -> its original style attribute // The whole game sits inside NYT's ".xwd-moment-container", next to the // pause screen, and the pause screen stretches to the container's height. // With the game now as tall as the list, the pause screen got that tall too. // While it's showing in list view, make just the pause screen (never the // game or toolbar) one window tall and keep it in view below NYT's header. function headerBottom() { let bottom = 0; for (const el of document.querySelectorAll('.pz-nav, header, [class*="pz-nav"]')) { const pos = getComputedStyle(el).position; if (pos !== 'sticky' && pos !== 'fixed') continue; const r = el.getBoundingClientRect(); if (r.top <= 0 && r.bottom > bottom && r.bottom < window.innerHeight / 3) bottom = r.bottom; } return Math.round(bottom); } // NYT stacks its "moments" (game, start screen, pause screen, ...) in one // grid cell, so every moment is as tall as the tallest one. In list view // the game is several screens tall, which stretched the pause card to // match. Keep every non-game moment one window tall and stuck just below // NYT's header so the pause card stays normal-sized and on screen. const pinned = new Map(); // el -> original style attribute function overlayMoments() { const container = document.querySelector('.xwd-moment-container'); const game = document.querySelector('.xwd__board'); if (!container || !game) return []; return [...container.children].filter((c) => !c.contains(game) && !c.querySelector('#xwdlv-panel')); } function pinOverlayMoments(on) { const want = new Set(on ? overlayMoments() : []); for (const [el, style] of pinned) { if (want.has(el) && el.isConnected) continue; if (style === null) el.removeAttribute('style'); else el.setAttribute('style', style); pinned.delete(el); } const top = headerBottom(); for (const el of want) { if (!pinned.has(el)) pinned.set(el, el.getAttribute('style')); const set = (k, v) => el.style.setProperty(k, v, 'important'); set('position', 'sticky'); set('top', `${top}px`); set('align-self', 'start'); set('height', `calc(100vh - ${top}px)`); set('max-height', `calc(100vh - ${top}px)`); set('min-height', '0'); set('overflow', 'auto'); } } // NYT's modals (pause, "Ready to start", congrats) live in // #portal-game-modals inside .pz-game-screen: an absolutely positioned // .xwd__modal--wrapper covering the whole game screen, whose // .xwd__modal--body stretches to fill it. In list view the game screen is // thousands of pixels tall, so the modal was too. Pin the wrapper to the // visible window and give the body a grid-sized height. const modalStyled = new Map(); // el -> original style attribute function continueButton(root) { for (const el of root.querySelectorAll('button, a, [role="button"]')) { if (!/^(continue|resume)\b/i.test(el.textContent.trim())) continue; const r = el.getBoundingClientRect(); if (r.width && r.height) return el; } return null; } function styleModal(el, props) { if (!modalStyled.has(el)) modalStyled.set(el, el.getAttribute('style')); for (const [k, v] of Object.entries(props)) { if (el.style.getPropertyValue(k) !== v || el.style.getPropertyPriority(k) !== 'important') el.style.setProperty(k, v, 'important'); } } function sizeModals(on) { const wrappers = on ? [...document.querySelectorAll('.xwd__modal--wrapper')] : []; const keep = new Set(); const top = coveredTop(); const avail = window.innerHeight - top; const h = Math.max(240, Math.min(660, avail - 32)); for (const w of wrappers) { styleModal(w, { position: 'fixed', top: `${top}px`, left: '0', right: '0', bottom: '0', height: 'auto', 'max-height': 'none', 'z-index': '20' }); keep.add(w); const body = w.querySelector('.xwd__modal--body'); if (body) { styleModal(body, { height: `${h}px`, 'max-height': `${h}px`, 'min-height': '0', 'align-self': 'center', 'margin-top': 'auto', 'margin-bottom': 'auto', overflow: 'auto' }); keep.add(body); } const content = w.querySelector('.xwd__modal--content'); if (content) { styleModal(content, { 'max-height': '100%', 'min-height': '0' }); keep.add(content); } } for (const [el, style] of modalStyled) { if (keep.has(el) && el.isConnected) continue; if (style === null) el.removeAttribute('style'); else el.setAttribute('style', style); modalStyled.delete(el); } } function unclampAncestors(on) { pinOverlayMoments(on); sizeModals(on); if (!on) { for (const [el, style] of unclamped) { if (style === null) el.removeAttribute('style'); else el.setAttribute('style', style); } unclamped.clear(); return; } if (!panel) return; for (let el = panel.parentElement; el && el !== document.body && el !== document.documentElement; el = el.parentElement) { if (unclamped.has(el)) continue; const cs = getComputedStyle(el); const clips = cs.overflowY !== 'visible' || cs.maxHeight !== 'none'; if (!clips || el.scrollHeight <= el.clientHeight + 1) continue; unclamped.set(el, el.getAttribute('style')); el.style.setProperty('overflow-y', 'visible', 'important'); el.style.setProperty('height', 'auto', 'important'); el.style.setProperty('max-height', 'none', 'important'); } for (const el of [document.documentElement, document.body]) { if (unclamped.has(el) || getComputedStyle(el).overflowY !== 'hidden') continue; unclamped.set(el, el.getAttribute('style')); el.style.setProperty('overflow-y', 'auto', 'important'); } } // NYT puts an ad and the puzzle title above the game. When the list opens, // scroll the page so the toolbar (timer, Check, Reveal) is at the top. function gameToolbar() { // NYT has more than one toolbar wrapper; use the one that's actually on screen. return [...document.querySelectorAll('.pz-game-toolbar, .xwd__toolbar--wrapper')].find((el) => el.getBoundingClientRect().height > 0) || null; } function fitToScreen() { const toolbar = gameToolbar(); if (toolbar) window.scrollTo({ top: toolbar.getBoundingClientRect().top + window.scrollY - headerBottom(), behavior: 'smooth' }); } // How much of the top of the window is covered by things that stay put while // the page scrolls (NYT's toolbar, if it sticks), so the Across/Down headings // stick just below it and the current clue isn't scrolled underneath it. function coveredTop() { let top = headerBottom(); const toolbar = gameToolbar(); if (toolbar) { const pos = getComputedStyle(toolbar).position; if (pos === 'sticky' || pos === 'fixed') top = Math.max(top, Math.round(toolbar.getBoundingClientRect().bottom)); } return top; } function ensurePanel() { if (panel && panel.isConnected) return true; if (!document.querySelector('g.xwd__cell')) return false; const anchor = document.querySelector('.xwd__layout_clueBarAndBoard') || document.querySelector('.xwd__board')?.closest('[class*="xwd__layout"]') || document.querySelector('.xwd__board'); if (!anchor) return false; panel = document.createElement('div'); panel.id = 'xwdlv-panel'; panel.addEventListener('mousedown', (e) => e.preventDefault()); // keep focus on the board panel.addEventListener('click', onPanelClick); anchor.parentNode.insertBefore(panel, anchor); model = null; return true; } function buildPanel() { panel.textContent = ''; for (const list of model.lists) { const h = document.createElement('h3'); h.textContent = list.title; panel.appendChild(h); for (const clue of model.clues.filter((c) => c.dir === list.dir)) { const row = document.createElement('div'); row.className = 'xwdlv-row'; row.dataset.key = clue.key; const text = document.createElement('div'); text.className = 'xwdlv-clue'; const num = document.createElement('span'); num.className = 'xwdlv-num'; num.textContent = clue.label; const body = document.createElement('span'); body.className = 'xwdlv-text'; body.innerHTML = clue.html; // NYT's own clue markup (italics etc.) text.append(num, body); const cells = document.createElement('div'); cells.className = 'xwdlv-cells'; for (const idx of clue.cells) { const cell = document.createElement('div'); cell.className = 'xwdlv-cell'; cell.dataset.idx = idx; cells.appendChild(cell); } row.append(text, cells); clue.row = row; panel.appendChild(row); } } } // NYT's Rebus entry is a text box (input#rebus-input) that it opens over // the selected square of the (hidden) grid. While it's open, show what's // being typed in the list instead. function rebusInput() { const el = document.querySelector('input.xwd__rebus--input, #rebus-input'); if (el) return el; // Fallback if NYT renames it: a focused text field inside the game. const a = document.activeElement; if (a && a.matches('input[type="text"], input:not([type]), textarea') && a.closest('[class*="xwd__layout"]') && !a.closest('#xwdlv-panel')) return a; return null; } function currentRebusText() { const el = rebusInput(); return el ? el.value || '' : null; } function rebusButton() { const tools = document.querySelector('.xwd__toolbar--tools') || document; return [...tools.querySelectorAll('button')].find((b) => /^rebus$/i.test(b.textContent.trim())) || null; } // Enter the rebus being typed into the square it was opened on, the way // pressing Return does. Needed before moving elsewhere from the list: NYT // otherwise keeps the box open and later drops the entry into whatever // square is selected by then. async function commitRebus() { const el = rebusInput(); if (!el) return; el.focus({ preventScroll: true }); const ev = new KeyboardEvent('keydown', { key: 'Enter', code: 'Enter', bubbles: true, cancelable: true }); for (const k of ['keyCode', 'which']) Object.defineProperty(ev, k, { get: () => 13 }); el.dispatchEvent(ev); await nextFrame(); if (rebusInput()) { const btn = rebusButton(); if (btn) clickEl(btn); await nextFrame(); } } let rebusText = null; let rebusIdx = null; // the square the open rebus box belongs to function updatePanel() { rebusText = currentRebusText(); if (rebusText === null) rebusIdx = null; else if (rebusIdx === null) rebusIdx = selectedCellIndex(); const selKey = selectedClueKey(); const related = relatedClueKeys(); const curIdx = selectedCellIndex(); const state = new Map(); for (const [idx, g] of model.cells) if (isPlayable(g)) state.set(idx, readCell(g)); for (const clue of model.clues) { const row = clue.row; row.classList.toggle('xwdlv-selected', clue.key === selKey); row.classList.toggle('xwdlv-related', clue.key !== selKey && related.has(clue.key)); let filled = true; row.querySelectorAll('.xwdlv-cell').forEach((el, i) => { const idx = clue.cells[i]; const s = state.get(idx); if (!s) return; if (!s.guess) filled = false; const isCur = clue.key === selKey && idx === curIdx; const editing = rebusText !== null && idx === rebusIdx && clue.key === selKey; const text = editing ? rebusText : s.guess; if (el.textContent !== text) el.textContent = text; el.classList.toggle('xwdlv-cur', isCur); el.classList.toggle('xwdlv-rebus-edit', editing); el.classList.toggle('xwdlv-pencil', s.penciled); const rebus = !editing && s.guess.length > 1; el.classList.toggle('xwdlv-rebus', rebus); const n = s.guess.length; const len = n > 5 ? 'long' : String(n); if (el.dataset.len !== len) el.dataset.len = len; el.classList.toggle('xwdlv-circled', s.circled); el.classList.toggle('xwdlv-shaded', s.shaded); el.classList.toggle('xwdlv-confirmed', s.confirmed); el.classList.toggle('xwdlv-revealed', s.badge === 'revealed'); el.classList.toggle('xwdlv-checked', s.badge === 'checked'); }); row.classList.toggle('xwdlv-filled', filled); } if (selKey && selKey !== lastSelectedKey) { lastSelectedKey = selKey; const clue = model.clues.find((c) => c.key === selKey); if (clue) scrollRowIntoView(clue.row); } } function scrollRowIntoView(row) { const top = coveredTop(); document.documentElement.style.setProperty('--xwdlv-sticky-top', `${top}px`); const heading = panel.querySelector('h3'); const visibleTop = top + (heading ? heading.getBoundingClientRect().height : 0); const r = row.getBoundingClientRect(); if (r.top < visibleTop || r.bottom > window.innerHeight) { const target = window.scrollY + r.top - visibleTop - (window.innerHeight - visibleTop) / 3; window.scrollTo({ top: Math.max(0, target), behavior: 'smooth' }); } } function render() { renderQueued = false; if (!ensurePanel()) return; ensureToggle(); if (!enabled) return; const next = buildModel(); if (!next) return; if (!model || model.signature !== next.signature) { const first = !model; model = next; buildPanel(); if (first) fitToScreen(); } else { // Clue
  • s and cells can be re-created by React; keep fresh references. model.cells = next.cells; next.clues.forEach((c, i) => (model.clues[i].li = c.li)); } updatePanel(); unclampAncestors(true); if (badge) showDebug(); } // Dev builds only: describe NYT's moments (game/pause/...) in the corner badge. function showDebug() { const head = `list view dev ${document.documentElement.getAttribute('data-xwdlv-dev')}`; const lines = [head, `vh=${window.innerHeight} scrollY=${Math.round(window.scrollY)} pinned=${pinned.size}`]; const mc = document.querySelector('.xwd-moment-container'); if (mc) { for (const c of mc.children) { const cs = getComputedStyle(c); const r = c.getBoundingClientRect(); lines.push(` moment ${[...c.classList].join('.').slice(0, 40)} ${cs.position} ${cs.display} vis=${cs.visibility} op=${cs.opacity} top=${Math.round(r.top)} rh=${Math.round(r.height)} txt=${c.textContent.trim().slice(0, 30)}`); } } const desc = (el) => el ? `${el.tagName.toLowerCase()}#${el.id}.${[...el.classList].join('.').slice(0, 50)}${el.value !== undefined ? ` val=${JSON.stringify(el.value)}` : ''}` : 'none'; lines.push(` active=${desc(document.activeElement)} rebus=${JSON.stringify(rebusText)} sel=${selectedClueKey()}@${selectedCellIndex()}`); for (const el of [...document.querySelectorAll('[class*="rebus" i]:not(.xwdlv-cell), input, textarea')].slice(0, 6)) lines.push(` r: ${desc(el)} in=${el.parentElement ? desc(el.parentElement) : ''}`); lines.push(` keys: ${keyLog.join(' ')}`); const btn = continueButton(document.body); if (btn) { lines.push(` modalStyled=${modalStyled.size}`); let n = 0; for (let el = btn; el && el !== document.body && n < 6; el = el.parentElement, n++) { const cs = getComputedStyle(el); const r = el.getBoundingClientRect(); lines.push(` ${el.tagName.toLowerCase()}.${[...el.classList].join('.').slice(0, 40)} ${cs.position} ${cs.display} top=${Math.round(r.top)} rh=${Math.round(r.height)} w=${Math.round(r.width)}`); } } const text = lines.join('\n'); if (badge.textContent !== text) badge.textContent = text; } function scheduleRender() { if (renderQueued) return; renderQueued = true; requestAnimationFrame(render); } // --------------------------------------------------------------------------- // Input function onPanelClick(e) { if (!model) return; const row = e.target.closest('.xwdlv-row'); if (!row) return; const clue = model.clues.find((c) => c.key === row.dataset.key); if (!clue) return; const cell = e.target.closest('.xwdlv-cell'); (async () => { await commitRebus(); if (cell) await selectCell(Number(cell.dataset.idx), clue.key); else await selectClue(clue); })(); } // In the list, Left/Right move within the current answer and Up/Down move to // the previous/next clue. Everything else goes to the game untouched. const keyLog = []; function onKeyDown(e) { if (badge) { const t = e.target; keyLog.push(`${e.key}>${t && t.tagName ? t.tagName.toLowerCase() + (t.id ? '#' + t.id : '') : '?'}`); if (keyLog.length > 8) keyLog.shift(); scheduleRender(); } if (!enabled || !model) return; if (e.altKey || e.ctrlKey || e.metaKey) return; if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return; const t = e.target; if (!(t instanceof Element) || !t.closest('g.xwd__cell, main')) return; if (t.closest('.xwd__toolbar--wrapper, input, textarea, [contenteditable]')) return; const selKey = selectedClueKey(); const i = model.clues.findIndex((c) => c.key === selKey); if (i < 0) return; e.preventDefault(); e.stopPropagation(); const clue = model.clues[i]; if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') { const pos = clue.cells.indexOf(selectedCellIndex()); const to = pos + (e.key === 'ArrowRight' ? 1 : -1); if (pos >= 0 && to >= 0 && to < clue.cells.length) selectCell(clue.cells[to], clue.key); } else { const n = model.clues.length; const to = model.clues[(i + (e.key === 'ArrowDown' ? 1 : -1) + n) % n]; selectClue(to); } } // --------------------------------------------------------------------------- // Start-up addStyles(); document.documentElement.classList.toggle(ON_CLASS, enabled); window.addEventListener('keydown', onKeyDown, true); // Typing in NYT's rebus box changes an input's value, which the // MutationObserver can't see. for (const type of ['input', 'keyup', 'focusin', 'focusout']) document.addEventListener(type, () => enabled && scheduleRender(), true); new MutationObserver((records) => { if (panel && records.every((r) => panel.contains(r.target))) return; scheduleRender(); }).observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true }); scheduleRender(); // If nothing shows up, leave a note in the console saying what the script // found on the page, so a layout change on NYT's side is easy to spot. const LOG = '[NYT list view]'; const version = typeof GM_info !== 'undefined' ? GM_info.script.version : '?'; console.info(LOG, `v${version} loaded on ${location.pathname}`); setTimeout(() => { if (toggle && toggle.isConnected) { console.info(LOG, toggle.classList.contains('xwdlv-floating') ? 'button added (floating, toolbar not found)' : 'button added to toolbar'); return; } const count = (sel) => document.querySelectorAll(sel).length; const layout = [...new Set([...document.querySelectorAll('[class*="xwd__layout"]')].flatMap((el) => [...el.classList]))]; console.warn(LOG, 'no button yet (still on the Play screen?)', { cells: count('g.xwd__cell'), board: count('.xwd__board'), clueBarAndBoard: count('.xwd__layout_clueBarAndBoard'), clueLists: count('.xwd__clue-list--wrapper'), clues: count('li.xwd__clue--li'), layout, width: window.innerWidth, }); }, 8000); })();