Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple ignored CSS blocks #181

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions src/htmlminifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -904,14 +904,35 @@ async function minifyHTML(value, options, partialMarkup) {
});

const ids = [];
new CleanCSS().minify(wrapCSS(text, type)).warnings.forEach(function (warning) {
const match = uidPattern.exec(warning);
if (match) {
const id = uidAttr + match[2] + uidAttr;
text = text.replace(id, ignoreCSS(id));
ids.push(id);
// Loop removing a single ID at a time from the warnings, a
// warning might contain multiple IDs in the context, but we only
// handle the first match on each attempt.
while (true) {
const minifyTest = new CleanCSS().minify(wrapCSS(text, type));
if (minifyTest.warnings.length === 0) {
// There are no warnings.
break;
}
});
if (!minifyTest.warnings.every(function (warning) {
// It is very important to reset the RegExp before searching
// as it's re-used each time.
uidPattern.lastIndex = 0;
const match = uidPattern.exec(warning);
if (match) {
const id = uidAttr + match[2] + uidAttr;
// Only substitute each ID once, if this has come up
// multiple times, then we need to abort.
if (!ids.includes(id)) {
text = text.replace(id, ignoreCSS(id));
ids.push(id);
return true;
}
}
return false;
})) {
break;
}
}

return fn(text, type).then(chunk => {
ids.forEach(function (id) {
Expand Down
11 changes: 11 additions & 0 deletions tests/minifier.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -3594,3 +3594,14 @@ test('minify Content-Security-Policy', async () => {
input = '<meta http-equiv="content-security-policy" content="default-src \'self\'; img-src https://*;">';
expect(await minify(input)).toBe(input);
});

test('minify CSS multiple ignore in single warning', async () => {
const input = '<style type="text/css">\n{% ignore1 %}\na {\n{% ignore2 %}\n}\n{% ignore3 %}\n</style>';
const output = '<style type="text/css">\n{% ignore1 %}\na{\n{% ignore2 %}\n}\n{% ignore3 %}\n</style>';
expect(await minify(input, {
ignoreCustomFragments: [/\{%[\s\S]*?%\}/],
minifyCSS: {
level: 0
}
})).toBe(output);
});