Coder Social home page Coder Social logo

praneshr / react-diff-viewer Goto Github PK

View Code? Open in Web Editor NEW
1.3K 16.0 258.0 3.55 MB

A simple and beautiful text diff viewer component made with Diff and React.

Home Page: https://praneshravi.in/react-diff-viewer/

License: MIT License

TypeScript 96.26% JavaScript 3.14% Shell 0.59%
reactjs diff diff-viewer code-compare

react-diff-viewer's Introduction

React Diff Viewer


Build Status npm version GitHub license

A simple and beautiful text diff viewer component made with Diff and React.

Inspired from Github diff viewer, it includes features like split view, inline view, word diff, line highlight and more. It is highly customizable and it supports almost all languages.

Check here for v2.0

Install

yarn add react-diff-viewer

# or

npm i react-diff-viewer

Usage

import React, { PureComponent } from 'react';
import ReactDiffViewer from 'react-diff-viewer';

const oldCode = `
const a = 10
const b = 10
const c = () => console.log('foo')

if(a > 10) {
  console.log('bar')
}

console.log('done')
`;
const newCode = `
const a = 10
const boo = 10

if(a === 10) {
  console.log('bar')
}
`;

class Diff extends PureComponent {
  render = () => {
    return (
      <ReactDiffViewer oldValue={oldCode} newValue={newCode} splitView={true} />
    );
  };
}

Props

Prop Type Default Description
oldValue string '' Old value as string.
newValue string '' New value as string.
splitView boolean true Switch between unified and split view.
disableWordDiff boolean false Show and hide word diff in a diff line.
compareMethod DiffMethod DiffMethod.CHARS JsDiff text diff method used for diffing strings. Check out the guide to use different methods.
hideLineNumbers boolean false Show and hide line numbers.
renderContent function undefined Render Prop API to render code in the diff viewer. Helpful for syntax highlighting
onLineNumberClick function undefined Event handler for line number click. (lineId: string) => void
highlightLines array[string] [] List of lines to be highlighted. Works together with onLineNumberClick. Line number are prefixed with L and R for the left and right section of the diff viewer, respectively. For example, L-20 means 20th line in the left pane. To highlight a range of line numbers, pass the prefixed line number as an array. For example, [L-2, L-3, L-4, L-5] will highlight the lines 2-5 in the left pane.
showDiffOnly boolean true Shows only the diffed lines and folds the unchanged lines
extraLinesSurroundingDiff number 3 Number of extra unchanged lines surrounding the diff. Works along with showDiffOnly.
codeFoldMessageRenderer function Expand {number} of lines ... Render Prop API to render code fold message.
styles object {} To override style variables and styles. Learn more about overriding styles
useDarkTheme boolean true To enable/disable dark theme.
leftTitle string undefined Column title for left section of the diff in split view. This will be used as the only title in inline view.
rightTitle string undefined Column title for right section of the diff in split view. This will be ignored in inline view.
linesOffset number 0 Number to start count code lines from.

Instance Methods

resetCodeBlocks() - Resets the expanded code blocks to it's initial state. Return true on successful reset and false during unsuccessful reset.

Syntax Highlighting

Syntax highlighting is a bit tricky when combined with diff. Here, React Diff Viewer provides a simple render prop API to handle syntax highlighting. Use renderContent(content: string) => JSX.Element and your favorite syntax highlighting library to achieve this.

An example using Prism JS

// Load Prism CSS
<link
  href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.15.0/prism.min.css"
/>

// Load Prism JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.15.0/prism.min.js"></script>
import React, { PureComponent } from 'react';
import ReactDiffViewer from 'react-diff-viewer';

const oldCode = `
const a = 10
const b = 10
const c = () => console.log('foo')

if(a > 10) {
  console.log('bar')
}

console.log('done')
`;
const newCode = `
const a = 10
const boo = 10

if(a === 10) {
  console.log('bar')
}
`;

class Diff extends PureComponent {
  highlightSyntax = str => (
    <pre
      style={{ display: 'inline' }}
      dangerouslySetInnerHTML={{
        __html: Prism.highlight(str, Prism.languages.javascript),
      }}
    />
  );

