Skip to content

Commit 3f2bc81

Browse files
authored
Merge pull request #169 from ani-team/feature/enhance/repo-readme
Правки с тестирования - Markdown, Alerts ## CHANGELOG - (#162) Добавлен title к секции README - (#162) Поправлены отступы, размеры h1-h6 - (#162) К h1-h2 добавлены дивайдеры - (#162) Добавлены стили для blockquotes - (#162) Добавлена трансформация локальных ссылок - (#162) Добавлена трансформация локальных изображений - (#162) Поправлен max-width у изображений - (#162) Добавлена поддержка github-flavored-markdown (для работы некоторых других тего, например `<del>...</del>` - (#162) Немного отрефакторен хелпер для алерта + использоание antd алерта заменено на использоание хелпера (для единого позиционирования и упрощения API) <img height=100 src="https://user-images.githubusercontent.com/42924400/100803864-f64f3400-343c-11eb-8977-c0393a840d4d.png" /> <img height=100 src="https://user-images.githubusercontent.com/42924400/100803925-0cf58b00-343d-11eb-872f-57161cd3a8cb.png" /> <img height=100 src="https://user-images.githubusercontent.com/42924400/100803907-06ffaa00-343d-11eb-8d93-ac543fc68922.png" /> <img height=100 src="https://user-images.githubusercontent.com/42924400/100805403-aa51be80-343f-11eb-919c-d28089728e6c.png" />
2 parents 1d2c9d6 + 2fe6bae commit 3f2bc81

File tree

7 files changed

+274
-22
lines changed

7 files changed

+274
-22
lines changed

package-lock.json

Lines changed: 126 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
"react-router-dom": "^5.2.0",
2929
"react-scripts": "3.4.3",
3030
"react-syntax-highlighter": "^15.3.1",
31+
"remark-gfm": "^1.0.0",
3132
"tailwindcss": "^1.9.5",
3233
"typescript": "^3.7.5",
3334
"use-query-params": "^1.1.9"

src/features/auth/page/index.tsx

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React from "react";
22
import { GithubFilled } from "@ant-design/icons";
3-
import { Alert, Card, notification } from "antd";
3+
import { Alert, Card } from "antd";
4+
import { alert } from "shared/helpers";
45
// !!! FIXME: loop imports
56
import { useTitle } from "pages/helpers";
67
import { authorizeGithub } from "../firebase";
@@ -20,14 +21,12 @@ import "./index.scss";
2021
const AuthPage = () => {
2122
useTitle("Sign in to Github Client");
2223
const { login } = useAuth();
23-
const showError = (message: string) =>
24-
notification.error({ message: "Authorization error", description: message, top: 72 });
2524

2625
// TODO: add ability to specify redirect url
2726
const authorize = () => {
2827
authorizeGithub()
2928
.then(login)
30-
.catch((err: Error) => showError(err.message));
29+
.catch((err: Error) => alert.error("Authorization error", err.message));
3130
};
3231

3332
return (

src/features/repo-explorer/components/index.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,12 @@ const Explorer = ({ repo }: Props) => {
7373
},
7474
});
7575
const { branches, files, lastCommit, readme } = useRepoDetails(data);
76-
76+
const repoUrl = `${repo.owner}/${repo.name}`;
7777
return (
7878
<div>
7979
<RepoToolbar repo={repo} branches={branches} activeBranch={branch} />
8080
<EntriesView files={files} lastCommit={lastCommit} loading={loading} className="mt-3" />
81-
<RepoReadme text={readme} loading={loading} />
81+
<RepoReadme text={readme} loading={loading} repoUrl={repoUrl} branch={branch} />
8282
</div>
8383
);
8484
};

src/features/repo-explorer/components/readme/index.scss

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,54 @@
33
border: 1px solid var(--clr-gray--100);
44
border-radius: 6px;
55

6-
code {
7-
padding: 1px 4px;
8-
background: var(--clr-gray--100);
9-
border-radius: 6px;
6+
&__title {
7+
font-size: 14px;
8+
}
9+
10+
&__markdown {
11+
// [github-styles] offsets
12+
> :first-child {
13+
margin-top: 0 !important;
14+
}
15+
// [github-styles] headers offsets
16+
h1,
17+
h2,
18+
h3,
19+
h4,
20+
h5,
21+
h6 {
22+
margin-top: 24px;
23+
margin-bottom: 16px;
24+
}
25+
// [github-styles] <code />
26+
code {
27+
padding: 1px 4px;
28+
background: var(--clr-gray--100);
29+
border-radius: 6px;
30+
}
31+
// [github-styles] dividers for h1, h2
32+
h1,
33+
h2 {
34+
padding-bottom: 0.3em;
35+
border-bottom: 1px solid var(--clr-gray--200);
36+
}
37+
// [github-styles] headers font-sizes
38+
h3 {
39+
font-size: 20px;
40+
}
41+
// [github-styles] headers font-sizes
42+
h4 {
43+
font-size: 16px;
44+
}
45+
// [github-styles] for markdown quotes
46+
blockquote {
47+
padding: 0 1em;
48+
color: var(--clr-gray--800);
49+
border-left: 0.25em solid var(--clr-gray--200);
50+
}
51+
// [github-styles] limit images max-width
52+
img {
53+
max-width: 100%;
54+
}
1055
}
1156
}

