Create split and replace component

This commit is contained in:
René Pfeuffer
2020-06-30 15:20:59 +02:00
parent 6df62788a1
commit f62683e528
4 changed files with 111 additions and 0 deletions

View File

@@ -0,0 +1,59 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import React from "react";
import { storiesOf } from "@storybook/react";
import SplitAndReplace from "./SplitAndReplace";
import { Icon } from "@scm-manager/ui-components/src";
storiesOf("SplitAndReplace", module).add("Simple replacement", () => {
const replacements = [
{
textToReplace: "'",
replacement: <Icon name={"quote-left"}/>,
replaceAll: true
},
{
textToReplace: "`",
replacement: <Icon name={"quote-right"}/>,
replaceAll: true
},
{
replacement: <div>&nbsp;</div>,
textToReplace: " ",
replaceAll: true
}
];
return (
<>
<div className={"container"}><SplitAndReplace
text={"'So this is it,` said Arthur, 'We are going to die.`"}
replacements={replacements}
/></div>
<div className={"container"}><SplitAndReplace
text={"'Yes,` said Ford, 'except... no! Wait a minute!`"}
replacements={replacements}
/></div>
</>
);
});

View File

@@ -0,0 +1,52 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import React, { FC, ReactNode } from "react";
import textSplitAndReplace from "./textSplitAndReplace";
type Replacement = {
textToReplace: string;
replacement: ReactNode;
replaceAll: boolean;
};
type Props = {
text: string;
replacements: Replacement[];
};
type PartToReplace = {
start: number;
length: number;
replacement: ReactNode;
};
const SplitAndReplace: FC<Props> = ({ text, replacements }) => {
const parts = textSplitAndReplace<ReactNode>(text, replacements, s => <div>{s}</div>);
if (parts.length === 0) {
return <>{parts[0]}</>;
}
return <div className={"media"}>{parts}</div>;
};
export default SplitAndReplace;

View File