  render = () => {
    return (
      <ReactDiffViewer
        oldValue={oldCode}
        newValue={newCode}
        splitView={true}
        renderContent={this.highlightSyntax}
      />
    );
  };
}

Text block diff comparison

Different styles of text block diffing are possible by using the enums corresponding to variou JsDiff methods (learn more). The supported methods are as follows.

enum DiffMethod {
  CHARS = 'diffChars',
  WORDS = 'diffWords',
  WORDS_WITH_SPACE = 'diffWordsWithSpace',
  LINES = 'diffLines',
  TRIMMED_LINES = 'diffTrimmedLines',
  SENTENCES = 'diffSentences',
  CSS = 'diffCss',
}
import React, { PureComponent } from 'react';
import ReactDiffViewer, { DiffMethod } from 'react-diff-viewer';

const oldCode = `
{
  "name": "Original name",
  "description": null
}
`;
const newCode = `
{
  "name": "My updated name",
  "description": "Brand new description",
  "status": "running"
}
`;

class Diff extends PureComponent {
  render = () => {
    return (
      <ReactDiffViewer
        oldValue={oldCode}
        newValue={newCode}
        compareMethod={DiffMethod.WORDS}
        splitView={true}
      />
    );
  };
}

Overriding Styles

React Diff Viewer uses emotion for styling. It also offers a simple way to override styles and style variables. You can supply different variables for both light and dark themes. Styles will be common for both themes.

Below are the default style variables and style object keys.

// Default variables and style keys

const defaultStyles = {
  variables: {
    light: {
      diffViewerBackground: '#fff',
      diffViewerColor: '#212529',
      addedBackground: '#e6ffed',
      addedColor: '#24292e',
      removedBackground: '#ffeef0',
      removedColor: '#24292e',
      wordAddedBackground: '#acf2bd',
      wordRemovedBackground: '#fdb8c0',
      addedGutterBackground: '#cdffd8',
      removedGutterBackground: '#ffdce0',
      gutterBackground: '#f7f7f7',
      gutterBackgroundDark: '#f3f1f1',
      highlightBackground: '#fffbdd',
      highlightGutterBackground: '#fff5b1',
      codeFoldGutterBackground: '#dbedff',
      codeFoldBackground: '#f1f8ff',
      emptyLineBackground: '#fafbfc',
      gutterColor: '#212529',
      addedGutterColor: '#212529',
      removedGutterColor: '#212529',
      codeFoldContentColor: '#212529',
      diffViewerTitleBackground: '#fafbfc',
      diffViewerTitleColor: '#212529',
      diffViewerTitleBorderColor: '#eee',
    },
    dark: {
      diffViewerBackground: '#2e303c',
      diffViewerColor: '#FFF',
      addedBackground: '#044B53',
      addedColor: 'white',
      removedBackground: '#632F34',
      removedColor: 'white',
      wordAddedBackground: '#055d67',
      wordRemovedBackground: '#7d383f',
      addedGutterBackground: '#034148',
      removedGutterBackground: '#632b30',
      gutterBackground: '#2c2f3a',
      gutterBackgroundDark: '#262933',
      highlightBackground: '#2a3967',
      highlightGutterBackground: '#2d4077',
      codeFoldGutterBackground: '#21232b',
      codeFoldBackground: '#262831',
      emptyLineBackground: '#363946',
      gutterColor: '#464c67',
      addedGutterColor: '#8c8c8c',
      removedGutterColor: '#8c8c8c',
      codeFoldContentColor: '#555a7b',
      diffViewerTitleBackground: '#2f323e',
      diffViewerTitleColor: '#555a7b',
      diffViewerTitleBorderColor: '#353846',
    }
  },
  diffContainer?: {}, // style object
  diffRemoved?: {}, // style object
  diffAdded?: {}, // style object
  marker?: {}, // style object
  emptyGutter?: {}, // style object
  highlightedLine?: {}, // style object
  lineNumber?: {}, // style object
  highlightedGutter?: {}, // style object
  contentText?: {}, // style object
  gutter?: {}, // style object
  line?: {}, // style object
  wordDiff?: {}, // style object
  wordAdded?: {}, // style object
  wordRemoved?: {}, // style object
  codeFoldGutter?: {}, // style object
  codeFold?: {}, // style object
  emptyLine?: {}, // style object
  content?: {}, // style object
  titleBlock?: {}, // style object
  splitView?: {}, // style object
}

