logo svelte /diff v0.4.3

SvelteDiff API

The package exports the component as both the default export and a named export.

<script lang="ts">
    import SvelteDiff from '@humanspeak/svelte-diff'
    // or: import { SvelteDiff } from '@humanspeak/svelte-diff'
</script>
<script lang="ts">
    import SvelteDiff from '@humanspeak/svelte-diff'
    // or: import { SvelteDiff } from '@humanspeak/svelte-diff'
</script>

Props

PropTypeDefaultPurpose
originalTextstringrequiredThe before/source text
modifiedTextstringrequiredThe after/target text
diffModeSvelteDiffMode'character''character', 'word', or 'line'; word/line skip cleanup
expectedPatternsbooleantrueEnable named capture templates; false compares exact literal source without parsing
timeoutnumber1Maximum diff computation time in seconds; 0 is unlimited
cleanupSemanticbooleanfalseCharacter only: optimize edit boundaries for human readability
cleanupEfficiencynumber4Character-only edit cost for efficiency cleanup; 0 disables it
compactbooleantrueRender unstyled equal text without wrapper spans; false restores legacy equal spans
onProcessingfunction—Receive timing, raw tuples, and optional captures
rendererClassesRendererClasses{}Classes for built-in segment spans
renderersPartial<Renderers>{}Snippet map for individual segment types
removeSnippet<[string]>—Direct child snippet for removed text
insertSnippet<[string]>—Direct child snippet for inserted text
equalSnippet<[string]>—Direct child snippet for unchanged text
expectedSnippet<[string, string]>—Direct child snippet for expected values
lineBreakSnippet<[]>—Direct child snippet between lines

Cleanup precedence

In character mode, the component computes a raw diff, then runs at most one cleanup pass:

  1. If cleanupSemantic is true, semantic cleanup runs.
  2. Otherwise, if cleanupEfficiency > 0, efficiency cleanup runs with that value as the edit cost.
  3. Otherwise, the raw diff is rendered.

Renderer precedence

Resolution happens independently for every segment type:

  1. A direct child snippet such as {#snippet insert(text)}
  2. The matching property in renderers
  3. The built-in fallback

For unchanged text, the default compact fallback emits text directly when no equal class or renderer is configured. Set compact={false} to restore the legacy equal <span>. Removed, inserted, expected, and customized equal segments retain their normal elements.

That means you can override one type and leave all others on their defaults.

<SvelteDiff {originalText} {modifiedText}>
    {#snippet insert(text: string)}
        <ins class="addition">+ {text}</ins>
    {/snippet}
</SvelteDiff>
<SvelteDiff {originalText} {modifiedText}>
    {#snippet insert(text: string)}
        <ins class="addition">+ {text}</ins>
    {/snippet}
</SvelteDiff>

onProcessing

The callback runs after computation and cleanup.

<script lang="ts">
    import type {
        SvelteDiffTiming,
        SvelteDiffTuple
    } from '@humanspeak/svelte-diff'

    function handleProcessing(
        timing: SvelteDiffTiming,
        diffs: SvelteDiffTuple[],
        captures?: Record<string, string>
    ) {
        console.log(timing.main, timing.cleanup, timing.total)
        console.log(diffs, captures)
    }
</script>

<SvelteDiff {originalText} {modifiedText} onProcessing={handleProcessing} />
<script lang="ts">
    import type {
        SvelteDiffTiming,
        SvelteDiffTuple
    } from '@humanspeak/svelte-diff'

    function handleProcessing(
        timing: SvelteDiffTiming,
        diffs: SvelteDiffTuple[],
        captures?: Record<string, string>
    ) {
        console.log(timing.main, timing.cleanup, timing.total)
        console.log(diffs, captures)
    }
</script>

<SvelteDiff {originalText} {modifiedText} onProcessing={handleProcessing} />

Timing values are milliseconds measured with performance.now().

Literal source

expectedPatterns defaults to true on the component. Set it to false when comparing source containing named regex groups:

<SvelteDiff originalText={before} modifiedText={after} expectedPatterns={false} />
<SvelteDiff originalText={before} modifiedText={after} expectedPatterns={false} />

Literal mode bypasses parsing, substitution, mismatch placeholders, and capture tagging. Raw tuples reconstruct both exact input strings. Changing this prop recomputes the comparison and clears stale capture metadata. Initial literal markup is rendered during SSR; callbacks remain client-only.

The synchronous computeDiff helper defaults to expectedPatterns: false. Its other defaults match the component. See Types and Exports for its options and result within a Svelte-aware toolchain.

Expected patterns

If originalText contains named capture groups, the component tries to match those regions in modifiedText and renders successful matches as expected instead of additions/removals.

<SvelteDiff
    originalText={'Release (?<version>v\\d+\\.\\d+\\.\\d+)'}
    modifiedText="Release v2.4.1"
/>
<SvelteDiff
    originalText={'Release (?<version>v\\d+\\.\\d+\\.\\d+)'}
    modifiedText="Release v2.4.1"
/>

The group name is passed to the expected snippet and its matched value appears in the callback’s captures object.

Deprecated aliases

SvelteDiffMatchPatch and the SvelteDiffMatchPatch* type names remain available for compatibility. New code should use SvelteDiff and the shorter SvelteDiff* types.

Mode and capture semantics

diffMode defaults to character; word and line skip both cleanup passes regardless of their props. timing.cleanup is exactly zero in token modes. See Diff Modes for token rules, Unicode limitations, and complete examples.

Capture extraction still precedes tokenization. Raw callback tuples reconstruct the resolved source (or cleaned placeholders on mismatch), and the exact modified text. Capture tagging may split displayed tokens, and newline rendering may split a tuple across snippet calls. For Release (?<version>v\\d+) and Release v2 ready, line mode removes Release v2, inserts the full actual line, and annotates v2 on the target side. The deleted captured value remains visible.

Mode changes recompute immediately; callback-only changes reuse the tuple array. Computation runs during SSR and callback delivery runs on the client. The token deadline includes preparation and decoding; timeout or more than 65,535 distinct tokens can return a full replacement. See performance.