// ==UserScript==
// @name Responsive Layout Grid Overlay
// @namespace http://tampermonkey.net/
// @version 0.1.0
// @description Overlays a configurable column grid (columns, gutters, margins, max width, baseline) on any page, with per-breakpoint settings, to check that content lines up. Never changes the page layout.
// @author Rob Wood
// @license MIT
// @icon https://www.google.com/s2/favicons?sz=64&domain=robertwood.me
// @homepage https://github.com/cubik73/Tampermonkey-Scripts/
// @supportURL https://github.com/cubik73/Tampermonkey-Scripts/issues
// @updateURL https://raw.githubusercontent.com/cubik73/Tampermonkey-Scripts/main/layout-grid.user.js
// @downloadURL https://raw.githubusercontent.com/cubik73/Tampermonkey-Scripts/main/layout-grid.user.js
// @match *://*/*
// @run-at document-idle
// @grant GM_getValue
// @grant GM_setValue
// @noframes
// ==/UserScript==
(function () {
'use strict';
// Kept in sync with the @version header above.
const SCRIPT_VERSION = '0.1.0';
// Lengths are any CSS length (px, rem, vw, %, clamp(), calc()…), so a
// grid can be described exactly as the site's own CSS describes it.
const DEFAULTS = {
enabled: false,
collapsed: false,
color: '#ff3366',
opacity: 0.15,
baseline: '', // row height for horizontal baseline lines; empty = off
showNumbers: true,
breakpoints: [
{ min: 0, columns: 4, gutter: '16px', margin: '16px', maxWidth: '' },
{ min: 768, columns: 8, gutter: '24px', margin: '32px', maxWidth: '' },
{ min: 1280, columns: 12, gutter: '24px', margin: '40px', maxWidth: '1440px' },
],
};
// Per site, since every site has its own grid.
const STORAGE_KEY = `lg-settings:${location.host}`;
function loadSettings() {
const saved = GM_getValue(STORAGE_KEY, null);
const s = structuredClone(DEFAULTS);
if (saved && typeof saved === 'object') Object.assign(s, saved);
if (!Array.isArray(s.breakpoints) || !s.breakpoints.length) s.breakpoints = structuredClone(DEFAULTS.breakpoints);
return s;
}
let S = loadSettings();
const save = () => GM_setValue(STORAGE_KEY, S);
// Same rule as min-width media queries: the largest min that fits wins.
function activeBreakpoint(bps, width) {
let best = null;
for (const bp of bps) {
if (width >= bp.min && (!best || bp.min >= best.min)) best = bp;
}
return best || bps.reduce((a, b) => (b.min < a.min ? b : a));
}
const validLength = (prop, v) => v.trim() !== '' && CSS.supports(prop, v.trim());
// ---------------------------------------------------------------------
// Shadow DOM host: overlay + panel, isolated from page CSS both ways.
// ---------------------------------------------------------------------
const host = document.createElement('div');
host.id = 'lg-host';
host.style.cssText = 'position:fixed; top:0; left:0; width:0; height:0; z-index:2147483646; pointer-events:none;';
document.documentElement.appendChild(host);
const root = host.attachShadow({ mode: 'open' });
root.innerHTML = `
`;
const $ = (id) => root.getElementById(id);
const gridEl = root.querySelector('.grid');
const baselineEl = root.querySelector('.baseline');
// ---------------------------------------------------------------------
// Overlay rendering
// ---------------------------------------------------------------------
function render() {
const width = window.innerWidth;
const bp = activeBreakpoint(S.breakpoints, width);
host.style.setProperty('--lg-color', S.color);
host.style.setProperty('--lg-opacity', S.opacity);
gridEl.classList.toggle('hidden', !S.enabled);
const cols = Math.max(1, Math.min(48, parseInt(bp.columns, 10) || 1));
gridEl.style.gridTemplateColumns = `repeat(${cols}, minmax(0, 1fr))`;
gridEl.style.columnGap = validLength('column-gap', bp.gutter) ? bp.gutter : '0';
gridEl.style.paddingInline = validLength('padding-left', bp.margin) ? bp.margin : '0';
gridEl.style.maxWidth = validLength('max-width', bp.maxWidth) ? bp.maxWidth : 'none';
if (gridEl.children.length !== cols || gridEl.dataset.numbers !== String(S.showNumbers)) {
gridEl.replaceChildren(...Array.from({ length: cols }, (_, i) => {
const c = document.createElement('div');
c.className = 'col';
if (S.showNumbers) c.textContent = i + 1;
return c;
}));
gridEl.dataset.numbers = String(S.showNumbers);
}
const hasBaseline = validLength('height', S.baseline);
baselineEl.classList.toggle('hidden', !S.enabled || !hasBaseline);
if (hasBaseline) host.style.setProperty('--lg-baseline', S.baseline.trim());
syncBaselineScroll();
$('status').textContent = `${width}px · ≥${bp.min} · ${cols} col`;
root.querySelectorAll('#bps tr').forEach((tr, i) => tr.classList.toggle('active', S.breakpoints[i] === bp));
}
// Baseline lines track the document, not the viewport, so they stay
// on the text as the page scrolls.
function syncBaselineScroll() {
baselineEl.style.backgroundPositionY = `${-window.scrollY}px`;
}
// ---------------------------------------------------------------------
// Panel
// ---------------------------------------------------------------------
function input(type, value, cls, onChange, validProp) {
const el = document.createElement('input');
el.type = type;
el.value = value;
if (cls) el.className = cls;
if (type === 'number') el.min = '0';
const check = () => {
const ok = validProp ? (el.value.trim() === '' || CSS.supports(validProp, el.value.trim())) : el.validity.valid;
el.setAttribute('aria-invalid', String(!ok));
return ok;
};
check();
el.addEventListener('input', () => { if (check()) { onChange(el.value); save(); render(); } });
return el;
}
function buildBreakpointRows() {
// Keep the table in ascending order so it reads like a stylesheet.
S.breakpoints.sort((a, b) => a.min - b.min);
const rows = S.breakpoints.map((bp) => {
const tr = document.createElement('tr');
const cells = [
input('number', bp.min, 'narrow', (v) => { bp.min = Math.max(0, parseInt(v, 10) || 0); }),
input('number', bp.columns, 'narrow', (v) => { bp.columns = Math.max(1, Math.min(48, parseInt(v, 10) || 1)); }),
input('text', bp.gutter, '', (v) => { bp.gutter = v; }, 'column-gap'),
input('text', bp.margin, '', (v) => { bp.margin = v; }, 'padding-left'),
input('text', bp.maxWidth, '', (v) => { bp.maxWidth = v; }, 'max-width'),
];
cells[1].max = '48';
cells[1].min = '1';
cells[4].placeholder = 'none';
cells[0].setAttribute('aria-label', 'Breakpoint min-width in px');
cells[1].setAttribute('aria-label', 'Columns');
cells[2].setAttribute('aria-label', 'Gutter');
cells[3].setAttribute('aria-label', 'Outer margin');
cells[4].setAttribute('aria-label', 'Max width');
// Re-sort only when the user leaves the field, so the row doesn't jump while typing.
cells[0].addEventListener('change', () => { buildBreakpointRows(); render(); });
const del = document.createElement('button');
del.textContent = '×';
del.setAttribute('aria-label', 'Remove breakpoint');
del.disabled = S.breakpoints.length === 1;
del.addEventListener('click', () => {
S.breakpoints.splice(S.breakpoints.indexOf(bp), 1);
save(); buildBreakpointRows(); render();
});
for (const el of [...cells, del]) {
const td = document.createElement('td');
td.appendChild(el);
tr.appendChild(td);
}
return tr;
});
$('bps').replaceChildren(...rows);
}
function syncControls() {
$('enabled').checked = S.enabled;
$('color').value = S.color;
$('opacity').value = S.opacity;
$('baseline').value = S.baseline;
$('numbers').checked = S.showNumbers;
$('body').classList.toggle('hidden', S.collapsed);
$('collapse').textContent = S.collapsed ? '+' : '–';
$('collapse').setAttribute('aria-label', S.collapsed ? 'Expand panel' : 'Collapse panel');
buildBreakpointRows();
}
function setEnabled(on) {
S.enabled = on;
$('enabled').checked = on;
save(); render();
}
$('enabled').addEventListener('change', (e) => setEnabled(e.target.checked));
$('collapse').addEventListener('click', () => { S.collapsed = !S.collapsed; save(); syncControls(); });
$('color').addEventListener('input', (e) => { S.color = e.target.value; save(); render(); });
$('opacity').addEventListener('input', (e) => { S.opacity = Number(e.target.value); save(); render(); });
$('numbers').addEventListener('change', (e) => { S.showNumbers = e.target.checked; save(); render(); });
$('baseline').addEventListener('input', (e) => {
const v = e.target.value.trim();
const ok = v === '' || CSS.supports('height', v);
e.target.setAttribute('aria-invalid', String(!ok));
if (ok) { S.baseline = v; save(); render(); }
});
$('add').addEventListener('click', () => {
const last = S.breakpoints[S.breakpoints.length - 1];
S.breakpoints.push({ ...last, min: Math.max(window.innerWidth, last.min + 1) });
save(); buildBreakpointRows(); render();
});
$('reset').addEventListener('click', () => {
S = { ...structuredClone(DEFAULTS), enabled: S.enabled, collapsed: S.collapsed };
save(); syncControls(); render();
});
// ---------------------------------------------------------------------
// Wiring
// ---------------------------------------------------------------------
window.addEventListener('resize', render);
window.addEventListener('scroll', syncBaselineScroll, { passive: true });
document.addEventListener('keydown', (e) => {
// e.code, not e.key: on macOS Alt changes the produced character.
if (e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && e.code === 'KeyG') {
e.preventDefault();
setEnabled(!S.enabled);
}
});
syncControls();
render();
})();