Diff View
Two texts compared a line at a time: what the second took out of the first, what it put in, and what it wrote otherwise, side by side in a wide view and in one column in a narrow one, the two columns scrolling as one.
import com.pantrixui.components.data.diffview.PantrixDiffView
- Lines. A line taken out is on the danger role's soft fill with a − before it; one put in on the success role's, with a +. A line written otherwise stands across from the line it was; its changed words are on a stronger fill of the same role. Across from a line one text alone has, the room is crossed with thin lines.
- Layout.
layoutsets the texts out by the view's own width, at the window's breakpoints: side by side from Medium, in one column below it (DiffLayout.Adaptive);SideBySideandUnifiedalways set them out so. In one column a change's lines taken out come first, and the lines it put in under them. - Folded lines.
contextunchanged lines, three by default, stay before and after each change; the rest fold into one row that says how many there are, and a press opens it.context = nullfolds nothing. - Numbers and colours. Each line carries its number in its own text, both numbers in one column.
highlightercolours the unchanged lines as a code editor's does; the changed lines are written in the one colour that reads on their fill. - Long lines. A line too long for its column goes on under itself, and the row takes the taller side's height.
softWrap = falsescrolls the two columns sideways together. - Changes.
rememberDiffViewStateis the view's state:changesgives the changes, each with the lines of both texts it takes;scrollToChange(i)brings a change into view the shorter way and shows it with a bar in the primary colour at its start (shownChange). With the focus in the view, Alt and the down arrow go to the next change, Alt and the up arrow to the one before, and a screen reader is told which it is. - Titles.
beforeTitleandafterTitlewrite the two texts' names over their columns; at the row's end stands how many lines were put in and taken out. - Comparison. The difference is found by
diffLines, Myers' shortest edit: texts of a few thousand lines at once, longer ones away from the main thread. An app gives its own comparison, of what a document means for example, as a list ofDiffLines.ignoreWhitespacecounts lines that differ only in their spaces as the same. - Selecting. What the lines say can be selected and copied by the system's own means; the numbers and the signs are not selected.
- Automation. With
tagKeythe view isDiffView_<tagKey>, a rowRow_<line>, in one column a changed line's two sidesRow_<line>_beforeandRow_<line>_after, a row of folded linesFold_<line>, and the titlesHeader_titles. A folded row opened is reported asexpand, a change gone to by its keys aschange. - Style and colour.
DiffViewStylegives the room, the edge and the bar,DiffViewColorsthe fills, the writing and the code's colours; what is not given stays the theme's.
Examples
Two versions of a file
Two versions of a settings file, with their names. The age line is written otherwise, city is taken out and team put in; the rest is the same. The unchanged lines are coloured by the demo's JSON highlighter. A wide view sets them side by side, a narrow one in one column.
PantrixDiffView(
before = SAVED,
after = EDITED,
highlighter = JsonHighlighter,
beforeTitle = "saved.json",
afterTitle = "edited.json",
tagKey = "versions"
)
private val SAVED =
"""
{
"name": "Ada",
"age": 36,
"city": "London",
"active": true
}
""".trimIndent()
private val EDITED =
"""
{
"name": "Ada",
"age": 37,
"active": true,
"team": "engines"
}
""".trimIndent()
One column
The same two versions in one column: each change's lines taken out first, the lines it put in under them; every line with both texts' numbers.
PantrixDiffView(before = SAVED, after = EDITED, layout = DiffLayout.Unified, tagKey = "unified")
private val SAVED =
"""
{
"name": "Ada",
"age": 36,
"city": "London",
"active": true
}
""".trimIndent()
private val EDITED =
"""
{
"name": "Ada",
"age": 37,
"active": true,
"team": "engines"
}
""".trimIndent()
Going to the changes
A long text in a room given a height: three changes in sixty lines. Three lines stay before and after each change, and those between fold into an "Unchanged lines" row; press one and it opens.
The buttons come from the state's changes list: press one and the view scrolls to that change the shorter way and shows it with a bar at its start. With the focus in the view, Alt and the down arrow go to the next one too.
val report = LocalExampleEvents.current
val compare = rememberDiffViewState()
val scope = rememberCoroutineScope()
Column(verticalArrangement = Arrangement.spacedBy(PantrixTheme.spacing.sm)) {
FlowRow(horizontalArrangement = Arrangement.spacedBy(PantrixTheme.spacing.sm)) {
compare.changes.forEachIndexed { at, change: DiffChange ->
PantrixButton(
text = "Line ${change.afterLines.first}",
onClick = {
scope.launch { compare.scrollToChange(at) }
report("Change ${at + 1}: +${change.added} −${change.removed}")
},
variant = if (compare.shownChange == at) ButtonVariant.Solid else ButtonVariant.Outline,
size = ButtonSize.Small,
tagKey = "change_$at"
)
}
}
PantrixDiffView(
before = LOG_BEFORE,
after = LOG_AFTER,
modifier = Modifier.height(320.dp),
state = compare,
tagKey = "log"
)
}
private val LOG_BEFORE = List(60) { "12:${it.toString().padStart(2, '0')} job ${it + 1} done" }.joinToString("\n")
private val LOG_AFTER = LOG_BEFORE.lines().toMutableList().apply {
set(9, "12:09 job 10 failed")
removeAt(30)
add(50, "12:50 job 51 retried")
}.joinToString("\n")
The app's own comparison
The app's own comparison: an app that compares what two documents mean gives the lines as DiffLines. Here the order of the keys is no difference; only the value of total changed and note was put in.
val lines = remember {
listOf(
DiffLine(DiffKind.Unchanged, "\"id\": 4821,", "\"id\": 4821,", beforeNumber = 2, afterNumber = 3),
DiffLine(DiffKind.Changed, "\"total\": 249.90,", "\"total\": 259.90,", beforeNumber = 3, afterNumber = 2),
DiffLine(DiffKind.Added, before = null, after = "\"note\": \"gift\"", afterNumber = 4)
)
}
PantrixDiffView(lines = lines, layout = DiffLayout.SideBySide, context = null, tagKey = "meaning")
Spaces and lines that do not wrap
With ignoreWhitespace on, lines whose indent alone changed count as the same, but are shown as written. With softWrap off, long lines stay on one line and the two columns scroll sideways together. diffLines makes the same comparison outside the view: here to say how many lines changed.
var ignore by rememberSaveable { mutableStateOf(true) }
var wrap by rememberSaveable { mutableStateOf(false) }
val changed = remember(ignore) {
diffLines(CODE_BEFORE, CODE_AFTER, ignoreWhitespace = ignore).count { it.kind != DiffKind.Unchanged }
}
Column(verticalArrangement = Arrangement.spacedBy(PantrixTheme.spacing.sm)) {
PantrixSwitchButton(
checked = ignore,
onCheckedChange = { ignore = it },
label = "Ignore spaces: $changed changed lines",
tagKey = "ignore"
)
PantrixSwitchButton(
checked = wrap,
onCheckedChange = { wrap = it },
label = "Wrap the lines",
tagKey = "wrap"
)
PantrixDiffView(
before = CODE_BEFORE,
after = CODE_AFTER,
layout = DiffLayout.SideBySide,
ignoreWhitespace = ignore,
softWrap = wrap,
tagKey = "code"
)
}
private val CODE_BEFORE =
"""
fun total(items: List<Item>): Double {
return items.sumOf { it.price * it.count }
}
""".trimIndent()
private val CODE_AFTER =
"""
fun total(items: List<Item>): Double {
return items.sumOf { it.price * it.count }
}
fun totalWithTax(items: List<Item>, rate: Double): Double = total(items) * (1 + rate)
""".trimIndent()
Its own colours and style
Its own colours and style: the lines taken out and put in in the app's colours, the bar of the change shown thicker, and no line numbers.
val colors = PantrixTheme.colors
PantrixDiffView(
before = SAVED,
after = EDITED,
layout = DiffLayout.Unified,
lineNumbers = false,
style = DiffViewStyle(barWidth = 4.dp, gutterGap = 12.dp),
colors = DiffViewColors(removed = colors.warning.container, added = colors.info.container),
tagKey = "own"
)
private val SAVED =
"""
{
"name": "Ada",
"age": 36,
"city": "London",
"active": true
}
""".trimIndent()
private val EDITED =
"""
{
"name": "Ada",
"age": 37,
"active": true,
"team": "engines"
}
""".trimIndent()
API
before
Two texts compared a line at a time: what the second took out of the first, what it put in, and what it wrote otherwise, side by side in a wide view and in one column in a narrow one, the two columns scrolling as one.
| Parameter | Type | Default | What it is |
|---|---|---|---|
before | String | the text before, a line to each line feed. | |
after | String | the text after. | |
modifier | Modifier | Modifier | the view's modifier. A height given here is the room the rows scroll in. |
layout | DiffLayout | DiffLayout.Adaptive | how the two texts are set out: side by side or in one column by the view's width, or always one way. |
context | Int? | 3 | how many unchanged lines stand before and after each change before the rest fold: three by default, and none folds where it is null. |
ignoreWhitespace | Boolean | false | whether two lines that differ only in their spaces are the same: each is shown as written. |
softWrap | Boolean | true | whether a line too long for its column goes on under itself. False keeps every line on one line, and the columns scroll sideways together. |
lineNumbers | Boolean | true | whether each line carries its number in its text, before its sign. |
selectable | Boolean | true | whether what the lines say can be selected, by a pointer drawn over it or a finger held on it, and copied by the system's own means. The numbers and the signs are not selected. |
highlighter | CodeHighlighter<*>? | null | what colours the tokens of the unchanged lines, as a code editor's does: none by default, and the lines are written in the text's colour. |
beforeTitle | String? | null | the name of the text before, over its column: a file's name, a version. With afterTitle it makes a row of titles over the rows, with how many lines were put in and taken out at its end; with neither the view has no such row. |
afterTitle | String? | null | the name of the text after, over its column. |
state | DiffViewState | rememberDiffViewState() | the changes, the one shown, and where the rows are scrolled to. |
style | DiffViewStyle? | null | this call's own style: over every enclosing one and under the density. Only the fields it sets change, on every platform. |
colors | DiffViewColors? | null | this view's own colours, where they are not the theme's: the ones set here, with the theme's for the rest. |
tagKey | String? | null | the view's automation key: the view is DiffView_<tagKey>, a row of lines in it DiffView_<tagKey>.Row_<line> with the line's place among the comparison's lines, in one column Row_<line>_before and Row_<line>_after for a changed line's two sides, a row of folded lines DiffView_<tagKey>.Fold_<line> with the place of its first line, and the row of titles DiffView_<tagKey>.Header_titles. A row opened is reported as a DiffView event, expand, with how many lines it held; a change gone to by its keys as change, with its place. Nothing of the texts is reported. |
lines
PantrixDiffView for a comparison its caller made: what a document means compared rather than its lines, or diffLines' lines made away from the screen.
| Parameter | Type | Default | What it is |
|---|---|---|---|
lines | List<DiffLine> | the comparison's lines, in the order the texts have them; the changes are the runs of lines that are not DiffKind.Unchanged. | |
modifier | Modifier | Modifier | the view's modifier. A height given here is the room the rows scroll in. |
layout | DiffLayout | DiffLayout.Adaptive | how the two texts are set out. |
context | Int? | 3 | how many unchanged lines stand before and after each change before the rest fold; null folds none. |
softWrap | Boolean | true | whether a line too long for its column goes on under itself. |
lineNumbers | Boolean | true | whether each line carries its number in its text. |
selectable | Boolean | true | whether what the lines say can be selected and copied by the system's own means. |
highlighter | CodeHighlighter<*>? | null | what colours the tokens of the unchanged lines; it reads each text's lines in their order. |
beforeTitle | String? | null | the name of the text before, over its column. |
afterTitle | String? | null | the name of the text after, over its column. |
state | DiffViewState | rememberDiffViewState() | the changes, the one shown, and where the rows are scrolled to. |
style | DiffViewStyle? | null | this call's own style: over every enclosing one and under the density. |
colors | DiffViewColors? | null | this view's own colours, where they are not the theme's. |
tagKey | String? | null | the view's automation key, as the other overload has it. |
DiffViewStyle
PantrixDiffView's geometry: the room around its rows and in them, the room before the lines where they are numbered, the edge, the bar of the change shown, and the row of the titles.
| Parameter | Type | Default | What it is |
|---|---|---|---|
shape | ShapeSpec | ShapeSpec.Unspecified | The corners of the view: a step of the brand's shape scale, or a fixed shape. |
horizontalPadding | Dp | Dp.Unspecified | The room between a column's sides and what it holds; the fills of the changes are drawn across it, to the sides. |
verticalPadding | Dp | Dp.Unspecified | The room over the first row and under the last, and over and under the titles. |
linePadding | Dp | Dp.Unspecified | The room over and under the words of each line. |
gutterGap | Dp | Dp.Unspecified | Between a line's number, its sign and its words. |
borderWidth | Dp | Dp.Unspecified | The width of the edge around the view, of the line between its two columns and of the line under its titles. Zero draws none. |
barWidth | Dp | Dp.Unspecified | The width of the bar down the start of the change shown. Zero draws none. |
iconSize | Dp | Dp.Unspecified | The width and height of the icon of a row of folded lines. |
DiffViewColors
What a PantrixDiffView is painted with, for a view that does not take the theme's colours: a colour that is set is used, and one that is left out stays the theme's.
| Parameter | Type | Default | What it is |
|---|---|---|---|
container | Color | Color.Unspecified | The fill behind the rows: the theme's surface. |
text | Color | Color.Unspecified | What no token colours. The theme's textPrimary. |
comment | Color | Color.Unspecified | A comment, which is slanted too. The theme's textSecondary. |
keyword | Color | Color.Unspecified | A word of the language. The theme's primary role. |
type | Color | Color.Unspecified | The name of a type. The theme's info role. |
string | Color | Color.Unspecified | A string. The theme's success role. |
number | Color | Color.Unspecified | A number. The theme's warning role. |
punctuation | Color | Color.Unspecified | Brackets, commas and semicolons. The theme's textSecondary. |
annotation | Color | Color.Unspecified | A name that says something about what follows it. The theme's danger role. |
property | Color | Color.Unspecified | The name of a member or a setting. The colour of a type where it is not set. |
tag | Color | Color.Unspecified | The name of an element of a markup. The colour of a keyword where it is not set. |
lineNumber | Color | Color.Unspecified | The line numbers and the signs of the unchanged lines, the titles' summary and the scroll bars. The theme's textSecondary. |
border | Color | Color.Unspecified | The edge around the view, the line between its two columns and the line under its titles. The theme's divider. |
removed | Color | Color.Unspecified | The fill of a line the text after took out: the danger role's container. |
removedContent | Color | Color.Unspecified | What is written on removed: the danger role's onContainer. |
removedWord | Color | Color.Unspecified | What is laid behind the words a changed line took out: a stronger share of the danger role, or on a removed of the caller's own a share of what is written there. |
added | Color | Color.Unspecified | The fill of a line the text after put in: the success role's container. |
addedContent | Color | Color.Unspecified | What is written on added: the success role's onContainer. |
addedWord | Color | Color.Unspecified | What is laid behind the words a changed line put in: a stronger share of the success role, or on an added of the caller's own a share of what is written there. |
gap | Color | Color.Unspecified | The lines across the side of a row that one text alone has a line on: the theme's divider. |
fold | Color | Color.Unspecified | The fill of a row of folded lines: the theme's background, a step from the view's surface. |
foldContent | Color | Color.Unspecified | What a row of folded lines says, and its icon: the theme's textSecondary. |
shown | Color | Color.Unspecified | The bar down the start of the change shown: the primary role's colour. |
Accessibility
- Screen reader. After a changed line's words it is told which side it is and its number: "Removed, line 4". An unchanged line is read once. The titles' summary is read in the theme's words.