src/features/repo-explorer/components/readme/index.tsx

Lines changed: 83 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,101 @@
11
import React from "react";
22
import Markdown from "react-markdown";
3+
import gfm from "remark-gfm";
34
import SkeletonArea from "../skeleton-area";
45
import CodeRenderer from "./code-renderer";
56
import "./index.scss";
67

78
type Props = {
9+
/** Текст README файла */
810
text: string;
11+
/** Флаг загрузки */
912
loading: boolean;
13+
/**
14+
* Ссылка-идентификатор репозитория
15+
* @remark Для обработки локальных ссылок
16+
*/
17+
repoUrl: string;
18+
/**
19+
* Текущая ветка
20+
* @remark Для обработки локальных ссылок
21+
*/
22+
branch: string;
1023
};
1124

12-
const RepoReadme = ({ text, loading }: Props) => {
25+
/**
26+
* @hook Обработка внутренних ссылок
27+
* @remark
28+
* - В README могут быть указаны ссылки на локальные ресурсы репозитория (images, files, anchors, ...)
29+
* - Поэтому, для корректной навигации и отображения, было решено предобрабатывать подобные ссылки
30+
*/
31+
const useLocalUri = ({ repoUrl, branch }: Props) => {
32+
/**
33+
* Нормализация внутренних ссылок
34+
* @example
35+
* transformLocalUri("https://some-url/...")
36+
* // => "https://some-url/..."
37+
* transformLocalUri("#some-header")
38+
* // => "https://github.com/${repo}#some-header"
39+
* transformLocalUri("./SOMEFILE.md")
40+
* // => "https://github.com/${repo}/blobk/${branch}/SOMEFILE.md"
41+
* transformLocalUri("docs/ANOTHER.md")
42+
* // => "https://github.com/${repo}/blobk/${branch}/docs/ANOTHER.md"
43+
*/
44+
const transformLinkUri = (uri: string) => {
45+
if (uri.startsWith("http")) return uri;
46+
if (uri.startsWith("#")) return `https://github.com/${repoUrl}${uri}`;
47+
// Если sibling-link - нормализуем
48+
const blobUrl = uri.replace("./", "");
49+
return `https://github.com/${repoUrl}/blob/${branch}/${blobUrl}`;
50+
};
51+
52+
/**
53+
* Получение исходника локального изображения
54+
* FIXME: Работает только с markodwn-изображениями, потом переделать бы на общий случай
55+
* @example
56+
* transformImageUri("docs/search.png")
57+
* // => https://raw.githubusercontent.com/${repo}/${branch}/docs/search.png
58+
*/
59+
const transformImageUri = (uri: string) => {
60+
if (uri.startsWith("http")) return uri;
61+
// Если sibling-link - нормализуем
62+
const blobUrl = uri.replace("./", "");
63+
return `https://raw.githubusercontent.com/${repoUrl}/${branch}/${blobUrl}`;
64+
};
65+
66+
return { transformLinkUri, transformImageUri };
67+
};
68+
69+
/**
70+
* README репозитория
71+
* TODO: Плохо обрабатываются сочетания markdown и html - возможно позже надо завезти отдельный htmlParser
72+
* @see https://github.com/remarkjs/react-markdown
73+
*/
74+
const RepoReadme = (props: Props) => {
75+
const { text, loading } = props;
76+
const uriTransformers = useLocalUri(props);
77+
1378
return (
1479
<div className="repo-readme mt-6">
1580
{loading && <SkeletonArea />}
1681
{text && (
17-
<Markdown className="p-6" allowDangerousHtml renderers={{ code: CodeRenderer }}>
18-
{text}
19-
</Markdown>
82+
<>
83+
{/* TODO: add link */}
84+
<h2 className="repo-readme__title p-4 m-0">README.md</h2>
85+
<Markdown
86+
className="repo-readme__markdown p-8 pt-4"
87+
allowDangerousHtml
88+
renderers={{ code: CodeRenderer }}
89+
/**
90+
* Github Flavored Markdown
91+
* @see https://github.com/remarkjs/react-markdown#use
92+
*/
93+
plugins={[gfm]}
94+
{...uriTransformers}
95+
>
96+
{text}
97+
</Markdown>
98+
</>
2099
)}
21100
</div>
22101
);

0 commit comments

Comments
 (0)