To override any style, just pass the new style object to the styles prop. New style will be computed using Object.assign(default, override).

For keys other than variables, the value can either be an object or string interpolation.

import React, { PureComponent } from 'react';
import ReactDiffViewer from 'react-diff-viewer';

const oldCode = `
const a = 10
const b = 10
const c = () => console.log('foo')

if(a > 10) {
  console.log('bar')
}

console.log('done')
`;
const newCode = `
const a = 10
const boo = 10

if(a === 10) {
  console.log('bar')
}
`;

class Diff extends PureComponent {
  highlightSyntax = str => (
    <span
      style={{ display: 'inline' }}
      dangerouslySetInnerHTML={{
        __html: Prism.highlight(str, Prism.languages.javascript),
      }}
    />
  );

  render = () => {
    const newStyles = {
      variables: {
        dark: {
          highlightBackground: '#fefed5',
          highlightGutterBackground: '#ffcd3c',
        },
      },
      line: {
        padding: '10px 2px',
        '&:hover': {
          background: '#a26ea1',
        },
      },
    };

    return (
      <ReactDiffViewer
        styles={newStyles}
        oldValue={oldCode}
        newValue={newCode}
        splitView={true}
        renderContent={this.highlightSyntax}
      />
    );
  };
}

Local Development

yarn install
yarn build # or use yarn build:watch
yarn start:examples

Check package.json for more build scripts.

License

MIT

react-diff-viewer's People

Contributors

amandarice avatar dependabot[bot] avatar dimitropoulos avatar jamiewinder avatar mjesuele avatar orevron avatar praneshr avatar seveibar avatar sxn avatar xiaoxiaojx avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-diff-viewer's Issues

Error while using in project - You may need an appropriate loader to handle this file type

