Diff Viewer
Read-only line diff of two texts, unified or side by side, with folded unchanged lines and word highlights.
c2-diff-viewer shows what changed between two texts, for reviewing a change before it is applied: a configuration, a generated file, a document revision. Set original and modified and the element computes the diff itself (Myers’ algorithm on lines, then on the words of each changed line pair), so the words that changed inside a line are marked too. mode="unified" (the default) draws one column with removed lines before added ones; mode="split" puts the two texts side by side, and draws the unified layout while the element is narrower than --c2-diff-viewer--split-min-width. Unchanged runs longer than the context lines kept around each change (3 by default) fold into a “Show N unchanged lines” row; opening one fires fold-expand, and expandAll() opens them all. line-numbers adds both line numbers, original-label and modified-label add a header with the counts of added and removed lines, and label names the diff for screen readers. The counts are also the stats property and the :state(changed) custom state.
A last line without a final line break differs from the same line with one, as in git diff, and says so. There is no syntax highlighting and no editing; diffLines(original, modified) is exported for code that needs the diff itself.
Import
import '@c2n/components/diff-viewer'Usage
| Original line | Modified line | Change | Text |
|---|---|---|---|
| 1 | 1 | >name: shop | |
| 2 | 2 | >start_url: https://shop.example/list | |
| 3 | 3 | >selectors: | |
| 4 | > | Removed | item: .card |
| 4 | >Added | item: article.product | |
| 5 | 5 | >price: .price | |
| 6 | >Added | title: h2 | |
| 6 | 7 | >pagination: next |
| Change | Before | Change | After |
|---|---|---|---|
| Removed | timeout: 30 | >Added | timeout: 45 | >
| retries: 2 | >retries: 2 | >||
| Removed | user_agent: my-plan/1.0No newline at end of file | >Added | user_agent: my-plan/1.1No newline at end of file | >
No changes
| Change | Text |
|---|---|
Set the texts as properties when they come from the app, and read the counts back:
const viewer = document.querySelector('c2-diff-viewer')
viewer.original = await loadPlan('live')
viewer.modified = await loadPlan('repaired')
await viewer.updateComplete
publishButton.disabled = viewer.stats.additions + viewer.stats.deletions === 0
viewer.addEventListener('fold-expand', (event) => console.log(event.detail)) // { originalStart, modifiedStart, count }