/** * 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("(?~()]|$)", "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