Skip to content

Emit theme colors as CSS vars with fallbacks; add webCompatibility SVG normalize - #8008

Open
AMDphreak wants to merge 4 commits into
mermaid-js:developfrom
AMDphreak:feat/css-variable-theme-web-compatibility
Open

Emit theme colors as CSS vars with fallbacks; add webCompatibility SVG normalize#8008
AMDphreak wants to merge 4 commits into
mermaid-js:developfrom
AMDphreak:feat/css-variable-theme-web-compatibility

Conversation

@AMDphreak

@AMDphreak AMDphreak commented Jul 29, 2026

Copy link
Copy Markdown

Summary

  • Add cssVariableTheme config: after concrete theme render, rewrite SVG theme colors in <style> and presentation attrs to var(--mermaid-<slot>, <resolvedFallback>) so one prerendered SVG works under host light/dark themes.
  • Add webCompatibility config: ensure viewBox, set width="100%" / height="auto", set preserveAspectRatio when missing, optionally strip hardcoded backgrounds.
  • Logic lives in packages/mermaid/src/utils/svgCssVars.ts (thin in-tree mirror of https://github.com/openshellorg/mermaid-svg-css-vars — no new dependency).
  • Unit tests in svgCssVars.spec.ts.

This is emit-time CSS vars with fallbacks. It is not #6860 (CSS vars as themeVariables inputs fail because khroma derivation needs concrete colors).

Closes / implements: #8007
Related: #6860

Test plan

  • vitest run packages/mermaid/src/utils/svgCssVars.spec.ts (5 tests passed)
  • tsx .esbuild/build.ts succeeds with updated config schema
  • Manual: mermaid.render with { cssVariableTheme: true, webCompatibility: true } and confirm SVG contains var(--mermaid-…) and responsive root attrs
  • Confirm default false leaves existing SVG output unchanged

Summary

Adds opt-in SVG post-processing configuration:

  • cssVariableTheme rewrites theme colors in SVG paint contexts to CSS variables with resolved fallbacks.
  • webCompatibility normalizes SVG sizing, viewBox, preserveAspectRatio, and optional background removal.
  • Integrates both options into Mermaid’s SVG serialization pipeline.
  • Adds nested directive validation for supported options and unsafe values.
  • Updates configuration types, schema, defaults, and documentation.
  • Adds unit and integration tests.
  • Adds a minor-release changeset.

Defaults remain disabled to preserve existing output. The build succeeds. Manual validation is pending.

Emit theme colors as var(--mermaid-<slot>, <resolved>) after concrete render, and normalize SVG for responsive host embedding. Distinct from accepting CSS vars as themeVariables inputs (mermaid-js#6860); implements mermaid-js#8007.

Co-authored-by: Cursor <cursoragent@cursor.com>
@netlify

netlify Bot commented Jul 29, 2026

Copy link
Copy Markdown

Deploy Preview for mermaid-js ready!

Name Link
🔨 Latest commit 7071d00
🔍 Latest deploy log https://app.netlify.com/projects/mermaid-js/deploys/6a7ba5d20999ac00081bd5fe
😎 Deploy Preview https://deploy-preview-8008--mermaid-js.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@github-actions github-actions Bot added the Type: Enhancement New feature or request label Jul 29, 2026
@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5b73959e-c0d7-4b15-be07-c66d613e493e

📥 Commits

Reviewing files that changed from the base of the PR and between f9d66ad and 7071d00.

📒 Files selected for processing (3)
  • docs/config/setup/mermaid/interfaces/MermaidConfig.md
  • packages/mermaid/src/utils/sanitizeDirective.ts
  • packages/mermaid/src/utils/svgCssVars.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/mermaid/src/utils/sanitizeDirective.ts
  • packages/mermaid/src/utils/svgCssVars.ts
  • docs/config/setup/mermaid/interfaces/MermaidConfig.md

📝 Walkthrough

Walkthrough

Adds opt-in CSS-variable theme rewriting and web-compatible SVG normalization. The change defines, validates, defaults, documents, tests, and applies both options during Mermaid SVG serialization.

Changes

SVG Web Compatibility Configuration

Layer / File(s) Summary
Configuration contract and defaults
packages/mermaid/src/config.type.ts, packages/mermaid/src/schemas/config.schema.yaml, packages/mermaid/src/defaultConfig.ts
Adds cssVariableTheme and webCompatibility options, schema definitions, and default values.
Nested option validation
packages/mermaid/src/utils/sanitizeDirective.ts, packages/mermaid/src/utils/sanitizeDirective.spec.ts
Validates supported nested fields and removes unsafe, unknown, or invalid values.
SVG transformation utilities
packages/mermaid/src/utils/svgCssVars.ts, packages/mermaid/src/utils/svgCssVars.spec.ts
Rewrites paint colors to CSS variables with fallbacks and normalizes SVG dimensions, viewBox, background styles, and aspect ratio.
Serialization integration and documentation
packages/mermaid/src/mermaidAPI.ts, packages/mermaid/src/mermaidAPI.spec.ts, docs/config/setup/mermaid/interfaces/MermaidConfig.md, docs/config/setup/defaultConfig/variables/configKeys.md, .changeset/css-var-theme-web-compat.md
Applies SVG preparation before sanitization, verifies rendered output, refreshes configuration references, and adds a minor-release changeset.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant MermaidAPI
  participant prepareMermaidSvgForWeb
  participant rewriteMermaidSvgCssVars
  participant normalizeMermaidSvgForWeb
  MermaidAPI->>prepareMermaidSvgForWeb: serialized SVG and configuration
  prepareMermaidSvgForWeb->>rewriteMermaidSvgCssVars: theme variables and CSS prefix
  rewriteMermaidSvgCssVars-->>prepareMermaidSvgForWeb: rewritten SVG
  prepareMermaidSvgForWeb->>normalizeMermaidSvgForWeb: web compatibility options
  normalizeMermaidSvgForWeb-->>prepareMermaidSvgForWeb: normalized SVG
  prepareMermaidSvgForWeb-->>MermaidAPI: transformed SVG before sanitization
Loading

Possibly related issues

  • mermaid-js/mermaid#8007: The PR implements the issue’s CSS-variable emission and SVG web-compatibility features.

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes both primary changes: CSS-variable theme fallbacks and web-compatible SVG normalization.
Description check ✅ Passed The description explains the changes, design approach, related issues, and test status, with only minor template sections omitted.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pkg-pr-new

pkg-pr-new Bot commented Jul 29, 2026

Copy link
Copy Markdown

Open in StackBlitz

@mermaid-js/examples

npm i https://pkg.pr.new/@mermaid-js/examples@8008

mermaid

npm i https://pkg.pr.new/mermaid@8008

@mermaid-js/layout-elk

npm i https://pkg.pr.new/@mermaid-js/layout-elk@8008

@mermaid-js/layout-tidy-tree

npm i https://pkg.pr.new/@mermaid-js/layout-tidy-tree@8008

@mermaid-js/mermaid-zenuml

npm i https://pkg.pr.new/@mermaid-js/mermaid-zenuml@8008

@mermaid-js/parser

npm i https://pkg.pr.new/@mermaid-js/parser@8008

@mermaid-js/tiny

npm i https://pkg.pr.new/@mermaid-js/tiny@8008

commit: 7071d00

@changeset-bot

changeset-bot Bot commented Jul 29, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 7071d00

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
mermaid Minor

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@codecov

codecov Bot commented Jul 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.74074% with 30 lines in your changes missing coverage. Please review.
✅ Project coverage is 77.64%. Comparing base (9665f6d) to head (7071d00).
⚠️ Report is 59 commits behind head on develop.

Files with missing lines Patch % Lines
packages/mermaid/src/utils/svgCssVars.ts 92.88% 18 Missing ⚠️
packages/mermaid/src/mermaidAPI.ts 30.00% 7 Missing ⚠️
packages/mermaid/src/utils/sanitizeDirective.ts 91.52% 5 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop    #8008      +/-   ##
===========================================
+ Coverage    77.54%   77.64%   +0.10%     
===========================================
  Files          564      573       +9     
  Lines        74906    75600     +694     
  Branches     12661    15006    +2345     
===========================================
+ Hits         58087    58703     +616     
- Misses       15821    15893      +72     
- Partials       998     1004       +6     
Flag Coverage Δ
e2e 70.43% <14.14%> (-0.30%) ⬇️
unit 74.89% <90.74%> (+0.06%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
packages/mermaid/src/defaultConfig.ts 52.20% <100.00%> (-10.95%) ⬇️
packages/mermaid/src/schemas/config.schema.yaml 100.00% <ø> (ø)
packages/mermaid/src/utils/sanitizeDirective.ts 93.91% <91.52%> (-1.59%) ⬇️
packages/mermaid/src/mermaidAPI.ts 91.97% <30.00%> (+0.55%) ⬆️
packages/mermaid/src/utils/svgCssVars.ts 92.88% <92.88%> (ø)

... and 34 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (1)
packages/mermaid/src/mermaidAPI.ts (1)

594-603: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Cover this branch through serializeSvg().

The new tests exercise prepareMermaidSvgForWeb directly, but not configuration propagation or the transformed output after sandbox/DOMPurify processing. Add a focused mermaidAPI regression test for the new flags.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/mermaid/src/mermaidAPI.ts` around lines 594 - 603, Add a focused
mermaidAPI regression test covering serializeSvg() with cssVariableTheme and
webCompatibility enabled, verifying both configuration propagation to
prepareMermaidSvgForWeb and the resulting sanitized/transformed SVG output.
Reuse the existing test setup and assert the behavior through the public
serialization path rather than calling prepareMermaidSvgForWeb directly.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/mermaid/src/utils/sanitizeDirective.ts`:
- Around line 70-74: Replace the blanket early skip for cssVariableTheme and
webCompatibility in sanitizeDirective with explicit nested-option validation.
Preserve the prototype-pollution key checks, validate prefix and
preserveAspectRatio as strings restricted to a safe charset, and validate other
supported nested options as booleans while rejecting unknown keys; reuse the
existing validation patterns or helpers where applicable.
- Around line 70-74: In packages/mermaid/src/utils/sanitizeDirective.ts:70-74,
replace the cssVariableTheme/webCompatibility bypass with targeted nested
validation: require prefix and preserveAspectRatio to be strings using a safe
charset excluding ", <, >, ), and ;, require other nested values to be booleans,
and retain the __/proto/constr guard. In
packages/mermaid/src/utils/svgCssVars.ts:181-191, harden setAttr/removeAttr by
escaping attribute values, including ", <, and &, before interpolation; also
escape prefix at the CSS var construction sites around lines 127 and 158.

In `@packages/mermaid/src/utils/svgCssVars.ts`:
- Around line 17-29: Update rewriteMermaidSvgCssVars to scope color-variable
replacement to SVG styling contexts only: fill/stroke/style attribute values and
generated <style> CSS content. Do not perform global serialized-SVG text
replacement, and ensure element text content such as labels remains unchanged;
adjust LOOKS_LIKE_COLOR handling as needed to support this scoped matching.
- Around line 208-219: Change the stripBackground default in the options
normalization block to false so webCompatibility enabled via the boolean form
does not remove diagram backgrounds implicitly. Preserve explicit
options.stripBackground values while keeping the existing defaults for
responsiveWidth, responsiveHeight, ensureViewBox, and preserveAspectRatio
unchanged.
- Around line 85-97: Update colorOccurrenceRegex so the shorthand alternative is
generated only when each expanded hex color component is a doubled pair;
otherwise match only the full-length hex value. Apply this validation for both
six-digit and eight-digit values, preserving the existing case-insensitive regex
behavior and fallback handling.

---

Nitpick comments:
In `@packages/mermaid/src/mermaidAPI.ts`:
- Around line 594-603: Add a focused mermaidAPI regression test covering
serializeSvg() with cssVariableTheme and webCompatibility enabled, verifying
both configuration propagation to prepareMermaidSvgForWeb and the resulting
sanitized/transformed SVG output. Reuse the existing test setup and assert the
behavior through the public serialization path rather than calling
prepareMermaidSvgForWeb directly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: af86abec-bf7c-4418-a091-820bd8ecb7b2

📥 Commits

Reviewing files that changed from the base of the PR and between 9665f6d and f599ca9.

📒 Files selected for processing (10)
  • docs/config/setup/defaultConfig/variables/configKeys.md
  • docs/config/setup/mermaid/interfaces/MermaidConfig.md
  • docs/config/setup/mermaid/interfaces/UnknownDiagramError.md
  • packages/mermaid/src/config.type.ts
  • packages/mermaid/src/defaultConfig.ts
  • packages/mermaid/src/mermaidAPI.ts
  • packages/mermaid/src/schemas/config.schema.yaml
  • packages/mermaid/src/utils/sanitizeDirective.ts
  • packages/mermaid/src/utils/svgCssVars.spec.ts
  • packages/mermaid/src/utils/svgCssVars.ts

Comment thread packages/mermaid/src/utils/sanitizeDirective.ts Outdated
Comment thread packages/mermaid/src/utils/svgCssVars.ts
Comment thread packages/mermaid/src/utils/svgCssVars.ts
Comment thread packages/mermaid/src/utils/svgCssVars.ts
@argos-ci

argos-ci Bot commented Jul 29, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Argos notifications ↗︎

Build Status Details Updated (UTC)
default (Inspect) ✅ No changes detected - Aug 11, 2026, 11:05 PM

Scope color rewrites to paint contexts, default stripBackground to off, validate nested directive options, and add a changeset.

Co-authored-by: Cursor <cursoragent@cursor.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/mermaid/src/utils/sanitizeDirective.ts`:
- Around line 105-162: Ensure all CSS custom-property prefixes begin with “--”.
In packages/mermaid/src/utils/sanitizeDirective.ts lines 105-162, reject or
normalize prefix values lacking that marker; in
packages/mermaid/src/utils/svgCssVars.ts lines 122-139, pass the normalized
prefix to buildBindings; and in packages/mermaid/src/utils/svgCssVars.ts lines
307-317, update sanitizeCssIdent to add “--” for direct API calls. Add coverage
in packages/mermaid/src/utils/sanitizeDirective.spec.ts lines 48-73 for a prefix
without “--”, asserting rejection or normalization.

In `@packages/mermaid/src/utils/svgCssVars.ts`:
- Around line 181-197: Update rewritePaintContexts so rewrite is applied only to
values of paint declarations within <style> blocks and style attributes,
including fill, stroke, stop-color, color, flood-color, and lighting-color.
Preserve selectors, custom-property names, URLs, and unrelated declaration
values; ensure `.red { fill: red; }` retains its selector while rewriting only
the fill value, and add a regression test for this case.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f547fc21-e4da-47b8-a5e7-fbddbe6314eb

📥 Commits

Reviewing files that changed from the base of the PR and between f599ca9 and f9d66ad.

📒 Files selected for processing (9)
  • .changeset/css-var-theme-web-compat.md
  • docs/config/setup/mermaid/interfaces/MermaidConfig.md
  • packages/mermaid/src/config.type.ts
  • packages/mermaid/src/mermaidAPI.spec.ts
  • packages/mermaid/src/schemas/config.schema.yaml
  • packages/mermaid/src/utils/sanitizeDirective.spec.ts
  • packages/mermaid/src/utils/sanitizeDirective.ts
  • packages/mermaid/src/utils/svgCssVars.spec.ts
  • packages/mermaid/src/utils/svgCssVars.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/mermaid/src/config.type.ts
  • packages/mermaid/src/utils/svgCssVars.spec.ts
  • packages/mermaid/src/schemas/config.schema.yaml
  • docs/config/setup/mermaid/interfaces/MermaidConfig.md

Comment on lines +105 to +162
/** Reject `"`, `<`, `>`, `)`, `;` so values cannot break out of SVG attrs / CSS `var()`. */
const SAFE_OPTION_STRING = /^[^"<>);]+$/;
const CSS_VAR_PREFIX = /^(--)?[\w-]*$/;

const CSS_VARIABLE_THEME_NESTED = new Set(['prefix']);
const WEB_COMPATIBILITY_NESTED = new Set([
'responsiveWidth',
'responsiveHeight',
'ensureViewBox',
'stripBackground',
'preserveAspectRatio',
]);

const sanitizeSvgPostProcessOptions = (
topKey: 'cssVariableTheme' | 'webCompatibility',
opts: Record<string, unknown>
): void => {
const allowed =
topKey === 'cssVariableTheme' ? CSS_VARIABLE_THEME_NESTED : WEB_COMPATIBILITY_NESTED;
for (const nested of Object.keys(opts)) {
const value = opts[nested];
if (
nested.startsWith('__') ||
nested.includes('proto') ||
nested.includes('constr') ||
!allowed.has(nested)
) {
log.debug('sanitize deleting nested key:', topKey, nested);
delete opts[nested];
continue;
}
if (nested === 'prefix') {
if (
typeof value !== 'string' ||
!CSS_VAR_PREFIX.test(value) ||
!SAFE_OPTION_STRING.test(value)
) {
log.debug('sanitize deleting invalid prefix:', value);
delete opts[nested];
}
continue;
}
if (nested === 'preserveAspectRatio') {
if (typeof value === 'boolean') {
continue;
}
if (typeof value !== 'string' || !SAFE_OPTION_STRING.test(value)) {
log.debug('sanitize deleting invalid preserveAspectRatio:', value);
delete opts[nested];
}
continue;
}
if (typeof value !== 'boolean') {
log.debug('sanitize deleting non-boolean nested option:', nested, value);
delete opts[nested];
}
}
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Ensure every emitted CSS custom property starts with --.

A valid directive or API option such as { prefix: 'host-' } currently emits var(host-primaryColor, ...). That is not a CSS custom property reference, so the affected paint declaration becomes invalid.

  • packages/mermaid/src/utils/sanitizeDirective.ts#L105-L162: reject or normalize prefixes that do not start with --.
  • packages/mermaid/src/utils/svgCssVars.ts#L122-L139: ensure buildBindings receives a normalized prefix.
  • packages/mermaid/src/utils/svgCssVars.ts#L307-L317: make sanitizeCssIdent add -- when it is absent, so direct API calls are safe.
  • packages/mermaid/src/utils/sanitizeDirective.spec.ts#L48-L73: add coverage for a prefix without -- and assert rejection or normalized output.
📍 Affects 3 files
  • packages/mermaid/src/utils/sanitizeDirective.ts#L105-L162 (this comment)
  • packages/mermaid/src/utils/svgCssVars.ts#L122-L139
  • packages/mermaid/src/utils/svgCssVars.ts#L307-L317
  • packages/mermaid/src/utils/sanitizeDirective.spec.ts#L48-L73
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/mermaid/src/utils/sanitizeDirective.ts` around lines 105 - 162,
Ensure all CSS custom-property prefixes begin with “--”. In
packages/mermaid/src/utils/sanitizeDirective.ts lines 105-162, reject or
normalize prefix values lacking that marker; in
packages/mermaid/src/utils/svgCssVars.ts lines 122-139, pass the normalized
prefix to buildBindings; and in packages/mermaid/src/utils/svgCssVars.ts lines
307-317, update sanitizeCssIdent to add “--” for direct API calls. Add coverage
in packages/mermaid/src/utils/sanitizeDirective.spec.ts lines 48-73 for a prefix
without “--”, asserting rejection or normalization.

Comment on lines +181 to +197
/**
* Rewrite colors only in paint contexts: `<style>` CSS and fill/stroke/style attrs.
* Never touch element text (labels like "Red Team").
*/
function rewritePaintContexts(svg: string, rewrite: (chunk: string) => string): string {
let out = svg.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, (block) => rewrite(block));
out = out.replace(
/\b(fill|stroke|stop-color|color|flood-color|lighting-color)\s*=\s*("[^"]*"|'[^']*')/gi,
(_full, name: string, quoted: string) => {
const q = quoted[0];
return `${name}=${q}${rewrite(quoted.slice(1, -1))}${q}`;
}
);
out = out.replace(/\bstyle\s*=\s*("[^"]*"|'[^']*')/gi, (_full, quoted: string) => {
const q = quoted[0];
return `style=${q}${rewrite(quoted.slice(1, -1))}${q}`;
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Limit rewriting to paint declaration values.

rewritePaintContexts rewrites the complete <style> block and complete style attribute value. If a fallback is red, it rewrites a selector such as .red { ... } into invalid CSS. It can also rewrite matching text in non-paint declarations.

Rewrite only the values of paint properties such as fill, stroke, and stop-color. Do not rewrite selectors, custom-property names, URLs, or unrelated declaration values. Add a regression test for .red { fill: red; }.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/mermaid/src/utils/svgCssVars.ts` around lines 181 - 197, Update
rewritePaintContexts so rewrite is applied only to values of paint declarations
within <style> blocks and style attributes, including fill, stroke, stop-color,
color, flood-color, and lighting-color. Preserve selectors, custom-property
names, URLs, and unrelated declaration values; ensure `.red { fill: red; }`
retains its selector while rewriting only the fill value, and add a regression
test for this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Type: Enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant