Repository navigation
feat(expert): render mermaid diagrams in messages #9011
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
Open
andypalmi
wants to merge
10
commits into
main
Choose a base branch
from
feat/expert-mermaid-diagrams
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
cc77817
feat(expert): render mermaid diagrams in messages
5f4706f
feat(expert): export mermaid diagrams, render them as they stream and…
6a80ee9
refactor(expert): show mermaid diagrams rendered by the Expert instea…
d4a5b5e
refactor(expert): nest the mermaid diagram styles under one selector
21990bb
fix(expert): match streamed mermaid blocks to their diagrams ignoring…
ff53ca7
refactor(expert): theme mermaid diagrams through CSS variables
189ab18
refactor(expert): add diagram buttons only when a diagram renders and…
7b9e098
Merge branch 'main' into feat/expert-mermaid-diagrams
andypalmi cc63ef0
fix(expert): keep whitespace while streaming messages
01f1246
fix(expert): sanitize diagrams once, drop their ids and export them i…
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,11 +12,21 @@ | |
| import { mapState } from 'pinia' | ||
|
|
||
| import { CODE_BLOCK_ICONS, useMarkdownHelper } from '@/composables/strings/Markdown.js' | ||
| import { THEME_VARIABLES, sanitizeDiagram, serializeSvg, svgToPngBlob } from '@/composables/strings/Mermaid.js' | ||
| import useStreamingWords from '@/composables/strings/StreamingWords.js' | ||
| import { sanitize } from '@/composables/strings/String.js' | ||
|
|
||
| import { useProductAssistantStore } from '@/stores/product-assistant.js' | ||
|
|
||
| // Sources are compared ignoring whitespace, so a diagram still matches its block if the spacing differs | ||
| function normalizeSource (source) { | ||
| return source.replace(/\s+/g, ' ').trim() | ||
| } | ||
|
|
||
| function diagramButton (label, className, attributes) { | ||
| return `<button type="button" class="ff-btn ff-btn--tertiary ff-btn-small ${className}" ${attributes}>${label}</button>` | ||
| } | ||
|
|
||
| export default { | ||
| name: 'StreamableContent', | ||
| props: { | ||
|
|
@@ -64,12 +74,19 @@ export default { | |
| type: Boolean, | ||
| required: false, | ||
| default: false | ||
| }, | ||
| // SVGs rendered by the Expert, matched to mermaid blocks by their source | ||
| diagrams: { | ||
| type: Array, | ||
| required: false, | ||
| default: () => [] | ||
| } | ||
| }, | ||
| emits: ['streaming-complete', 'update:modelValue'], | ||
| setup () { | ||
| const { stream, text, isStreaming } = useStreamingWords({ | ||
| delayMs: 30 | ||
| delayMs: 10, | ||
| wordsPerTick: 4 | ||
| }) | ||
| const { markedInstance } = useMarkdownHelper() | ||
|
|
||
|
|
@@ -86,6 +103,13 @@ export default { | |
|
|
||
| return rawText | ||
| }, | ||
| // Streaming re-renders the content on every tick, so each diagram is sanitized once up front | ||
| safeDiagrams () { | ||
| return this.diagrams.map(diagram => ({ | ||
| source: normalizeSource(diagram.source || ''), | ||
| svg: sanitizeDiagram(diagram.svg || '') | ||
| })) | ||
| }, | ||
| text () { | ||
| const text = this.shouldStream ? this.streamedText : this.rawText | ||
|
|
||
|
|
@@ -104,6 +128,7 @@ export default { | |
| isStreaming (isStreaming) { | ||
| if (!isStreaming) { | ||
| this.$emit('streaming-complete') | ||
| this.renderDiagrams() | ||
| if (this.modelValue) { | ||
| this.$emit('update:modelValue', { | ||
| ...this.modelValue, | ||
|
|
@@ -117,9 +142,124 @@ export default { | |
| if (this.shouldStream) { | ||
| this.stream(this.rawText) | ||
| } | ||
| this.renderDiagrams() | ||
| }, | ||
| updated () { | ||
| this.renderDiagrams() | ||
| }, | ||
| methods: { | ||
| // Mermaid blocks stay as plain code until their closing fence has streamed in, then | ||
| // are swapped for the SVG the Expert rendered, so earlier diagrams show while later text streams. | ||
| renderDiagrams () { | ||
| if (!this.richContent) return | ||
| const blocks = [...this.$el.querySelectorAll('.ff-code-block--mermaid')] | ||
| const ready = this.isStreaming ? this.completedMermaidBlocks() : blocks.length | ||
| for (const block of blocks.slice(0, ready)) { | ||
| if (block.hasAttribute('data-mermaid-state')) continue | ||
| const source = block.querySelector('pre code')?.textContent || '' | ||
| const svg = this.findDiagramSvg(source) | ||
| if (svg) { | ||
| this.showDiagram(block, svg) | ||
| } else { | ||
| block.setAttribute('data-mermaid-state', 'failed') | ||
| } | ||
| } | ||
| }, | ||
| findDiagramSvg (source) { | ||
| const key = normalizeSource(source) | ||
| return this.safeDiagrams.find(diagram => diagram.source === key)?.svg | ||
| }, | ||
| // The page theme, so exports look like the diagram on screen | ||
| diagramTheme (block) { | ||
| const style = getComputedStyle(block.querySelector('.ff-code-block--diagram')) | ||
| const theme = {} | ||
| for (const name of THEME_VARIABLES) { | ||
| const value = style.getPropertyValue(name).trim() | ||
| if (value) { | ||
| theme[name] = value | ||
| } | ||
| } | ||
| return theme | ||
| }, | ||
| // The streamed text is cut mid-block, so count the mermaid blocks whose end has arrived. | ||
| completedMermaidBlocks () { | ||
| const parts = this.streamedText.split('ff-code-block--mermaid').slice(1) | ||
| return parts.filter(part => part.includes('</pre>')).length | ||
| }, | ||
| showDiagram (block, svg) { | ||
| const diagram = document.createElement('div') | ||
| diagram.className = 'ff-code-block--diagram' | ||
| diagram.innerHTML = svg | ||
| block.appendChild(diagram) | ||
| block.querySelector('pre').hidden = true | ||
| const actions = document.createElement('span') | ||
| actions.className = 'ff-code-block--diagram-actions' | ||
| actions.innerHTML = [ | ||
| diagramButton('Code', 'ff-code-block--toggle', 'aria-pressed="false"'), | ||
| diagramButton('Copy SVG', 'ff-code-block--export', 'data-export="svg"'), | ||
| diagramButton('Copy image', 'ff-code-block--export', 'data-export="image"'), | ||
| diagramButton('Download PNG', 'ff-code-block--export', 'data-export="png"') | ||
| ].join('') | ||
| block.querySelector('.ff-code-block--copy').after(actions) | ||
| block.setAttribute('data-mermaid-state', 'rendered') | ||
| }, | ||
| async exportDiagram (btn) { | ||
| const block = btn.closest('.ff-code-block') | ||
| const source = block.querySelector('pre code')?.textContent || '' | ||
| const svg = this.findDiagramSvg(source) | ||
| if (!svg) return | ||
| const theme = this.diagramTheme(block) | ||
| const label = btn.textContent | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. |
||
| const flash = text => { | ||
| btn.textContent = text | ||
| setTimeout(() => { btn.textContent = label }, 2000) | ||
| } | ||
| try { | ||
| switch (btn.dataset.export) { | ||
| case 'svg': | ||
| await navigator.clipboard.writeText(serializeSvg(svg, theme)) | ||
| flash('Copied') | ||
| break | ||
| case 'image': { | ||
| const blob = svgToPngBlob(svg, { theme }) | ||
| await navigator.clipboard.write([new ClipboardItem({ 'image/png': blob })]) | ||
| flash('Copied') | ||
| break | ||
| } | ||
| case 'png': { | ||
| const url = URL.createObjectURL(await svgToPngBlob(svg, { theme })) | ||
| const a = document.createElement('a') | ||
| a.href = url | ||
| a.download = 'diagram.png' | ||
| a.click() | ||
| // Revoking straight after the click can cancel the download in Safari and Firefox | ||
| setTimeout(() => URL.revokeObjectURL(url), 40 * 1000) | ||
| break | ||
| } | ||
| } | ||
| } catch (_) { | ||
| flash('Failed') | ||
| } | ||
| }, | ||
| handleClick (event) { | ||
| const toggleBtn = event.target.closest('.ff-code-block--toggle') | ||
| if (toggleBtn) { | ||
| const block = toggleBtn.closest('.ff-code-block') | ||
| const showCode = toggleBtn.getAttribute('aria-pressed') !== 'true' | ||
| block.querySelector('pre').hidden = !showCode | ||
| block.querySelector('.ff-code-block--diagram').hidden = showCode | ||
| block.querySelectorAll('.ff-code-block--export').forEach(btn => { btn.hidden = showCode }) | ||
| toggleBtn.setAttribute('aria-pressed', String(showCode)) | ||
| toggleBtn.classList.toggle('active', showCode) | ||
| toggleBtn.blur() | ||
| return | ||
| } | ||
| const exportBtn = event.target.closest('.ff-code-block--export') | ||
| if (exportBtn) { | ||
| this.exportDiagram(exportBtn) | ||
| exportBtn.blur() | ||
| return | ||
| } | ||
| const copyBtn = event.target.closest('.ff-code-block--copy') || event.target.closest('.ff-table-block--copy') | ||
| if (!copyBtn) return | ||
|
|
||
|
|
@@ -265,6 +405,40 @@ export default { | |
| } | ||
| } | ||
|
|
||
| // The diagram takes its colours from these variables, so it follows the theme without being re-rendered | ||
| :deep(.ff-code-block--diagram) { | ||
| --pele-bg: var(--ff-color-bg-surface); | ||
| --pele-fg: var(--ff-color-text); | ||
| --pele-muted: var(--ff-color-text-subtle); | ||
| --pele-line: var(--ff-color-text-subtle); | ||
| --pele-surface: var(--ff-color-bg-surface-raised); | ||
| --pele-surface-alt: var(--ff-color-bg-surface-raised); | ||
| --pele-border: var(--ff-color-accent); | ||
| --pele-accent: var(--ff-color-accent); | ||
|
|
||
| padding: 1rem; | ||
| overflow-x: auto; | ||
| background: var(--ff-color-bg-surface); | ||
|
|
||
| svg { | ||
| display: block; | ||
| max-width: 100%; | ||
| height: auto; | ||
| margin: 0 auto; | ||
| } | ||
| } | ||
|
|
||
| :deep(.ff-code-block--diagram-actions) { | ||
| display: inline-flex; | ||
| gap: 0.5rem; | ||
| margin: 0 auto 0 0.5rem; | ||
|
|
||
| // .ff-btn sets display, which would override the hidden attribute | ||
| [hidden] { | ||
| display: none; | ||
| } | ||
| } | ||
|
|
||
| :deep(.ff-code-block--header) { | ||
| display: flex; | ||
| align-items: center; | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import DOMPurify from 'dompurify' | ||
|
|
||
| // The CSS variables the diagram takes its colours from | ||
| export const THEME_VARIABLES = [ | ||
| '--pele-bg', | ||
| '--pele-fg', | ||
| '--pele-muted', | ||
| '--pele-line', | ||
| '--pele-surface', | ||
| '--pele-surface-alt', | ||
| '--pele-border', | ||
| '--pele-accent' | ||
| ] | ||
|
|
||
| // The SVG is rendered by the Expert and arrives with the message, so it is untrusted markup. | ||
| // Ids are dropped because nothing in the SVG refers to them and they repeat across the diagrams on a page. | ||
| export function sanitizeDiagram (svg) { | ||
| return DOMPurify.sanitize(svg, { USE_PROFILES: { svg: true, svgFilters: true }, FORBID_ATTR: ['id'] }) | ||
| } | ||
|
|
||
| function parseSvg (svg) { | ||
| const doc = new DOMParser().parseFromString(svg, 'image/svg+xml') | ||
| return doc.documentElement | ||
| } | ||
|
|
||
| // Returns the diagram as standalone SVG markup with explicit pixel dimensions. The theme | ||
| // variables are written onto the SVG, as outside the page it no longer inherits them. | ||
| export function serializeSvg (svg, theme = {}) { | ||
| const el = parseSvg(svg) | ||
| const [, , width, height] = (el.getAttribute('viewBox') || '').split(/\s+/).map(Number) | ||
| if (width && height) { | ||
| el.setAttribute('width', width) | ||
| el.setAttribute('height', height) | ||
| } | ||
| el.style.maxWidth = '' | ||
| for (const [name, value] of Object.entries(theme)) { | ||
| el.style.setProperty(name, value) | ||
| } | ||
| el.setAttribute('xmlns', 'http://www.w3.org/2000/svg') | ||
| return new XMLSerializer().serializeToString(el) | ||
| } | ||
|
|
||
| export async function svgToPngBlob (svg, { scale = 2, theme = {} } = {}) { | ||
| const standalone = serializeSvg(svg, theme) | ||
| const el = parseSvg(standalone) | ||
| const width = Number(el.getAttribute('width')) | ||
| const height = Number(el.getAttribute('height')) | ||
| const image = new Image() | ||
| await new Promise((resolve, reject) => { | ||
| image.onload = resolve | ||
| image.onerror = reject | ||
| image.src = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(standalone) | ||
| }) | ||
| const canvas = document.createElement('canvas') | ||
| canvas.width = Math.ceil(width * scale) | ||
| canvas.height = Math.ceil(height * scale) | ||
| const ctx = canvas.getContext('2d') | ||
| ctx.fillStyle = theme['--pele-bg'] || '#ffffff' | ||
| ctx.fillRect(0, 0, canvas.width, canvas.height) | ||
| ctx.drawImage(image, 0, 0, canvas.width, canvas.height) | ||
| return new Promise((resolve, reject) => { | ||
| canvas.toBlob(blob => blob ? resolve(blob) : reject(new Error('PNG export failed')), 'image/png') | ||
| }) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.

There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
So while streaming,
:key="text"rebuilds the whole content every tick andupdated()re-injects the diagrams each time, so the diagram buttons don't work until streaming ends. None of my clicks on Code / export registered.Could each diagram be its own Vue component instead of going through
v-html? Then it wouldn't rebuild every tick, and we could useff-button/ff-kebab-menu, which would also fix the export buttons wrapping in the drawer on smaller screens.