ERROR in ./compliance/app/compliance//react-diff-viewer/lib/styles.js
Module parse failed: /Users/nswarnka/Documents/Neeraj/Projects/mashup-project/mashup/ui-plugins/compliance/app/compliance/node_modules/react-diff-viewer/lib/styles.js Unexpected token (5:42)
You may need an appropriate loader to handle this file type.
| const emotion_1 = require("emotion");
| exports.default = (styleOverride) => {
| const { variables: overrideVariables, ...styles } = styleOverride;
| const variables = {
| ...{
@ ./compliance/app/compliance/
/react-diff-viewer/lib/index.js 7:17-36
@ ./compliance/app/compliance/src/components/ComplianceTabs/DiffViewer.js
@ ./compliance/app/compliance/src/components/ComplianceTabs/ComplianceTabs.js
@ ./compliance/app/compliance/src/components/complianceDetails/ComplianceDetails.js
@ ./compliance/app/compliance/src/graphViews/ComplianceView.js

explicitly add border-collapse so that it works out of the box without a css reset

Screenshot_20191023_080218

The above screenshot shows what this project looks like "out of the box" without a CSS Reset. The example page is using a reset: _reboot.scss which is giving table border-collapse: collapse;, when (on chrome) the user agent stylesheet specifies border-collapse: separate.

By simply adding this style manually to table it makes the difference between the tool working without a css reset being required and thus makes the project more portable.

Expand links get squished when line numbers are hidden, in unified (non-split) mode

Firstly thanks for this great library, amazing work :)

I believe there's a minor UI issue when using unified (non-split) view and hiding line numbers, where the expand links end up squished over to the right, like this:

2020-01-09 13_15_53-Audit - Octopus Deploy

The combination to get this to occur is as follows:

return <ReactDiffViewer ... splitView={false} hideLineNumbers={true} />;

Text diff result is unexpected when the oldvalue="1\n2\n3" and newvalue="1\n2"

[version: 1.1.0]

When I use mock value, oldvalue="1\n2\n3" and new value="1\n2", this diff viewer shows unexpected result, as follow picture.
image

The the third line on the left side should be texted "3" with "remove-line" style. In fact, "3" is texted on the right side, and the third line number is 2.

I'm confused. Is this a bug?

Evenly split page?

Apologies if this is documented somewhere, but I couldn't find it. I'm wondering if it is currently possible to give the document on the left and the document on the right even width on the page? Right now one doc often takes up 70-80% of the page width.

(Suggestion) Change TSConfig target option to something other than ESNext

Hey,

Would it be possible to target something other than esnext in the tsconfig.json configuration? With the current esnext setting, the code will include spread operators, which will cause at least Edge (version 41) to hang.

We've succesfully ran with a target setting of es6 and it seems to work on all "modern" browsers. I can provide a PR if that would help.

Column title in split view

I am showing a diff using split view, and at the top of both columns I'd like to set arbitrary text. I would like to show date values specifying the time the change was made, along with some other metadata. Is this currently possible? Thanks!

package in npm lack of build files.

I installed this package via npm i -S react-diff-viewer, And I used ReactDiffViewer in my code, but my app complained that react-diff-viewer not found like this.

Module not found: Can't resolve 'react-diff-viewer' in 'D:\code\electron\react-material-electron\src\pages'
Compiling...
Failed to compile.

I checked the node_modules/react-diff-viewer and found that no lib directory exits there.

So I think you should npm run build before publish to npm. Currently, I manual build this package and copy lib directory to node_modules/react-diff-viewer.

When oldValue and newValue is too long , diff viewer container will overflow page

I use this component to compare two similar json string, I set splitView=true.
But I when some fields is too long in json string, the diff viewer container will overflow page.
image
image

I try to set new styles, but not fix this problem.
I want both of oldValue and newValue display half of container, please help me to fix this problem , thx!

You may need an appropriate loader for this filetype

When I import this package in a Rails/React app I see this error

Uncaught Error: Module parse failed: Unexpected token (5:42)
You may need an appropriate loader to handle this file type.
| const emotion_1 = require("emotion");
| exports.default = (styleOverride) => {
|     const { variables: overrideVariables, ...styles } = styleOverride;
|     const variables = {
|         ...{
    at Object.<anonymous> (diff.js:1585)
    at __webpack_require__ (bootstrap 1f5c261f2a8d531ceb44:19)
    at Object.<anonymous> (index.js:7)
    at __webpack_require__ (bootstrap 1f5c261f2a8d531ceb44:19)
    at Object.<anonymous> (HighlightSummary.jsx:52)
    at __webpack_require__ (bootstrap 1f5c261f2a8d531ceb44:19)
    at Object.<anonymous> (checkPropTypes.js:59)
    at __webpack_require__ (bootstrap 1f5c261f2a8d531ceb44:19)
    at Object.<anonymous> (evaluate.jsx:4)
    at __webpack_require__ (bootstrap 1f5c261f2a8d531ceb44:19)

I'm not sure if there are some things I'm missing (webpack, babel, etc.)

You may need an appropriate loader to handle this file type

Hi Library Owners,

I am trying to use this react diff library in my react project -.
npm i react-diff-viewer

"dependencies": {
"react-diff-viewer": "^2.0.1"
}

Got added,

while building and using I am getting this error-

ERROR in ./compliance/app/compliance/~/react-diff-viewer/lib/styles.js
Module parse failed: /Users/nswarnka/Documents/Neeraj/Projects/mashup-project/mashup/ui-plugins/compliance/app/compliance/node_modules/react-diff-viewer/lib/styles.js Unexpected token (5:42)
You may need an appropriate loader to handle this file type.
| const emotion_1 = require("emotion");
| exports.default = (styleOverride) => {
| const { variables: overrideVariables, ...styles } = styleOverride;
| const variables = {
| ...{

.babelrc file -> In my babel i have "babel-preset-react", "babel-preset-stage-0" and "es2015" please check.


{
  "presets": [
    "babel-preset-react",
    ["es2015", {"modules": false}],
    "babel-preset-stage-0"
  ],
  "env": {
    "test": {
      "plugins": [
        "transform-es2015-modules-commonjs",
        "transform-decorators-legacy",
        "babel-plugin-react-html-attrs",
        "babel-plugin-transform-decorators-legacy",
        "babel-plugin-transform-class-properties"
      ]
    }
  }
}

package.json file ->

{
  "name": "compliance-ui-plugin",
  "version": "1.0.0",
  "scripts": {
    "build": "dpm build"
  },
  "author": "nsw",
  "license": "ISC",
  "devDependencies": {},
  "description": "Compliance UI Plugin",
  "dependencies": {
    "emotion": "^10.0.14",
    "react-diff-viewer": "^2.0.1"
  }
}

I got to know have to use Webpack loader to make it work. Could you please help me with this ? Thanks.

Asked the query in stack overflow as well ->
https://stackoverflow.com/questions/57653076/you-may-need-an-appropriate-loader-to-handle-this-file-type-while-using-external

Compile error using strictNullChecks: true on branch v2.0

Tried to use the alpha version in a project with the following tsconfig compile option
"strictNullChecks": true gives the following error

/node_modules/react-diff-viewer/lib/styles.d.ts
(3,5): Property 'diffContainer' of type 'string | undefined' is not assignable to string index type 'string'.

I did have a solution by changing the index signature of ReactDiffViewerStyles to [key: string]: string | undefined; - after changing this it compiles fine with the option.

Having trouble compiling this library in a typescript react project targetting es5

I'm not completely sure what's causing this, but I wonder if it's because this project seems to be targetting esnext? The current project I'm on has es5 as the target. The only thing that seems to fix the compilation error below is to set my target to esnext, but that introduces other errors in other files in my project.

./node_modules/react-diff-viewer/lib/styles.js
Module parse failed: Unexpected token (5:42)
You may need an appropriate loader to handle this file type.
| const emotion_1 = require("emotion");
| exports.default = (styleOverride) => {
|     const { variables: overrideVariables, ...styles } = styleOverride;
|     const variables = {
|         ...{

Issue with showDiffOnly option

Hello,

We would like to report an issue with “showDiffOnly” option.

The aforementioned option does not always work correctly and despite it is enabled, some lines that have no differences are still displayed. The corresponding lines are not highlighted, however, they shouldn’t be visible at all. Unfortunately, it was not possible to customize the library in order to resolve the case.

You may find more information on the attached screenshots. Also, the code that reproduces the issue may be found below.

We would highly appreciate if you provide us with more information regarding issue and fix it if possible.

Hope for your cooperation and look forward to hearing from you soon.

- Details:

"react-diff-viewer": "^2.0.1"

- oldValue:

<div class="test-class">
    <div class="test1-class">
	  <div class="test3-class">
    		<img src="test/src" alt="test alt" height="70px" style="padding: 10px 0 0 0;">
   	</div>  	
  	<p style="padding: 20px 0 10px 0; font-size: 14px; text-align: center; color: #000000; font-weight: 100"><b>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed.</b></p>
    <ul>
      <li style="text-align: left;font-weight: 100;font-size: 14px;padding: 0 0 5px 0;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt</li>
      <li style="text-align: left;font-weight: 100;font-size: 14px;padding: 0 0 5px 0;">Lorem ipsum dolor sit amet,</li>
    </ul>
    #if(test)
	  <div style="position: absolute; top: 80%; left: 22.5%">
		<button class="testing-class" data-toggle="modal" data-target="#tesing-target">lorem ipsum dolor</button>
	</div>      
</div>

- newValue:

<div class="test-class">
  <div class="test1-class">
    <div class="test3-class"><img src="test/src" alt="test alt" height="70px" style="padding: 10px 0 0 0;"></div>  	
    <p style="padding: 20px 0 10px 0; font-size: 14px; text-align: center; color: #000000; font-weight: 100"><b>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed.</b></p>
    <ul>
      <li style="text-align: left;font-weight: 100;font-size: 14px;padding: 0 0 5px 0;">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt</li>
      <li style="text-align: left;font-weight: 100;font-size: 14px;padding: 0 0 5px 0;">Lorem ipsum dolor sit amet,</li>
    </ul>
    #if(test)
    <div style="position: absolute; top: 75%; left: 22%">
      <button class="testing-class" data-toggle="modal" data-target="#tesing-target">lorem ipsum dolor
    </button>
  </div>      
</div>

showDiffOnly disabled
all-code

showDiffOnly enabled
diff-only

Diff View not displaying subsequent lines when a change is made to the first line.

Hi praneshr,
Thank you for developing this tool! This will be extremely useful for what I am trying to use it for. That being said, I have come across a bug which I hope can be resolved with ease.

What I am trying to accomplish:

  • I have a textarea that will be pre-populated with some text.
  • A user will make changes in this textarea and then review their changes using 'react-diff-viewer'

The bug I have come across:

  • When line 1 has been modified, the diff viewer will NOT display the proceeding lines of the textarea.
  • When line 1 is not modified, the diff viewer WILL display the proceeding lines of the textarea.

I have attached screenshots illustrating what it happening.

Step 1 (Initial Content):
Screen Shot 2019-10-29 at 10 42 56 AM

Step 2 (Add Content):
Screen Shot 2019-10-29 at 10 43 07 AM

Step 3 (Review Diff):
Screen Shot 2019-10-29 at 10 43 23 AM

Step 4 (Do not add content to line 1, but add to other lines):
Screen Shot 2019-10-29 at 10 43 39 AM

Step 5 (Review content with no changes to line 1. RESULT: Diff displays proceeding lines):
Screen Shot 2019-10-29 at 10 43 52 AM

How i can build project in local

I have cloned the project in my local
did npn i for dependencies
But i am not able to run this locally, could you tell me how to use this ?

I am running as - npm run devServer

Support Disable Code Fold Message

Hi there,

I have a use-case where I need to hide the code fold message. Passing undefined to codeFoldRenderer simply falls back to the default behavior. It's possible to pass an override function, but this feels like a bit of a hack. Would a PR be accepted to support a displayCodeFoldMessage property that would optionally allow users to disable the code fold message? The default value would be true to support backwards-compatibility.

Thanks for all the work on this component!

Relax engine requirements

The latest version 3.0.0 looks great, and thank you for all the improvements.

However, one thing that changed is the engines definition in package.json. When attempting to install with yarn, it refuses to install if you're not using node 12.

This can be worked around with the --ignore-engines flag, but it's not clear whether requiring v12 is absolutely necessary. I think at least v10 should be allowed as well.

$ yarn add react-diff-viewer
yarn add v1.21.1
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
error [email protected]: The engine "node" is incompatible with this module. Expected version "^12". Got "10.17.0"
error Found incompatible module.

Too long to view

How can I set a length so that the content scrolls on its own
image

Remove engines requirement

Please remove the engines requirement from package.json as there is no reason to include such an annoying field.
Or at lease make it something like { "node": ">= 8" }

Can I use this library in my enterprise project ?

Here I am looking for few details -

Can I use this library in my enterprise company project ? I can see this is MIT license so I think I can use it.
Your library or react component use https://github.com/kpdecker/jsdiff jsdiff which seems to be under BSD licensing, https://github.com/kpdecker/jsdiff/blob/master/LICENSE

Can i assume this is stable component we can refer and use in project.

Thanks for awesome library and work, looking forward to hear from you. Thanks.

Issue with showDiffOnly option

Hello, @praneshr .

Thank you for your response regarding issue #43 , it is highly appreciated. However, as mentioned in the initial message, it is not possible to customize the library with the provided settings including extraLinesSurroundingDiff.

I attempted to set the aforementioned option to 0, 1 and some other values, still, it did not resolve the issue with several extra lines. Moreover, they are display rather randomly.

Also, updating the package to the latest version (2.0.5) did not help.

Is there anything else you may suggest? I would highly appreciate of you look into the issue deeper and fix it if possible.

Have a great day ahead!

[feature request] Export Package as ES5

This is related to the core issue in #47, but offers a suggestion on a solution. From @jamesopti on https://github.com/optimizely/oui/pull/1271:

This (https://github.com/optimizely/oui/pull/1271/files#diff-11e9f7f953edc64ba14b0cc350ae7b9dR42) works as a crutch, but is not ideal.

Could you open a ticket with the package maintainer?

There is a lot of debate in the community about whether the package.json module should be used purely to indicate ESM (the spec) or to indicate ES2015+ code (which has become common practice).

I think the simple solution here is for the package maintainer to just export an ES5 package. It's pretty straightforward.

More on this topic here: https://babeljs.io/blog/2018/06/26/on-consuming-and-publishing-es2015+-packages

@praneshr, reading through the related issues it sounds like you may have strong feelings that this should be handled by the consumer. Curious though, do you think there are any drawbacks in exporting as es5? I think it would make this module more easily consumable for many more projects without custom configuration like we ended up doing (hopefully only temporarily).

If it's less of a philosophical difference and more of a question of the actual human work it would add, I'd be happy to take a stab at it.

Typing issue (possibly to do with strict null types)

When I build my TypeScript project which uses this library, I get several typing errors in the styles.d.ts file. This appears to be due to the properties of ReactDiffViewerStyles being optional properties, but the type of [key: string] being string, not string | undefined.

Could not find a declaration file for module...implicitly has an 'any' type

When I try to import ReactDiffViewer, typescript throws this nasty error: "Could not find a declaration file for module...implicitly has an 'any' type." Turns out, the solution is simple, which you can find here: https://stackoverflow.com/questions/41292559/could-not-find-a-declaration-file-for-module-module-name-path-to-module-nam.

Tl;dr: could you please modify your package.json to have these two lines?

"main": "lib/index",
"typings": "lib/index",

^ removes the .js at the end of "lib/index.js" and adds typings

This solved the problem locally for me, but it'd be nice if this fix was automatically included for everyone!

Question! about file compare

I'm working on a project that needs a diff but not really for code but more documents how is the support for something like that?
the data I'm consuming will be structured in nodes like this and not just raw text

  {
    "id": "00000000-0000-0000-0000-000000000000",
    "priorId": "00000000-0000-0000-0000-000000000001",
    "headingLevel": 1,
    "content": "Short Title",
    "previousContent": null,
    "changeStatus": 1
  }

Thanks! 😄

Words based diff

Hi, pretty useful work. Currently it shows diff based on characters. How can we show diff based on words.

Just like this one words-based-diff

Add option to disable line text-wrap

In some cases, like long strings or very nested JSON, it may be useful to allow the user or implementer to enable / disable text wrap. If it's not too difficult it would be neat to allow for a prop or CSS option to easily enable / disable line text wrapping.

Unable to customize the gutter styles

Hi!

First off, I love the component! It's great that you've built the styling customizability in so cleanly, too. However, I am running into an issue.

I'm looking for a way to target the leftmost gutter for splitView={false}:

image

I want to hide this gutter, and be able to change the width of the gutters etc..

Even this does nothing:

<ReactDiffViewer
  oldValue={someValue}
  newValue={someOtherValue}
  splitView={false}
  styles={
    gutter: {
     visibility: 'hidden',
    }
  }
/>

bug: react element key hardcoded to 100 (?!?), index keys used frequently

Observe the following snippet of code from index.tsx:

<tr key={Math.round(100).toString()}>

Now consider the following sandbox example: https://codesandbox.io/embed/proud-firefly-wlko9

This is a serious bug.

This example demonstrates that when there's a row that has a key that's based off of the index two react elements will exist with the same key, which, of course, causes react to go crazy. In my specific app, which datafetches the thing that's being diffed, it results in the row being duplicated every few seconds (such that if you have the app open for 60 seconds, you might have 60 duplicated rows).

React depends on keys being unique among siblings.

Furthermore, it's widely considered an antipattern to use array indexes as keys [sources: 1, 2, 3, 4], something that's done very frequently in this project [source 1, 2, 3, 4, 5, 6].

I understand that this is a tough cookie to crack because with a library like this you don't have very many guarantees. You can't exactly force the end user to provide an id for every row/column/whatever. To solve this problem in the past for similar problems I've used some of the solutions suggested in the linked resources on this antipattern above (e.g. shortid).

This bug was introduced here.

Unified (non-split) view without line numbers seems to add extra <td>

Here's a screenshot from my local Storybook:
image

Steps to reproduce:

  • hideLineNumbers{true}
  • showDiffOnly{true}
  • splitView{false}
  • Then oldValue and newValue should have code that is changed on at least one line but is the same on more than 3 lines surrounding.

The result is the screenshot above. I notice that removing the td from the Elements panel seems to resolve it. So this element:

image

When removed makes it look like this:

image

I'm thinking

{!splitView ? content : <td />}
should actually be:

{!splitView ? content : null}

So splitView={true} will add an extra cell but unified view will not. If you think that's a reasonable approach, I can make a PR!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.