refactor to use file control factory

This commit is contained in:
Konstantin Schaper
2020-08-10 20:48:08 +02:00
parent 08efc9421d
commit c69ab4ea65
12 changed files with 226 additions and 190 deletions

View File

@@ -29,13 +29,15 @@ import parser from "gitdiff-parser";
import simpleDiff from "../__resources__/Diff.simple";
import hunksDiff from "../__resources__/Diff.hunks";
import binaryDiff from "../__resources__/Diff.binary";
import { DiffEventContext, File } from "./DiffTypes";
import {DiffEventContext, File, FileControlFactory} from "./DiffTypes";
import Toast from "../toast/Toast";
import { getPath } from "./diffs";
import DiffButton from "./DiffButton";
import styled from "styled-components";
import { MemoryRouter } from "react-router-dom";
import {one} from "../__resources__/changesets";
import {one, two} from "../__resources__/changesets";
import {Changeset} from "@scm-manager/ui-types";
import JumpToFileButton from "./JumpToFileButton";
const diffFiles = parser.parse(simpleDiff);
@@ -45,16 +47,50 @@ const Container = styled.div`
const RoutingDecorator = (story: () => ReactNode) => <MemoryRouter initialEntries={["/"]}>{story()}</MemoryRouter>;
const fileControlFactory: (changeset: Changeset) => FileControlFactory = (changeset) => (file) => {
const baseUrl = "/repo/hitchhiker/heartOfGold/code/changeset";
const sourceLink = {
url: `${baseUrl}/${changeset.id}/${file.newPath}/`,
label: "Jump to source"
};
const targetLink = changeset._embedded?.parents?.length === 1 && {
url: `${baseUrl}/${changeset._embedded.parents[0].id}/${file.oldPath}`,
label: "Jump to target"
};
const links = [];
switch (file.type) {
case "add":
links.push(sourceLink);
break;
case "delete":
if (targetLink) {
links.push(targetLink);
}
break;
default:
if (targetLink) {
links.push(sourceLink, targetLink);
} else {
links.push(sourceLink);
}
}
return links.map(({url, label}) => <JumpToFileButton
tooltip={label}
link={url}
/>);
};
storiesOf("Diff", module)
.addDecorator(RoutingDecorator)
.addDecorator(storyFn => <Container>{storyFn()}</Container>)
.add("Default", () => <Diff diff={diffFiles} changeset={one} />)
.add("Side-By-Side", () => <Diff diff={diffFiles} sideBySide={true} changeset={one} />)
.add("Collapsed", () => <Diff diff={diffFiles} defaultCollapse={true} changeset={one} />)
.add("Default", () => <Diff diff={diffFiles} />)
.add("Side-By-Side", () => <Diff diff={diffFiles} sideBySide={true} />)
.add("Collapsed", () => <Diff diff={diffFiles} defaultCollapse={true} fileControlFactory={fileControlFactory(two)} />)
.add("File Controls", () => (
<Diff
diff={diffFiles}
changeset={one}
fileControlFactory={() => (
<DiffButton
tooltip="A skull and crossbones or death's head is a symbol consisting of a human skull and two long bones crossed together under or behind the skull. The design originates in the Late Middle Ages as a symbol of death and especially as a memento mori on tombstones."
@@ -67,14 +103,12 @@ storiesOf("Diff", module)
.add("File Annotation", () => (
<Diff
diff={diffFiles}
changeset={one}
fileAnnotationFactory={file => [<p key={file.newPath}>Custom File annotation for {file.newPath}</p>]}
/>
))
.add("Line Annotation", () => (
<Diff
diff={diffFiles}
changeset={one}
annotationFactory={ctx => {
return {
N2: <p key="N2">Line Annotation</p>
@@ -94,7 +128,7 @@ storiesOf("Diff", module)
return (
<>
{changeId && <Toast type="info" title={"Change " + changeId} />}
<Diff diff={diffFiles} changeset={one} onClick={onClick} />
<Diff diff={diffFiles} onClick={onClick} />
</>
);
};
@@ -102,11 +136,11 @@ storiesOf("Diff", module)
})
.add("Hunks", () => {
const hunkDiffFiles = parser.parse(hunksDiff);
return <Diff diff={hunkDiffFiles} changeset={one} />;
return <Diff diff={hunkDiffFiles} />;
})
.add("Binaries", () => {
const binaryDiffFiles = parser.parse(binaryDiff);
return <Diff diff={binaryDiffFiles} changeset={one} />;
return <Diff diff={binaryDiffFiles} />;
})
.add("SyntaxHighlighting", () => {
const filesWithLanguage = diffFiles.map((file: File) => {
@@ -118,22 +152,20 @@ storiesOf("Diff", module)
}
return file;
});
return <Diff diff={filesWithLanguage} changeset={one} />;
return <Diff diff={filesWithLanguage} />;
})
.add("CollapsingWithFunction", () => (
<Diff diff={diffFiles} changeset={one} defaultCollapse={(oldPath, newPath) => oldPath.endsWith(".java")} />
<Diff diff={diffFiles} defaultCollapse={(oldPath, newPath) => oldPath.endsWith(".java")} />
))
.add("Expandable", () => {
const filesWithLanguage = diffFiles.map((file: File) => {
file._links = { lines: { href: "http://example.com/" } };
return file;
});
return <Diff diff={filesWithLanguage} changeset={one} />;
return <Diff diff={filesWithLanguage} />;
})
.add("WithLinkToFile", () => (
<Diff
diff={diffFiles}
changeset={one}
baseUrl="/repo/hitchhiker/heartOfGold/code/changeset"
/>
));

View File

@@ -23,17 +23,15 @@
*/
import React from "react";
import DiffFile from "./DiffFile";
import { DiffObjectProps, File } from "./DiffTypes";
import {DiffObjectProps, File, FileControlFactory} from "./DiffTypes";
import Notification from "../Notification";
import { WithTranslation, withTranslation } from "react-i18next";
import {Changeset} from "@scm-manager/ui-types";
import {WithTranslation, withTranslation} from "react-i18next";
type Props = WithTranslation &
DiffObjectProps & {
diff: File[];
changeset: Changeset;
baseUrl?: string;
};
diff: File[];
fileControlFactory?: FileControlFactory;
};
class Diff extends React.Component<Props> {
static defaultProps: Partial<Props> = {
@@ -41,7 +39,7 @@ class Diff extends React.Component<Props> {
};
render() {
const { diff, t, ...fileProps } = this.props;
const {diff, t, ...fileProps} = this.props;
return (
<>
{diff.length === 0 ? (

View File

@@ -22,34 +22,30 @@
* SOFTWARE.
*/
import React from "react";
import { withTranslation, WithTranslation } from "react-i18next";
import {withTranslation, WithTranslation} from "react-i18next";
import classNames from "classnames";
import styled from "styled-components";
// @ts-ignore
import { Decoration, getChangeKey, Hunk } from "react-diff-view";
import { ButtonGroup } from "../buttons";
import {Decoration, getChangeKey, Hunk} from "react-diff-view";
import {ButtonGroup} from "../buttons";
import Tag from "../Tag";
import Icon from "../Icon";
import { Change, ChangeEvent, DiffObjectProps, File, Hunk as HunkType } from "./DiffTypes";
import {Change, ChangeEvent, DiffObjectProps, File, Hunk as HunkType} from "./DiffTypes";
import TokenizedDiffView from "./TokenizedDiffView";
import DiffButton from "./DiffButton";
import { MenuContext } from "@scm-manager/ui-components";
import DiffExpander, { ExpandableHunk } from "./DiffExpander";
import {MenuContext} from "@scm-manager/ui-components";
import DiffExpander, {ExpandableHunk} from "./DiffExpander";
import HunkExpandLink from "./HunkExpandLink";
import { Modal } from "../modals";
import {Modal} from "../modals";
import ErrorNotification from "../ErrorNotification";
import HunkExpandDivider from "./HunkExpandDivider";
import JumpToFileButton from "./JumpToFileButton";
import {Changeset} from "@scm-manager/ui-types";
const EMPTY_ANNOTATION_FACTORY = {};
type Props = DiffObjectProps &
WithTranslation & {
file: File;
changeset: Changeset;
baseUrl?: string;
};
file: File;
};
type Collapsible = {
collapsed?: boolean;
@@ -119,7 +115,7 @@ class DiffFile extends React.Component<Props, State> {
}
defaultCollapse: () => boolean = () => {
const { defaultCollapse, file } = this.props;
const {defaultCollapse, file} = this.props;
if (typeof defaultCollapse === "boolean") {
return defaultCollapse;
} else if (typeof defaultCollapse === "function") {
@@ -130,7 +126,7 @@ class DiffFile extends React.Component<Props, State> {
};
toggleCollapse = () => {
const { file } = this.state;
const {file} = this.state;
if (this.hasContent(file)) {
this.setState(state => ({
collapsed: !state.collapsed
@@ -161,7 +157,7 @@ class DiffFile extends React.Component<Props, State> {
<HunkExpandLink
icon={"fa-angle-double-up"}
onClick={this.expandHead(expandableHunk, expandableHunk.maxExpandHeadRange)}
text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandHeadRange })}
text={this.props.t("diff.expandComplete", {count: expandableHunk.maxExpandHeadRange})}
/>
</HunkExpandDivider>
);
@@ -171,19 +167,19 @@ class DiffFile extends React.Component<Props, State> {
<HunkExpandLink
icon={"fa-angle-up"}
onClick={this.expandHead(expandableHunk, 10)}
text={this.props.t("diff.expandByLines", { count: 10 })}
text={this.props.t("diff.expandByLines", {count: 10})}
/>{" "}
<HunkExpandLink
icon={"fa-angle-double-up"}
onClick={this.expandHead(expandableHunk, expandableHunk.maxExpandHeadRange)}
text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandHeadRange })}
text={this.props.t("diff.expandComplete", {count: expandableHunk.maxExpandHeadRange})}
/>
</HunkExpandDivider>
);
}
}
// hunk header must be defined
return <span />;
return <span/>;
};
createHunkFooter = (expandableHunk: ExpandableHunk) => {
@@ -194,7 +190,7 @@ class DiffFile extends React.Component<Props, State> {
<HunkExpandLink
icon={"fa-angle-double-down"}
onClick={this.expandBottom(expandableHunk, expandableHunk.maxExpandBottomRange)}
text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandBottomRange })}
text={this.props.t("diff.expandComplete", {count: expandableHunk.maxExpandBottomRange})}
/>
</HunkExpandDivider>
);
@@ -204,19 +200,19 @@ class DiffFile extends React.Component<Props, State> {
<HunkExpandLink
icon={"fa-angle-down"}
onClick={this.expandBottom(expandableHunk, 10)}
text={this.props.t("diff.expandByLines", { count: 10 })}
text={this.props.t("diff.expandByLines", {count: 10})}
/>{" "}
<HunkExpandLink
icon={"fa-angle-double-down"}
onClick={this.expandBottom(expandableHunk, expandableHunk.maxExpandBottomRange)}
text={this.props.t("diff.expandComplete", { count: expandableHunk.maxExpandBottomRange })}
text={this.props.t("diff.expandComplete", {count: expandableHunk.maxExpandBottomRange})}
/>
</HunkExpandDivider>
);
}
}
// hunk footer must be defined
return <span />;
return <span/>;
};
createLastHunkFooter = (expandableHunk: ExpandableHunk) => {
@@ -226,7 +222,7 @@ class DiffFile extends React.Component<Props, State> {
<HunkExpandLink
icon={"fa-angle-down"}
onClick={this.expandBottom(expandableHunk, 10)}
text={this.props.t("diff.expandLastBottomByLines", { count: 10 })}
text={this.props.t("diff.expandLastBottomByLines", {count: 10})}
/>{" "}
<HunkExpandLink
icon={"fa-angle-double-down"}
@@ -237,7 +233,7 @@ class DiffFile extends React.Component<Props, State> {
);
}
// hunk header must be defined
return <span />;
return <span/>;
};
expandHead = (expandableHunk: ExpandableHunk, count: number) => {
@@ -259,16 +255,16 @@ class DiffFile extends React.Component<Props, State> {
};
diffExpanded = (newFile: File) => {
this.setState({ file: newFile, diffExpander: new DiffExpander(newFile) });
this.setState({file: newFile, diffExpander: new DiffExpander(newFile)});
};
diffExpansionFailed = (err: any) => {
this.setState({ expansionError: err });
this.setState({expansionError: err});
};
collectHunkAnnotations = (hunk: HunkType) => {
const { annotationFactory } = this.props;
const { file } = this.state;
const {annotationFactory} = this.props;
const {file} = this.state;
if (annotationFactory) {
return annotationFactory({
hunk,
@@ -280,8 +276,8 @@ class DiffFile extends React.Component<Props, State> {
};
handleClickEvent = (change: Change, hunk: HunkType) => {
const { onClick } = this.props;
const { file } = this.state;
const {onClick} = this.props;
const {file} = this.state;
const context = {
changeId: getChangeKey(change),
change,
@@ -294,7 +290,7 @@ class DiffFile extends React.Component<Props, State> {
};
createGutterEvents = (hunk: HunkType) => {
const { onClick } = this.props;
const {onClick} = this.props;
if (onClick) {
return {
onClick: (event: ChangeEvent) => {
@@ -315,7 +311,7 @@ class DiffFile extends React.Component<Props, State> {
} else if (i > 0) {
items.push(
<Decoration>
<HunkDivider />
<HunkDivider/>
</Decoration>
);
}
@@ -358,7 +354,7 @@ class DiffFile extends React.Component<Props, State> {
if (file.oldPath !== file.newPath && (file.type === "copy" || file.type === "rename")) {
return (
<>
{file.oldPath} <Icon name="arrow-right" color="inherit" /> {file.newPath}
{file.oldPath} <Icon name="arrow-right" color="inherit"/> {file.newPath}
</>
);
} else if (file.type === "delete") {
@@ -377,7 +373,7 @@ class DiffFile extends React.Component<Props, State> {
};
renderChangeTag = (file: File) => {
const { t } = this.props;
const {t} = this.props;
if (!file.type) {
return;
}
@@ -389,14 +385,14 @@ class DiffFile extends React.Component<Props, State> {
const color =
value === "added" ? "success is-outlined" : value === "deleted" ? "danger is-outlined" : "info is-outlined";
return <ChangeTypeTag className={classNames("is-rounded", "has-text-weight-normal")} color={color} label={value} />;
return <ChangeTypeTag className={classNames("is-rounded", "has-text-weight-normal")} color={color} label={value}/>;
};
hasContent = (file: File) => file && !file.isBinary && file.hunks && file.hunks.length > 0;
render() {
const { fileControlFactory, fileAnnotationFactory, changeset: { id: changesetId, _embedded: { parents } }, baseUrl, t } = this.props;
const { file, collapsed, sideBySide, diffExpander, expansionError } = this.state;
const {fileControlFactory, fileAnnotationFactory, t} = this.props;
const {file, collapsed, sideBySide, diffExpander, expansionError} = this.state;
const viewType = sideBySide ? "split" : "unified";
let body = null;
@@ -417,37 +413,14 @@ class DiffFile extends React.Component<Props, State> {
</div>
);
}
const collapseIcon = this.hasContent(file) ? <Icon name={icon} color="inherit" /> : null;
const collapseIcon = this.hasContent(file) ? <Icon name={icon} color="inherit"/> : null;
const fileControls = fileControlFactory ? fileControlFactory(file, this.setCollapse) : null;
let jumpToSource = null;
let jumpToTarget = null;
if (changesetId && baseUrl) {
const jumpToSourceButton = <JumpToFileButton
tooltip={this.props.t("diff.jumpToSource")}
link={`${baseUrl.substr(0, baseUrl.lastIndexOf("/"))}/sources/${changesetId}/${file.newPath}/`}
/>;
const jumpToTargetButton = parents?.length === 1 && <JumpToFileButton
tooltip={this.props.t("diff.jumpToTarget")}
link={`${baseUrl.substr(0, baseUrl.lastIndexOf("/"))}/sources/${parents[0].id}/${file.oldPath}/`}
/>;
switch (file.type) {
case "add":
jumpToSource = jumpToSourceButton;
break;
case "delete":
jumpToTarget = jumpToTargetButton;
break;
default:
jumpToSource = jumpToSourceButton;
jumpToTarget = jumpToTargetButton;
}
}
const sideBySideToggle =
file.hunks && file.hunks.length > 0 ? (
file.hunks && file.hunks.length > 0 && (
<ButtonWrapper className={classNames("level-right", "is-flex")}>
<ButtonGroup>
<MenuContext.Consumer>
{({ setCollapsed }) => (
{({setCollapsed}) => (
<DiffButton
icon={sideBySide ? "align-left" : "columns"}
tooltip={t(sideBySide ? "diff.combined" : "diff.sideBySide")}
@@ -462,15 +435,6 @@ class DiffFile extends React.Component<Props, State> {
)}
</MenuContext.Consumer>
{fileControls}
{jumpToSource}
{jumpToTarget}
</ButtonGroup>
</ButtonWrapper>
) : (
<ButtonWrapper className={classNames("level-right", "is-flex")}>
<ButtonGroup>
{jumpToSource}
{jumpToTarget}
</ButtonGroup>
</ButtonWrapper>
);
@@ -480,8 +444,8 @@ class DiffFile extends React.Component<Props, State> {
errorModal = (
<Modal
title={t("diff.expansionFailed")}
closeFunction={() => this.setState({ expansionError: undefined })}
body={<ErrorNotification error={expansionError} />}
closeFunction={() => this.setState({expansionError: undefined})}
body={<ErrorNotification error={expansionError}/>}
active={true}
/>
);

View File

@@ -22,25 +22,22 @@
* SOFTWARE.
*/
import React from "react";
import { apiClient } from "../apiclient";
import {apiClient} from "../apiclient";
import ErrorNotification from "../ErrorNotification";
// @ts-ignore
import parser from "gitdiff-parser";
import Loading from "../Loading";
import Diff from "./Diff";
import { DiffObjectProps, File } from "./DiffTypes";
import { NotFoundError } from "../errors";
import { Notification } from "../index";
import { withTranslation, WithTranslation } from "react-i18next";
import {Changeset} from "@scm-manager/ui-types";
import {DiffObjectProps, File} from "./DiffTypes";
import {NotFoundError} from "../errors";
import {Notification} from "../index";
import {withTranslation, WithTranslation} from "react-i18next";
type Props = WithTranslation &
DiffObjectProps & {
url: string;
changeset: Changeset;
baseUrl: string;
};
url: string;
};
type State = {
diff?: File[];
@@ -71,8 +68,8 @@ class LoadingDiff extends React.Component<Props, State> {
}
fetchDiff = () => {
const { url } = this.props;
this.setState({ loading: true });
const {url} = this.props;
this.setState({loading: true});
apiClient
.get(url)
.then(response => {
@@ -98,14 +95,14 @@ class LoadingDiff extends React.Component<Props, State> {
};
render() {
const { diff, loading, error } = this.state;
const {diff, loading, error} = this.state;
if (error) {
if (error instanceof NotFoundError) {
return <Notification type="info">{this.props.t("changesets.noChangesets")}</Notification>;
}
return <ErrorNotification error={error} />;
return <ErrorNotification error={error}/>;
} else if (loading) {
return <Loading />;
return <Loading/>;
} else if (!diff) {
return null;
} else {

View File

@@ -22,15 +22,16 @@
* SOFTWARE.
*/
import React from "react";
import { Changeset, Link, Collection } from "@scm-manager/ui-types";
import {Changeset, Collection, Link} from "@scm-manager/ui-types";
import LoadingDiff from "../LoadingDiff";
import Notification from "../../Notification";
import { WithTranslation, withTranslation } from "react-i18next";
import {WithTranslation, withTranslation} from "react-i18next";
import {FileControlFactory} from "../DiffTypes";
type Props = WithTranslation & {
changeset: Changeset;
baseUrl: string;
defaultCollapse?: boolean;
fileControlFactory?: FileControlFactory;
};
export const isDiffSupported = (changeset: Collection) => {
@@ -48,12 +49,12 @@ export const createUrl = (changeset: Collection) => {
class ChangesetDiff extends React.Component<Props> {
render() {
const { changeset, baseUrl, defaultCollapse, t } = this.props;
const {changeset, fileControlFactory, defaultCollapse, t} = this.props;
if (!isDiffSupported(changeset)) {
return <Notification type="danger">{t("changeset.diffNotSupported")}</Notification>;
} else {
const url = createUrl(changeset);
return <LoadingDiff url={url} defaultCollapse={defaultCollapse} sideBySide={false} changeset={changeset} baseUrl={baseUrl} />;
return <LoadingDiff url={url} defaultCollapse={defaultCollapse} sideBySide={false} fileControlFactory={fileControlFactory}/>;
}
}
}

View File

@@ -35,6 +35,7 @@ import ChangesetAuthor from "./ChangesetAuthor";
import ChangesetTags from "./ChangesetTags";
import ChangesetButtonGroup from "./ChangesetButtonGroup";
import ChangesetDescription from "./ChangesetDescription";
import {FileControlFactory} from "../DiffTypes";
type Props = WithTranslation & {
repository: Repository;

View File

@@ -45,11 +45,13 @@ export * from "./changesets";
export { default as Diff } from "./Diff";
export { default as DiffFile } from "./DiffFile";
export { default as DiffButton } from "./DiffButton";
export { FileControlFactory } from "./DiffTypes";
export { default as LoadingDiff } from "./LoadingDiff";
export { DefaultCollapsed, DefaultCollapsedFunction } from "./defaultCollapsed";
export { default as RepositoryAvatar } from "./RepositoryAvatar";
export { default as RepositoryEntry } from "./RepositoryEntry";
export { default as RepositoryEntryLink } from "./RepositoryEntryLink";
export { default as JumpToFileButton } from "./JumpToFileButton";
export {
File,