Pantrix UI

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

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.

ParameterTypeDefaultWhat it is
beforeStringthe text before, a line to each line feed.
afterStringthe text after.
modifierModifierModifierthe view's modifier. A height given here is the room the rows scroll in.
layoutDiffLayoutDiffLayout.Adaptivehow the two texts are set out: side by side or in one column by the view's width, or always one way.
contextInt?3how many unchanged lines stand before and after each change before the rest fold: three by default, and none folds where it is null.
ignoreWhitespaceBooleanfalsewhether two lines that differ only in their spaces are the same: each is shown as written.
softWrapBooleantruewhether a line too long for its column goes on under itself. False keeps every line on one line, and the columns scroll sideways together.
lineNumbersBooleantruewhether each line carries its number in its text, before its sign.
selectableBooleantruewhether 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.
highlighterCodeHighlighter<*>?nullwhat 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.
beforeTitleString?nullthe 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.
afterTitleString?nullthe name of the text after, over its column.
stateDiffViewStaterememberDiffViewState()the changes, the one shown, and where the rows are scrolled to.
styleDiffViewStyle?nullthis call's own style: over every enclosing one and under the density. Only the fields it sets change, on every platform.
colorsDiffViewColors?nullthis view's own colours, where they are not the theme's: the ones set here, with the theme's for the rest.
tagKeyString?nullthe 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.

ParameterTypeDefaultWhat it is
linesList<DiffLine>the comparison's lines, in the order the texts have them; the changes are the runs of lines that are not DiffKind.Unchanged.
modifierModifierModifierthe view's modifier. A height given here is the room the rows scroll in.
layoutDiffLayoutDiffLayout.Adaptivehow the two texts are set out.
contextInt?3how many unchanged lines stand before and after each change before the rest fold; null folds none.
softWrapBooleantruewhether a line too long for its column goes on under itself.
lineNumbersBooleantruewhether each line carries its number in its text.
selectableBooleantruewhether what the lines say can be selected and copied by the system's own means.
highlighterCodeHighlighter<*>?nullwhat colours the tokens of the unchanged lines; it reads each text's lines in their order.
beforeTitleString?nullthe name of the text before, over its column.
afterTitleString?nullthe name of the text after, over its column.
stateDiffViewStaterememberDiffViewState()the changes, the one shown, and where the rows are scrolled to.
styleDiffViewStyle?nullthis call's own style: over every enclosing one and under the density.
colorsDiffViewColors?nullthis view's own colours, where they are not the theme's.
tagKeyString?nullthe 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.

ParameterTypeDefaultWhat it is
shapeShapeSpecShapeSpec.UnspecifiedThe corners of the view: a step of the brand's shape scale, or a fixed shape.
horizontalPaddingDpDp.UnspecifiedThe room between a column's sides and what it holds; the fills of the changes are drawn across it, to the sides.
verticalPaddingDpDp.UnspecifiedThe room over the first row and under the last, and over and under the titles.
linePaddingDpDp.UnspecifiedThe room over and under the words of each line.
gutterGapDpDp.UnspecifiedBetween a line's number, its sign and its words.
borderWidthDpDp.UnspecifiedThe width of the edge around the view, of the line between its two columns and of the line under its titles. Zero draws none.
barWidthDpDp.UnspecifiedThe width of the bar down the start of the change shown. Zero draws none.
iconSizeDpDp.UnspecifiedThe 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.

ParameterTypeDefaultWhat it is
containerColorColor.UnspecifiedThe fill behind the rows: the theme's surface.
textColorColor.UnspecifiedWhat no token colours. The theme's textPrimary.
commentColorColor.UnspecifiedA comment, which is slanted too. The theme's textSecondary.
keywordColorColor.UnspecifiedA word of the language. The theme's primary role.
typeColorColor.UnspecifiedThe name of a type. The theme's info role.
stringColorColor.UnspecifiedA string. The theme's success role.
numberColorColor.UnspecifiedA number. The theme's warning role.
punctuationColorColor.UnspecifiedBrackets, commas and semicolons. The theme's textSecondary.
annotationColorColor.UnspecifiedA name that says something about what follows it. The theme's danger role.
propertyColorColor.UnspecifiedThe name of a member or a setting. The colour of a type where it is not set.
tagColorColor.UnspecifiedThe name of an element of a markup. The colour of a keyword where it is not set.
lineNumberColorColor.UnspecifiedThe line numbers and the signs of the unchanged lines, the titles' summary and the scroll bars. The theme's textSecondary.
borderColorColor.UnspecifiedThe edge around the view, the line between its two columns and the line under its titles. The theme's divider.
removedColorColor.UnspecifiedThe fill of a line the text after took out: the danger role's container.
removedContentColorColor.UnspecifiedWhat is written on removed: the danger role's onContainer.
removedWordColorColor.UnspecifiedWhat 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.
addedColorColor.UnspecifiedThe fill of a line the text after put in: the success role's container.
addedContentColorColor.UnspecifiedWhat is written on added: the success role's onContainer.
addedWordColorColor.UnspecifiedWhat 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.
gapColorColor.UnspecifiedThe lines across the side of a row that one text alone has a line on: the theme's divider.
foldColorColor.UnspecifiedThe fill of a row of folded lines: the theme's background, a step from the view's surface.
foldContentColorColor.UnspecifiedWhat a row of folded lines says, and its icon: the theme's textSecondary.
shownColorColor.UnspecifiedThe bar down the start of the change shown: the primary role's colour.

Accessibility