Skip to content

Commit e1fc30b

Browse files
feat(html): minify the stylesheets an SVG or XHTML document embeds
The XML printer offers the embedded renderer a `<style>` body and a `style=""` value, both synchronously and deferred, but only on elements whose resolved namespace is SVG or XHTML, where they are CSS. The XML comparison's webpack row now runs with the built-in renderer a build uses. Claude-Session: https://claude.ai/code/session_01WzCD9CDRFzG1j2yQARWzLp Co-authored-by: Alexander Akait <[email protected]>
1 parent 3f661f8 commit e1fc30b

5 files changed

Lines changed: 259 additions & 2 deletions

File tree

‎lib/html/syntax-parser.js‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12840,6 +12840,77 @@ const _xmlPrintsChildren = (path, minify) => {
1284012840
return false;
1284112841
};
1284212842

12843+
// The namespaces whose `<style>` and `style=""` hold CSS; in any other one the
12844+
// same names are data a stylesheet has nothing to do with.
12845+
const XML_STYLED_NAMESPACES = new Set([
12846+
"http://www.w3.org/2000/svg",
12847+
"http://www.w3.org/1999/xhtml"
12848+
]);
12849+
12850+
/**
12851+
* Whether an XML element is in a namespace that styles with CSS, read off the
12852+
* `xmlns` declarations in scope for its prefix (Namespaces in XML §6.2).
12853+
* @param {HtmlElement} node the element
12854+
* @returns {boolean} true for an SVG or XHTML element
12855+
*/
12856+
const _xmlElementIsStyled = (node) => {
12857+
const name = _tagNameOf(node);
12858+
const colon = name.indexOf(":");
12859+
const declaration = colon === -1 ? "xmlns" : `xmlns:${name.slice(0, colon)}`;
12860+
for (let n = node; n !== 0; n = _nodeParents[n]) {
12861+
if (_S._nodeTypes[n] !== NodeType.Element) break;
12862+
const start = _nodeAttrStarts[n];
12863+
for (let i = start; i < start + _nodeAttrCounts[n]; i++) {
12864+
if (_attrNames[i] === declaration) {
12865+
return XML_STYLED_NAMESPACES.has(decodeXmlAttribute(_attrValueOf(i)));
12866+
}
12867+
}
12868+
}
12869+
return false;
12870+
};
12871+
12872+
/**
12873+
* XML character data in its shortest well-formed spelling: as it stands where
12874+
* nothing in it is markup, else a CDATA section, else escaped.
12875+
* @param {string} text decoded text
12876+
* @returns {string} the text as XML content
12877+
*/
12878+
const _xmlCharacterData = (text) => {
12879+
if (!text.includes("<") && !text.includes("&")) {
12880+
return text.replace(/]]>/g, "]]&gt;").replace(/\r/g, "&#13;");
12881+
}
12882+
return text.includes("]]>") || text.includes("\r")
12883+
? escapeXmlText(text)
12884+
: `<![CDATA[${text}]]>`;
12885+
};
12886+
12887+
/**
12888+
* Offer a `style` attribute of an SVG or XHTML element to the caller's renderer,
12889+
* as the declaration list it is.
12890+
* @param {string} value the decoded value
12891+
* @returns {string | null} the value written between its quotes, the marker standing for it, or null when nothing renders it
12892+
*/
12893+
const _xmlStyleAttribute = (value) => {
12894+
/**
12895+
* @param {string} css what to write
12896+
* @returns {string} it quoted
12897+
*/
12898+
const quote = (css) => {
12899+
const delimiter = css.includes('"') && !css.includes("'") ? "'" : '"';
12900+
return `${delimiter}${escapeXmlAttribute(css, delimiter)}${delimiter}`;
12901+
};
12902+
if (_S._deferEmbeddedSource !== undefined) {
12903+
return _deferEmbedded(
12904+
value,
12905+
CSS_TYPE,
12906+
(rendered) => quote(typeof rendered === "string" ? rendered : value),
12907+
BLOCK_CONTENTS
12908+
);
12909+
}
12910+
const rendered = _renderEmbeddedOrNull(value, CSS_TYPE, BLOCK_CONTENTS);
12911+
return rendered === null ? null : quote(rendered);
12912+
};
12913+
1284312914
/**
1284412915
* An XML element's start tag: as written, or when minifying rebuilt with one
1284512916
* space between attributes and each value in its shortest well-formed spelling.
@@ -12855,11 +12926,26 @@ const _xmlOpenTag = (path, minify) => {
1285512926
}
1285612927
let out = `<${_tagNameOf(node)}`;
1285712928
const start = _nodeAttrStarts[node];
12929+
const rendering =
12930+
_S._renderEmbeddedSource !== undefined ||
12931+
_S._deferEmbeddedSource !== undefined;
1285812932
for (let i = start; i < start + _nodeAttrCounts[node]; i++) {
1285912933
// A default the DTD supplies is the DTD's to keep supplying.
1286012934
if (_attrNameStarts[i] === -1) continue;
1286112935
const raw = _attrValueOf(i);
1286212936
const decoded = decodeXmlAttribute(raw);
12937+
if (
12938+
rendering &&
12939+
_attrNames[i] === "style" &&
12940+
decoded.trim() !== "" &&
12941+
_xmlElementIsStyled(node)
12942+
) {
12943+
const styled = _xmlStyleAttribute(decoded);
12944+
if (styled !== null) {
12945+
out += ` style=${styled}`;
12946+
continue;
12947+
}
12948+
}
1286312949
const quote =
1286412950
decoded.split('"').length > decoded.split("'").length ? "'" : '"';
1286512951
let value = escapeXmlAttribute(decoded, quote);
@@ -15191,6 +15277,8 @@ module.exports._mergeableStyleAfter = _mergeableStyleAfter;
1519115277
module.exports._onlyTextChild = _onlyTextChild;
1519215278
module.exports._sheetClosing = _sheetClosing;
1519315279
module.exports._styleRunText = _styleRunText;
15280+
module.exports._xmlCharacterData = _xmlCharacterData;
15281+
module.exports._xmlElementIsStyled = _xmlElementIsStyled;
1519415282
module.exports._xmlOpenTag = _xmlOpenTag;
1519515283
module.exports.baseTag = baseTag;
1519615284
module.exports.buildHeadTags = buildHeadTags;

‎lib/html/syntax-printer.js‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,8 @@ const {
6161
_styleRunText,
6262
_synthesizeOpenTag,
6363
_takeRenderedSheet,
64+
_xmlCharacterData,
65+
_xmlElementIsStyled,
6466
_xmlOpenTag,
6567
collapseWhitespaceRuns,
6668
decodeEntities,
@@ -242,6 +244,31 @@ const _escapeTextContent = (s, minify) => {
242244
.replace(/\r/g, "&#13;");
243245
};
244246

247+
/**
248+
* Whether a text node is the whole body of an SVG or XHTML `<style>`, which a
249+
* caller's renderer is offered as the stylesheet it is.
250+
* @param {HtmlPath} path the accessor positioned on the text node
251+
* @returns {boolean} true when the text is a stylesheet to render
252+
*/
253+
const _isXmlStylesheet = (path) => {
254+
if (
255+
_S._renderEmbeddedSource === undefined &&
256+
_S._deferEmbeddedSource === undefined
257+
) {
258+
return false;
259+
}
260+
const parent = path.parentOf();
261+
if (parent === 0) return false;
262+
const name = path.tagName(parent);
263+
if (name !== "style" && !name.endsWith(":style")) return false;
264+
// A comment or an element beside it splits the sheet, which is left alone.
265+
return (
266+
path.firstChild(parent) === path.node &&
267+
path.nextSibling(path.node) === 0 &&
268+
_xmlElementIsStyled(parent)
269+
);
270+
};
271+
245272
/**
246273
* Print a node of a document parsed as XML. Nothing HTML's serialization does
247274
* applies: no tag is implied or omitted, every value stays quoted, and text is
@@ -269,6 +296,17 @@ const _printXml = (path, writer, minify) => {
269296
case NodeType.Text: {
270297
const raw = path.source();
271298
const data = path.data();
299+
if (minify && _isXmlStylesheet(path)) {
300+
return data.trim() === ""
301+
? raw
302+
: _S._deferEmbeddedSource === undefined
303+
? _xmlCharacterData(_renderEmbedded(data, CSS_TYPE))
304+
: _deferEmbedded(data, CSS_TYPE, (rendered) =>
305+
_xmlCharacterData(
306+
typeof rendered === "string" ? rendered : data
307+
)
308+
);
309+
}
272310
// A CDATA section the input ran out in would hold the end tags after it.
273311
if (!minify) {
274312
return raw.includes("<![CDATA[") && !raw.endsWith("]]>")

‎test/unitCases/HtmlSyntax.unittest.js‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3852,6 +3852,78 @@ b&#10;c">
38523852
expect(printXml(minified, "minify")).toBe(minified);
38533853
});
38543854

3855+
it("should hand SVG and XHTML stylesheets to the embedded renderer", () => {
3856+
const { builtinEmbeddedRenderer } = require("../../lib/html/builtinEmbeddedRenderer");
3857+
const document = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:h="http://www.w3.org/1999/xhtml">
3858+
<style type="text/css"><![CDATA[
3859+
.a { fill : #FFFFFF ; }
3860+
text > tspan { stroke: red }
3861+
a[href="x&y"] { fill: blue }
3862+
]]></style>
3863+
<rect style="fill: #ff0000 ; stroke : none"/>
3864+
<h:style>p { color : red }</h:style>
3865+
<foreignObject><h:p style="color : red">x</h:p></foreignObject>
3866+
<x:style xmlns:x="urn:not-css">keep { this }</x:style>
3867+
<g xmlns="urn:not-css" style="keep : this"><style>keep { this }</style></g>
3868+
<style>a { b : c }<!-- split --></style>
3869+
</svg>`;
3870+
expect(
3871+
/** @type {{ code: string }} */ (
3872+
new SourceProcessor().process(document, {
3873+
xml: true,
3874+
mode: "minify",
3875+
renderEmbeddedSource: builtinEmbeddedRenderer()
3876+
})
3877+
).code
3878+
).toMatchSnapshot();
3879+
});
3880+
3881+
it("should defer an XML stylesheet to an asynchronous renderer", async () => {
3882+
/** @type {string[]} */
3883+
const offered = [];
3884+
const { code } = await new SourceProcessor().processAsync(
3885+
'<svg xmlns="http://www.w3.org/2000/svg"><style>a { b : c }</style><rect style="fill: red"/><style> </style></svg>',
3886+
{
3887+
xml: true,
3888+
mode: "minify",
3889+
renderEmbeddedSource: (
3890+
/** @type {string} */ source,
3891+
/** @type {{ as?: string }} */ hole
3892+
) => {
3893+
offered.push(source);
3894+
return Promise.resolve(hole.as ? 'fill:"a<b"' : "a<b{}");
3895+
}
3896+
}
3897+
);
3898+
expect(offered).toEqual(["a { b : c }", "fill: red"]);
3899+
expect(code).toMatchSnapshot();
3900+
});
3901+
3902+
it("should write a rendered stylesheet in the shortest character data", () => {
3903+
const { _xmlCharacterData } = require("../../lib/html/syntax-parser");
3904+
expect(_xmlCharacterData("a>b{}")).toBe("a>b{}");
3905+
expect(_xmlCharacterData("a]]>b\r")).toBe("a]]&gt;b&#13;");
3906+
expect(_xmlCharacterData("a<b&c")).toBe("<![CDATA[a<b&c]]>");
3907+
expect(_xmlCharacterData("a<b]]>")).toBe("a&lt;b]]&gt;");
3908+
});
3909+
3910+
it("should leave a stylesheet as written when nothing renders it", () => {
3911+
const document =
3912+
'<svg xmlns="http://www.w3.org/2000/svg"><style>a { b : c }</style><rect style="fill : red"/></svg>';
3913+
expect(printXml(document, "minify")).toBe(
3914+
'<svg xmlns="http://www.w3.org/2000/svg"><style>a { b : c }</style><rect style="fill : red"/></svg>'
3915+
);
3916+
expect(
3917+
/** @type {{ code: string }} */ (
3918+
new SourceProcessor().process(document, {
3919+
xml: true,
3920+
mode: "minify",
3921+
renderEmbeddedSource: () => undefined
3922+
})
3923+
).code
3924+
).toBe(document);
3925+
});
3926+
38553927
it("should close what the input ran out in", () => {
38563928
expect(printXml("<r><!-- open", "beautify")).toBe("<r><!-- open--></r>");
38573929
expect(printXml("<r><![CDATA[a<b", "beautify")).toBe("<r>a&lt;b</r>");

‎test/unitCases/__snapshots__/HtmlSyntax.unittest.js.snap‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,20 @@ ANSWER(svg)
6666
</body></html>"
6767
`;
6868
69+
exports[`parseHtml XML mode printing should defer an XML stylesheet to an asynchronous renderer 1`] = `"<svg xmlns=\\"http://www.w3.org/2000/svg\\"><style><![CDATA[a<b{}]]></style><rect style='fill:\\"a&lt;b\\"'/><style> </style></svg>"`;
70+
71+
exports[`parseHtml XML mode printing should hand SVG and XHTML stylesheets to the embedded renderer 1`] = `
72+
"<svg xmlns=\\"http://www.w3.org/2000/svg\\" xmlns:h=\\"http://www.w3.org/1999/xhtml\\">
73+
<style type=\\"text/css\\"><![CDATA[.a{fill:#fff}text>tspan{stroke:red}a[href=\\"x&y\\"]{fill:blue}]]></style>
74+
<rect style=\\"fill:red;stroke:none\\"/>
75+
<h:style>p{color:red}</h:style>
76+
<foreignObject><h:p style=\\"color:red\\">x</h:p></foreignObject>
77+
<x:style xmlns:x=\\"urn:not-css\\">keep { this }</x:style>
78+
<g xmlns=\\"urn:not-css\\" style=\\"keep : this\\"><style>keep { this }</style></g>
79+
<style>a { b : c }</style>
80+
</svg>"
81+
`;
82+
6983
exports[`parseHtml XML mode printing should write XML back as written when beautifying 1`] = `
7084
"<?xml version=\\"1.0\\"?><!DOCTYPE svg [ <!ENTITY ns \\"http://www.w3.org/2000/svg\\"> <!ATTLIST svg version CDATA \\"1.1\\"> ]><!-- drawn by hand --><svg xmlns=\\"&ns;\\" viewBox = \\"0 0 10 10\\" data-q='say \\"hi\\"' data-both=\\"it's &quot;q&quot;\\" data-ws=\\"a
7185
b&#10;c\\">

‎tooling/compare-xml-tools.js‎

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,9 @@ const fs = require("fs");
3131
const path = require("path");
3232
const { pathToFileURL } = require("url");
3333

34+
const {
35+
builtinEmbeddedRenderer
36+
} = require("../lib/html/builtinEmbeddedRenderer");
3437
const { SourceProcessor } = require("../lib/html/syntax");
3538
const {
3639
NodeType,
@@ -407,9 +410,20 @@ const TOOLS = [
407410
}
408411
},
409412
{
413+
// With the renderer a build hands it, so an SVG's stylesheets are minified.
410414
name: "webpack",
411415
stage: "minify",
412-
create: () => (xml) => printXml(xml, "minify")
416+
create: () => {
417+
const renderEmbeddedSource = builtinEmbeddedRenderer();
418+
return (xml) =>
419+
/** @type {{ code: string }} */ (
420+
new SourceProcessor().process(xml, {
421+
xml: true,
422+
mode: "minify",
423+
renderEmbeddedSource
424+
})
425+
).code;
426+
}
413427
},
414428
{
415429
// SVG's own optimizer: it rewrites path data and drops what it deems
@@ -456,6 +470,31 @@ const TOOLS = [
456470
const SVG_ONLY = new Set(["svgo"]);
457471
const SVG_ROOT = /<svg[\s>]/;
458472

473+
const STYLE_ELEMENT = /(?:^|:)style$/;
474+
475+
/**
476+
* A stylesheet as webpack's CSS minifier reads it, run to a fixed point, so a
477+
* tool that minified an SVG's `<style>` is not reported for changing its text.
478+
* @param {string} css a `<style>` body
479+
* @returns {string} its canonical form
480+
*/
481+
const canonicalCss = (css) => {
482+
try {
483+
const { SourceProcessor: CssProcessor } = require("../lib/css/syntax");
484+
485+
const processor = new CssProcessor();
486+
let out = css;
487+
for (let i = 0; i < 3; i++) {
488+
const next = processor.process(out, { mode: "minify" }).code;
489+
if (next === out) break;
490+
out = next;
491+
}
492+
return out;
493+
} catch (_err) {
494+
return css;
495+
}
496+
};
497+
459498
/**
460499
* What a document says, read by a strict XML parser that shares nothing with
461500
* webpack's: every element and attribute, and the text with whitespace runs
@@ -484,7 +523,13 @@ const fingerprint = (parseXml, xml) => {
484523
*/
485524
const walk = (node) => {
486525
if (node.type === "text" || node.type === "cdata") {
487-
const value = node.text.replace(/\s+/g, " ").trim();
526+
const value = (
527+
STYLE_ELEMENT.test(node.parent.name || "")
528+
? canonicalCss(node.text)
529+
: node.text
530+
)
531+
.replace(/\s+/g, " ")
532+
.trim();
488533
if (value !== "") text.push(value);
489534
return;
490535
}

0 commit comments

Comments
 (0)