From b2fb7af1fab57a82e956c6ad296ac45aa5214923 Mon Sep 17 00:00:00 2001 From: ZHAO Jinxiang Date: Mon, 6 Sep 2021 16:35:07 +0800 Subject: [PATCH] feat: allow custom compareMethod --- src/compute-lines.ts | 6 +++--- src/index.tsx | 5 +++-- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/compute-lines.ts b/src/compute-lines.ts index 53eb93ca..08e8df07 100644 --- a/src/compute-lines.ts +++ b/src/compute-lines.ts @@ -90,9 +90,9 @@ const constructLines = (value: string): string[] => { const computeDiff = ( oldValue: string, newValue: string, - compareMethod: string = DiffMethod.CHARS, + compareMethod: string | ((oldStr: string, newStr: string) => diff.Change[]) = DiffMethod.CHARS, ): ComputedDiffInformation => { - const diffArray: JsDiffChangeObject[] = jsDiff[compareMethod]( + const diffArray: JsDiffChangeObject[] = ((typeof compareMethod === 'string') ? jsDiff[compareMethod] : compareMethod)( oldValue, newValue, ); @@ -143,7 +143,7 @@ const computeLineInformation = ( oldString: string, newString: string, disableWordDiff: boolean = false, - compareMethod: string = DiffMethod.CHARS, + compareMethod: string | ((oldStr: string, newStr: string) => diff.Change[]) = DiffMethod.CHARS, linesOffset: number = 0, ): ComputedLineInformation => { const diffArray = diff.diffLines( diff --git a/src/index.tsx b/src/index.tsx index 3e012109..5e7ec169 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -1,6 +1,7 @@ import * as React from 'react'; import * as PropTypes from 'prop-types'; import cn from 'classnames'; +import { Change } from 'diff'; import { computeLineInformation, @@ -36,7 +37,7 @@ export interface ReactDiffViewerProps { // Enable/Disable word diff. disableWordDiff?: boolean; // JsDiff text diff method from https://github.com/kpdecker/jsdiff/tree/v4.0.1#api - compareMethod?: DiffMethod; + compareMethod?: DiffMethod | ((oldStr: string, newStr: string) => Change[]); // Number of unmodified lines surrounding each line diff. extraLinesSurroundingDiff?: number; // Show/hide line number. @@ -99,7 +100,7 @@ class DiffViewer extends React.Component< newValue: PropTypes.string.isRequired, splitView: PropTypes.bool, disableWordDiff: PropTypes.bool, - compareMethod: PropTypes.oneOf(Object.values(DiffMethod)), + compareMethod: PropTypes.oneOfType([PropTypes.oneOf(Object.values(DiffMethod)), PropTypes.func]), renderContent: PropTypes.func, onLineNumberClick: PropTypes.func, extraLinesSurroundingDiff: PropTypes.number,