Something went wrong. Try again.
Library to rectify mistakes in the design of CSS. npmx.dev/package/@declanchidlow/fixcss
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526/** * FixCSS - Rectifies mistakes in the design of CSS * Developed by Declan Chidlow (https://vale.rocks) * @version 1.0.0 */
(function (root, factory) { if (typeof define === "function" && define.amd) { define([], factory); } else if (typeof module === "object" && module.exports) { module.exports = factory(); } else { root.fixCSS = factory(); }})(typeof self !== "undefined" ? self : this, function () { "use strict";
// ─── Property Name Fixes ─────────────────────────────────────────────── var PROPERTY_FIXES = { // #2 — animation-iteration-count is unnecessarily verbose "animation-count": "animation-iteration-count",
// #12 — z-index should be z-order or depth "z-order": "z-index", "depth": "z-index",
// #19 — border-radius rounds corners, not borders "corner-radius": "border-radius",
// #21 — hyphens should be a verb (hyphenate), not a plural noun "hyphenate": "hyphens",
// #24 — *-blend-mode is verbose; 'blend' suffices "mix-blend": "mix-blend-mode", "background-blend": "background-blend-mode",
// #36 — display is too generic "display-type": "display",
// #37 — list-style references HTML concepts, not presentation "marker-style": "list-style", "marker-style-type": "list-style-type", "marker-style-position": "list-style-position", "marker-style-image": "list-style-image",
// #46 — shape-outside should mention 'wrap' since it doesn't clip "wrap-shape": "shape-outside", "shape-wrap": "shape-outside",
// #13 — overflow-wrap should be a white-space keyword (handled in values) but we also alias the longhand for completeness "wrap-words": "overflow-wrap",
// Flexbox alignment: writing-mode relative names (mistake #45) "align-inline": "justify-content", "align-block": "align-items", "justify-inline": "justify-items", "justify-block": "justify-content", };
// ─── Value / Keyword Fixes ───────────────────────────────────────────── var VALUE_FIXES = { // #1 — white-space: no-wrap (hyphenated) "white-space": { "no-wrap": "nowrap", "wrap": "pre-wrap", // wrap should exist as a white-space value },
// #4 — vertical-align: text-middle (more accurate than 'middle') "vertical-align": { "text-middle": "middle", "x-middle": "middle", },
// #17 — system color keywords should be hyphenated "*": { "accent-color-text": "accentColorText", "accent-color": "accentColor", "current-color": "currentColor", }, };
// ─── Selector Fixes ──────────────────────────────────────────────────── var SELECTOR_FIXES = { // #29 — :void = current :empty (no children at all) // :empty should match whitespace-only elements (now :blank in spec) ":void": ":empty", "::placeholder-text": "::placeholder", // #40 ":placeholder": ":placeholder-shown", // #40 ":marked-block": "::marker", // #37 — list-item -> marked-block naming };
// ─── Display Value Fixes ─────────────────────────────────────────────── // See mistake #37 — list-item should be marked-block var DISPLAY_VALUES = { "marked-block": "list-item", };
// ─── Unicode Range Fixes ─────────────────────────────────────────────── // See mistake #25 — CSS-consistent unicode notation // Converts u+XXXX-XXXX -> U+XXXX-XXXX and u+XXXX -> U+XXXX var UNICODE_RANGE_RE = /u\+([0-9a-fA-F]+)/g;
// ─── Core Conversion ───────────────────────────────────────────────────
/** * Convert a CSS string from 'fixed' syntax to browser-compatible CSS. * * @param {string} css - The CSS source to convert * @param {Object} [opts] - Options * @param {boolean} [opts.fixShorthandDefaults=true] - Apply behavioural fixes (e.g. single-value background-size duplication) * @param {boolean} [opts.fixAxisOrder=true] - Swap vertical-first axis order to horizontal-first * @param {boolean} [opts.fixSelectorCombinators=true] - Convert >> and ++ combinators * @returns {string} Converted CSS */ function fixCSS(css, opts) { opts = Object.assign( { fixShorthandDefaults: true, fixAxisOrder: true, fixSelectorCombinators: true, }, opts, );
var result = css;
// Handle strings var strings = []; result = result.replace(/([''"])(?:(?!\1|\\).|\\.)*\1/g, function (match) { strings.push(match); return "STR" + (strings.length - 1) + ""; });
// Handle comments var comments = []; result = result.replace(/\/\*[\s\S]*?\*\//g, function (match) { comments.push(match); return "CMT" + (comments.length - 1) + ""; });
// Fix unicode ranges (#25) result = result.replace(UNICODE_RANGE_RE, function (match, hex) { return "U+" + hex.toUpperCase(); });
// Fix selectors // Match selectors preceded by {, }, ; or at the start of the string. // Capture separator whitespace in group 1 to preserve formatting. result = result.replace(/(^|[{};]\s*)([^{};]+?)(\s*\{)/gm, function (match, before, selectorBlock, brace) { var fixed = selectorBlock;
// Fix combinator patterns (#23) — must be done before general selector fixes if (opts.fixSelectorCombinators) { // Descendant combinator: >> -> space // Only outside of functional notation fixed = fixed.replace(/\)\s*>>\s*/g, ") >> "); // mark >> after ) for later fixed = fixed.replace(/\s*>>\s*/g, " "); // Indirect sibling: ++ -> ~ fixed = fixed.replace(/\+\+/g, "~"); }
// Fix pseudo-class/element names // Sort keys by length descending so longer matches (::placeholder-text) are processed before shorter ones (:placeholder) to avoid double-conversion var selectorKeys = Object.keys(SELECTOR_FIXES) .filter(function (k) { return SELECTOR_FIXES[k]; }) .sort(function (a, b) { return b.length - a.length; });
for (var i = 0; i < selectorKeys.length; i++) { var key = selectorKeys[i]; // Escape special regex chars in key var escapedKey = key.replace(/[.*+?^${}()|[\]\\:]/g, "\\$&"); // Use negative lookbehind so :placeholder doesn't match inside ::placeholder var regex = new RegExp("(?<!:)(" + escapedKey + ")(?=[\\s:,.[\\]#+>~()]|$)", "g"); fixed = fixed.replace(regex, SELECTOR_FIXES[key]); }
return before + fixed + brace; });
// Fix property names and values inside declaration blocks result = result.replace(/\{([^}]*)\}/g, function (match, declarations) { var fixed = declarations;
// Fix property names for (var prop in PROPERTY_FIXES) { var escapedProp = prop.replace(/([.*+?^${}()|[\]\\])/g, "\\$1"); var propRegex = new RegExp("(^|[;\\s\\n])(" + escapedProp + ")\\s*:", "g"); fixed = fixed.replace(propRegex, function (m, before) { return before + PROPERTY_FIXES[prop] + ":"; }); }
// Fix display values (#37 — marked-block -> list-item, now that display-type -> display) fixed = fixed.replace(/display\s*:\s*([^;!}]+)/g, function (m, val) { var trimmed = val.trim(); if (DISPLAY_VALUES[trimmed]) { return "display: " + DISPLAY_VALUES[trimmed]; } return m; });
// Fix property-specific and global values (data-driven from VALUE_FIXES) fixed = fixPropertyValues(fixed);
// Fix 4-arg rgb/hsl -> rgba/hsla (#22) fixed = fixed.replace(/\brgb\s*\(\s*([^,)]+)\s*,\s*([^,)]+)\s*,\s*([^,)]+)\s*,\s*([^,)]+)\s*\)/g, "rgba($1, $2, $3, $4)"); fixed = fixed.replace(/\bhsl\s*\(\s*([^,)]+)\s*,\s*([^,)]+)\s*,\s*([^,)]+)\s*,\s*([^,)]+)\s*\)/g, "hsla($1, $2, $3, $4)");
// Fix span(N) -> span N in grid properties (#43) fixed = fixed.replace(/\bspan\s*\(\s*(\d+)\s*\)/g, "span $1");
// Fix fr units in flex shorthand (#35) fixed = fixed.replace(/flex\s*:\s*([^;!}]+)/g, function (m, flexVals) { return "flex: " + flexVals.replace(/(\d+(?:\.\d+)?)fr/g, "$1"); });
// Fix shorthand defaults (#8) if (opts.fixShorthandDefaults) { fixed = fixShorthandValues(fixed); }
// Fix axis order for 2-value properties (#9) if (opts.fixAxisOrder) { fixed = fixAxisOrder(fixed); }
// Fix CCW -> CW for 4-value shorthands (#11, opt-in) fixed = fixShorthandDirection(fixed, opts);
return "{" + fixed + "}"; });
// Restore comments result = result.replace(/CMT(\d+)/g, function (match, index) { return comments[parseInt(index, 10)]; });
// Restore strings result = result.replace(/STR(\d+)/g, function (match, index) { return strings[parseInt(index, 10)]; });
return result; }
/** * Fix property-specific and global values, data-driven from VALUE_FIXES. * @private */ function fixPropertyValues(declarations) { var result = declarations; var globalFixes = VALUE_FIXES["*"] || {};
// Per-property value fixes for (var prop in VALUE_FIXES) { if (prop === "*") continue; var fixes = VALUE_FIXES[prop]; var escapedProp = prop.replace(/([.*+?^${}()|[\]\\])/g, "\\$1"); var propRegex = new RegExp(escapedProp + "\\s*:\\s*([^;!}]+)", "g"); result = result.replace(propRegex, function (m, val) { var trimmed = val.trim(); if (fixes[trimmed]) { return prop + ": " + fixes[trimmed]; } return m; }); }
// Global value fixes (any property) — current-color -> currentColor, etc. // Process longest keys first so accent-color-text matches before accent-color var globalKeys = Object.keys(globalFixes).sort(function (a, b) { return b.length - a.length; }); for (var i = 0; i < globalKeys.length; i++) { var key = globalKeys[i]; var escapedKey = key.replace(/([.*+?^${}()|[\]\\])/g, "\\$1"); result = result.replace(new RegExp("\\b" + escapedKey + "\\b", "g"), globalFixes[key]); }
return result; }
/** * Fix shorthand defaults (#8). * Single-value background-size and translate() duplicate to both axes. * @private */ function fixShorthandValues(declarations) { return ( declarations // background-size: X -> background-size: X X (single value duplicates) .replace(/background-size\s*:\s*([^\s;!}]+)(?=\s*[;}!]|$)/g, function (m, val) { return /^(cover|contain|auto)$/.test(val) ? m : "background-size: " + val + " " + val; }) // translate(X) -> translate(X, X) .replace(/translate\s*\(\s*([^,)]+)\s*\)/g, function (m, val) { val = val.trim(); return val === "0" || val === "none" ? m : "translate(" + val + ", " + val + ")"; }) ); }
/** * Fix axis order for properties that should be vertical-first (#9). * background-position and border-spacing currently take H first, V second. * We swap them so the 'correct' CSS (V first) works. * @private */ function fixAxisOrder(declarations) { return declarations.replace(/(background-position|border-spacing)\s*:\s*([^\s;!}]+)\s+([^\s;!}]+)(?=\s*[;}!]|$)/g, "$1: $3 $2"); }
/** * Fix 4-value shorthand direction from CCW to CW (#11). * In 'correct' CSS, margin/padding 4-value shorthands go CCW: top, left, bottom, right. * Browsers use CW: top, right, bottom, left. * Opt-in via convertCCW() or { ccwShorthand: true }. * @private */ function fixShorthandDirection(declarations, opts) { if (!opts.ccwShorthand) return declarations;
var props = "(margin|padding|border-color|border-style|border-width|inset|scroll-margin|scroll-padding)"; var regex = new RegExp(props + "\\s*:\\s*([^\\s;!}]+)\\s+([^\\s;!}]+)\\s+([^\\s;!}]+)\\s+([^\\s;!}]+)(?=\\s*[;}!]|$)", "g");
return declarations.replace(regex, function (match, prop, top, left, bottom, right) { // CCW: top, left, bottom, right -> CW: top, right, bottom, left return prop + ": " + top + " " + right + " " + bottom + " " + left; }); }
/** * Explicitly convert CCW-ordered shorthand values to CW. * Call this when you've written 4-value shorthands in CCW order. * * @param {string} css * @returns {string} */ function convertCCW(css) { return fixCSS(css, { ccwShorthand: true }); }
/** * Convert only the property names (not values or selectors). * Useful for partial conversions. * * @param {string} css * @returns {string} */ function convertProperties(css) { var result = css; for (var prop in PROPERTY_FIXES) { var escapedProp = prop.replace(/([.*+?^${}()|[\]\\])/g, "\\$1"); var regex = new RegExp("(^|[;\\s\\n])(" + escapedProp + ")\\s*:", "g"); result = result.replace(regex, "$1" + PROPERTY_FIXES[prop] + ":"); } return result; }
// ─── Browser Runtime ───────────────────────────────────────────────────
var _debug = false; var _styleObserver = null; var _initialised = false;
function log() { if (_debug) console.log.apply(console, ["[FixCSS]"].concat([].slice.call(arguments))); }
function convertPage() { if (typeof document === "undefined") return;
log("Converting page styles…");
// Convert existing <style> blocks var styles = document.querySelectorAll("style"); for (var i = 0; i < styles.length; i++) { convertStyleElement(styles[i]); }
// Convert existing inline styles var elements = document.querySelectorAll("[style]"); for (var j = 0; j < elements.length; j++) { convertInlineStyle(elements[j]); } }
/** * Convert a single <style> element's content. * @private */ function convertStyleElement(el) { if (el.hasAttribute("data-fixcss-converted")) return; try { var original = el.textContent; var converted = fixCSS(original); if (converted !== original) { el.textContent = converted; log("Converted <style>:", el.id || "(unnamed)"); } } catch (e) { log("Error converting <style>: " + e.message); } el.setAttribute("data-fixcss-converted", "true"); }
/** * Convert a single element's inline style. * @private */ function convertInlineStyle(el) { if (el.hasAttribute("data-fixcss-inline-converted")) return; try { var original = el.getAttribute("style"); // Inline styles need to be wrapped for the converter var wrapped = ".x{" + original + "}"; var converted = fixCSS(wrapped); var unwrapped = converted.replace(/\.x\s*\{\s*/, "").replace(/\s*\}\s*$/, ""); if (unwrapped !== original) { el.setAttribute("style", unwrapped); } } catch (e) { log("Error converting inline style: " + e.message); } el.setAttribute("data-fixcss-inline-converted", "true"); }
function start() { if (_initialised || typeof document === "undefined" || typeof MutationObserver === "undefined") return; _initialised = true;
convertPage();
// Watch for new <style> elements _styleObserver = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { mutation.addedNodes.forEach(function (node) { if (node.nodeType === 1) { // Element if (node.tagName === "STYLE") { convertStyleElement(node); } // Check for <style> descendants var childStyles = node.querySelectorAll ? node.querySelectorAll("style") : []; for (var i = 0; i < childStyles.length; i++) { convertStyleElement(childStyles[i]); } // Check for inline styles on the element itself if (node.hasAttribute && node.hasAttribute("style")) { convertInlineStyle(node); } // Check descendants with inline styles if (node.querySelectorAll) { var inlineEls = node.querySelectorAll("[style]"); for (var j = 0; j < inlineEls.length; j++) { convertInlineStyle(inlineEls[j]); } } } }); }); });
_styleObserver.observe(document.documentElement, { childList: true, subtree: true, });
log("Observing DOM for new styles…"); }
function shutdown() { if (_styleObserver) { _styleObserver.disconnect(); _styleObserver = null; } _initialised = false; log("Shut down."); }
/** * Enable or disable debug logging. * @param {boolean} [flag=true] */ function debug(flag) { _debug = flag !== false; log("Debug mode:", _debug ? "ON" : "OFF"); }
// ─── Auto-initialise in browser ──────────────────────────────────────── if (typeof document !== "undefined" && typeof window !== "undefined") { if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", start); } else { // DOM already ready setTimeout(start, 0); } }
// ─── Public API ──────────────────────────────────────────────────────── return { // Core conversion fixCSS: fixCSS, convertCCW: convertCCW, convertProperties: convertProperties,
// Browser runtime convertPage: convertPage, start: start, shutdown: shutdown, debug: debug,
// Reference tables PROPERTY_FIXES: PROPERTY_FIXES, VALUE_FIXES: VALUE_FIXES, SELECTOR_FIXES: SELECTOR_FIXES, DISPLAY_VALUES: DISPLAY_VALUES,
VERSION: "1.0.0", };});