support permalinks to lines in source code view (#1472)

This features adjusts the syntax checker to render a little link icon next to a hovered line. When clicked,
a permanent link to this line is created and copied to the user's clipboard. When visiting the link,
the focused row is highlighted.

Co-authored-by: Eduard Heimbuch <eduard.heimbuch@cloudogu.com>
This commit is contained in:
Konstantin Schaper
2020-12-14 09:15:18 +01:00
committed by GitHub
parent 1ef0b42eb5
commit fed16f296a
9 changed files with 18170 additions and 15258 deletions

View File

@@ -0,0 +1,45 @@
/*
* 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.
*/
export default async function copyToClipboard(text: string) {
if (navigator.clipboard) {
return navigator.clipboard.writeText(text);
} else {
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed"; //avoid scrolling to bottom
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand("copy");
return Promise.resolve();
} catch (e) {
return Promise.reject(e);
} finally {
document.body.removeChild(textArea);
}
}
}

View File

@@ -21,7 +21,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import React from "react";
import React, { ReactNode } from "react";
import { storiesOf } from "@storybook/react";
import styled from "styled-components";
import SyntaxHighlighter from "./SyntaxHighlighter";
@@ -31,12 +31,16 @@ import GoHttpServer from "./__resources__/HttpServer.go";
import JsHttpServer from "./__resources__/HttpServer.js";
import PyHttpServer from "./__resources__/HttpServer.py";
import Markdown from "./__resources__/test-page.md";
import { MemoryRouter } from "react-router-dom";
const Spacing = styled.div`
padding: 1em;
`;
const RoutingDecorator = (story: () => ReactNode) => <MemoryRouter initialEntries={["/"]}>{story()}</MemoryRouter>;
storiesOf("SyntaxHighlighter", module)
.addDecorator(RoutingDecorator)
.add("Java", () => (
<Spacing>
<SyntaxHighlighter language="java" value={JavaHttpServer} />

View File

@@ -21,37 +21,68 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import React from "react";
import React, { FC, useEffect, useState } from "react";
import { PrismAsyncLight as ReactSyntaxHighlighter } from "react-syntax-highlighter";
import { defaultLanguage, determineLanguage } from "./languages";
// eslint-disable-next-line no-restricted-imports
import highlightingTheme from "./syntax-highlighting";
import { useLocation } from "react-router-dom";
import { withContextPath } from "./urls";
import createSyntaxHighlighterRenderer from "./SyntaxHighlighterRenderer";
const LINE_NUMBER_URL_HASH_REGEX = /^#line-(.*)$/;
type Props = {
language?: string;
value: string;
showLineNumbers?: boolean;
permalink?: string;
};
class SyntaxHighlighter extends React.Component<Props> {
static defaultProps: Partial<Props> = {
language: defaultLanguage,
showLineNumbers: true
};
const SyntaxHighlighter: FC<Props> = ({
language = defaultLanguage,
showLineNumbers = true,
value,
permalink
}) => {
const location = useLocation();
const [contentRef, setContentRef] = useState<HTMLElement | null>();
render() {
const { showLineNumbers, language } = this.props;
return (
useEffect(() => {
const match = location.hash.match(LINE_NUMBER_URL_HASH_REGEX);
if (contentRef && match) {
const lineNumber = match[1];
// We defer the content check until after the syntax-highlighter has rendered
setTimeout(() => {
const element = contentRef.querySelector(`#line-${lineNumber}`);
if (element && element.scrollIntoView) {
element.scrollIntoView();
}
});
}
}, [value, contentRef]);
const createLinePermaLink = (lineNumber: number) =>
window.location.protocol +
"//" +
window.location.host +
withContextPath((permalink || location.pathname) + "#line-" + lineNumber);
const defaultRenderer = createSyntaxHighlighterRenderer(createLinePermaLink, showLineNumbers);
return (
<div ref={setContentRef}>
<ReactSyntaxHighlighter
showLineNumbers={showLineNumbers}
showLineNumbers={false}
language={determineLanguage(language)}
style={highlightingTheme}
renderer={defaultRenderer}
>
{this.props.value}
{value}
</ReactSyntaxHighlighter>
);
}
}
</div>
);
};
export default SyntaxHighlighter;

View File

@@ -0,0 +1,151 @@
/*
* 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, useEffect, useState } from "react";
// eslint-disable-next-line @typescript-eslint/ban-ts-ignore
// @ts-ignore
import { createElement } from "react-syntax-highlighter";
import Icon from "./Icon";
import Tooltip from "./Tooltip";
import styled from "styled-components";
import copyToClipboard from "./CopyToClipboard";
import { useTranslation } from "react-i18next";
import { useHistory, useLocation } from "react-router-dom";
const RowContainer = styled.div`
.linenumber {
display: inline-block;
min-width: 3em;
padding-right: 1em;
text-align: right;
user-select: none;
color: rgb(154, 154, 154);
}
span.linenumber:hover {
cursor: pointer;
}
span.linenumber + span > span.linenumber {
display: none !important;
}
&.focused,
&.focused > span:last-child {
background-color: rgb(229, 245, 252);
}
i {
visibility: hidden;
}
i:hover {
cursor: pointer;
}
&:hover i {
visibility: visible;
}
`;
type CreateLinePermaLinkFn = (lineNumber: number) => string;
type Props = {
rows: React.ReactNode[];
stylesheet: any;
useInlineStyles: boolean;
createLinePermaLink: CreateLinePermaLinkFn;
showLineNumbers: boolean;
};
const SyntaxHighlighterRenderer: FC<Props> = ({
rows,
stylesheet,
useInlineStyles,
createLinePermaLink,
showLineNumbers = true
}) => {
const location = useLocation();
const history = useHistory();
const [focusedLine, setLineToFocus] = useState<number | undefined>(undefined);
const [copying, setCopying] = useState(false);
const [t] = useTranslation("repos");
useEffect(() => {
const match = location.hash.match(/^#line-(.*)$/);
if (match) {
const lineNumber = match[1];
setLineToFocus(Number(lineNumber));
}
}, [location.hash]);
const lineNumberClick = (lineNumber: number) => {
history.push(location.pathname + "#line-" + lineNumber);
setCopying(true);
copyToClipboard(createLinePermaLink(lineNumber)).finally(() => setCopying(false));
};
return (
<>
{rows.map((node: React.ReactNode, i: number) => {
const lineNumber = i + 1;
const line = createElement({
node,
stylesheet,
useInlineStyles,
key: `code-segment${i}`
});
return (
<RowContainer
id={`line-${lineNumber}`}
className={(focusedLine === lineNumber && "focused") || undefined}
key={`line-${lineNumber}`}
>
{showLineNumbers && (
<>
{copying ? (
<Icon name="spinner" />
) : (
<Tooltip message={t("sources.content.copyPermalink")}>
<Icon name="link" onClick={() => lineNumberClick(lineNumber)} />
</Tooltip>
)}
<span
onClick={() => history.push(location.pathname + "#line-" + lineNumber)}
className="linenumber react-syntax-highlighter-line-number"
>
{lineNumber}
</span>
</>
)}
{line}
</RowContainer>
);
})}
</>
);
};
//
export const create = (createLinePermaLink: CreateLinePermaLinkFn, showLineNumbers = false): FC<Props> => {
return props => (
<SyntaxHighlighterRenderer {...props} createLinePermaLink={createLinePermaLink} showLineNumbers={showLineNumbers} />
);
};
export default create;

File diff suppressed because it is too large Load Diff