@@ -0,0 +1,134 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import textSplitAndReplace from "./textSplitAndReplace";
type Wrapped = {
text: string;
};
const testWrapper = (s: string) => {
return { text: s };
};
describe("text split and replace", () => {
it("should wrap text if nothing should be replaced", () => {
const result = textSplitAndReplace<Wrapped>("Don't Panic.", [], testWrapper);
expect(result).toHaveLength(1);
expect(result[0]).toStrictEqual({ text: "Don't Panic." });
});
it("should replace single string", () => {
const result = textSplitAndReplace<Wrapped>(
"Don't Panic.",
[{ textToReplace: "'", replacement: { text: "`" } }],
testWrapper
);
expect(result).toHaveLength(3);
expect(result[0]).toStrictEqual({ text: "Don" });
expect(result[1]).toStrictEqual({ text: "`" });
expect(result[2]).toStrictEqual({ text: "t Panic." });
});
it("should replace strings only once if replace all is not set", () => {
const result = textSplitAndReplace<Wrapped>(
"'So this is it,' said Arthur, 'We are going to die.'",
[{ textToReplace: "'", replacement: { text: "“" } }],
testWrapper
);
expect(result).toHaveLength(2);
expect(result[0]).toStrictEqual({ text: "“" });
expect(result[1]).toStrictEqual({ text: "So this is it,' said Arthur, 'We are going to die.'" });
});
it("should replace all strings if replace all is set to true", () => {
const result = textSplitAndReplace<Wrapped>(
"'So this is it,' said Arthur, 'We are going to die.'",
[{ textToReplace: "'", replacement: { text: "“" }, replaceAll: true }],
testWrapper
);
expect(result).toHaveLength(7);
expect(result[0]).toStrictEqual({ text: "“" });
expect(result[1]).toStrictEqual({ text: "So this is it," });
expect(result[2]).toStrictEqual({ text: "“" });
expect(result[3]).toStrictEqual({ text: " said Arthur, " });
expect(result[4]).toStrictEqual({ text: "“" });
expect(result[5]).toStrictEqual({ text: "We are going to die." });
expect(result[6]).toStrictEqual({ text: "“" });
});
it("should replace strings with multiple replacements", () => {
const result = textSplitAndReplace<Wrapped>(
"'So this is it,' said Arthur, 'We are going to die.'",
[
{ textToReplace: "'", replacement: { text: "“" }, replaceAll: true },
{ textToReplace: "Arthur", replacement: { text: "Dent" }, replaceAll: true }
],
testWrapper
);
expect(result).toHaveLength(9);
expect(result[0]).toStrictEqual({ text: "“" });
expect(result[1]).toStrictEqual({ text: "So this is it," });
expect(result[2]).toStrictEqual({ text: "“" });
expect(result[3]).toStrictEqual({ text: " said " });
expect(result[4]).toStrictEqual({ text: "Dent" });
expect(result[5]).toStrictEqual({ text: ", " });
expect(result[6]).toStrictEqual({ text: "“" });
expect(result[7]).toStrictEqual({ text: "We are going to die." });
expect(result[8]).toStrictEqual({ text: "“" });
});
it("should ignore conflicting replacements", () => {
const result = textSplitAndReplace<Wrapped>(
"'So this is it,' said Arthur, 'We are going to die.'",
[
{ textToReplace: "said Arthur", replacement: { text: "to be replaced" } },
{ textToReplace: " said", replacement: { text: "to be ignored 1" }, replaceAll: true },
{ textToReplace: "d A", replacement: { text: "to be ignored 2" }, replaceAll: true },
{ textToReplace: "Arthur,", replacement: { text: "to be ignored 3" }, replaceAll: true }
],
testWrapper
);
expect(result).toHaveLength(3);
expect(result[0]).toStrictEqual({ text: "'So this is it,' " });
expect(result[1]).toStrictEqual({ text: "to be replaced" });
expect(result[2]).toStrictEqual({ text: ", 'We are going to die.'" });
});
it("should replace adjacent texts", () => {
const result = textSplitAndReplace<Wrapped>(
"'So this is it,' said Arthur, 'We are going to die.'",
[
{ textToReplace: "'So this is it,'", replacement: { text: "one" } },
{ textToReplace: " said Arthur, ", replacement: { text: "two" } },
{ textToReplace: "'We are going to die.'", replacement: { text: "three" } }
],
testWrapper
);
expect(result).toHaveLength(3);
expect(result[0]).toStrictEqual({ text: "one" });
expect(result[1]).toStrictEqual({ text: "two" });
expect(result[2]).toStrictEqual({ text: "three" });
});
});

View File

@@ -0,0 +1,86 @@
/*
* MIT License
*
* Copyright (c) 2020-present Cloudogu GmbH and Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
type Replacement<T> = {
textToReplace: string;
replacement: T;
replaceAll?: boolean;
};
type PartToReplace<T> = {
start: number;
length: number;
replacement: T;
};
function hasConflict<T>(alreadyFoundReplacements: PartToReplace<T>[], newReplacement: PartToReplace<T>) {
return !!alreadyFoundReplacements.find(
existing =>
(existing.start <= newReplacement.start && existing.start + existing.length > newReplacement.start) ||
(newReplacement.start <= existing.start && newReplacement.start + newReplacement.length > existing.start)
);
}
export default function textSplitAndReplace<T>(
text: string,
replacements: Replacement<T>[],
textWrapper: (s: string) => T
): T[] {
const partsToReplace: PartToReplace<T>[] = [];
replacements.forEach(replacement => {
let lastIndex = -1;
do {
const start = text.indexOf(replacement.textToReplace, lastIndex);
if (start >= 0) {
const length = replacement.textToReplace.length;
const newReplacement = { start, length, replacement: replacement.replacement };
if (!hasConflict(partsToReplace, newReplacement)) {
partsToReplace.push(newReplacement);
}
lastIndex = start + length;
} else {
lastIndex = -1;
}
} while (replacement.replaceAll && lastIndex >= 0);
});
partsToReplace.sort((a, b) => a.start - b.start);
const result: T[] = [];
let lastIndex = 0;
for (const { start, length, replacement } of partsToReplace) {
if (start > lastIndex) {
result.push(textWrapper(text.substr(lastIndex, start - lastIndex)));
}
result.push(replacement);
lastIndex = start + length;
}
if (lastIndex < text.length) {
result.push(textWrapper(text.substr(lastIndex)));
}
return result;
}