Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,22 @@

## [Unreleased]

### Fixed

- Relative images and links now resolve against the repository instead of the
host page's origin. A README using `images/logo.png` renders that image on
any site, not a broken-image icon. Images point at `raw.githubusercontent.com`
and links at the `blob` view, both derived from the README's own download URL,
so a README in a subdirectory or on a non-default branch resolves correctly.
Absolute URLs, in-page anchors and `mailto:` are left alone.
- `rollup -c` builds again. The TypeScript plugin now rejects a `declarationDir`
that sits outside the Rollup output directory, so both bundles share
`dir: "dist"`. Published file paths are unchanged.
- The published package no longer ships declaration files for tests, stories and
the StackBlitz example.
- `jest` runs again. `marked` and its extensions are ESM only and were being
skipped as `node_modules`.

### Added

- Centered README hero, logo (blue Markdown M↓ icon on rounded square), 5 modern badges (incl. Storybook).
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
- Render any Markdown file with **GitHub native styling**
- **Light + dark** modes
- [`marked`](https://github.com/markedjs/marked)-powered with plugins for **GFM alerts**, **heading anchors**, and **fuzzy links**
- Relative images and links resolve back to the repository, so a README written for github.com renders the same anywhere
- Works on both the client and server (SSR-safe)
- TypeScript types included
- Tiny API: one component, two ways to load content
Expand Down
2 changes: 1 addition & 1 deletion dist/cjs/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/cjs/index.js.map

Large diffs are not rendered by default.

11 changes: 0 additions & 11 deletions dist/cjs/types/components/github-readme.d.ts

This file was deleted.

7 changes: 0 additions & 7 deletions dist/cjs/types/components/github-readme.stories.d.ts

This file was deleted.

1 change: 0 additions & 1 deletion dist/cjs/types/components/github-readme.test.d.ts

This file was deleted.

1 change: 0 additions & 1 deletion dist/cjs/types/components/index.d.ts

This file was deleted.

1 change: 0 additions & 1 deletion dist/cjs/types/index.d.ts

This file was deleted.

2 changes: 1 addition & 1 deletion dist/esm/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/esm/index.js.map

Large diffs are not rendered by default.

11 changes: 0 additions & 11 deletions dist/esm/types/components/github-readme.d.ts

This file was deleted.

7 changes: 0 additions & 7 deletions dist/esm/types/components/github-readme.stories.d.ts

This file was deleted.

1 change: 0 additions & 1 deletion dist/esm/types/components/github-readme.test.d.ts

This file was deleted.

1 change: 0 additions & 1 deletion dist/esm/types/components/index.d.ts

This file was deleted.

1 change: 0 additions & 1 deletion dist/esm/types/index.d.ts

This file was deleted.

Binary file added docs/changelog/media/74/after.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added docs/changelog/media/74/before-1.3.3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 6 additions & 1 deletion jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,10 @@ module.exports = {
testEnvironment: 'jsdom',
moduleNameMapper: {
'.(css|less|scss)$': 'identity-obj-proxy'
}
},
// marked and its extensions ship ESM only, so they have to go through babel
// rather than being skipped as node_modules.
transformIgnorePatterns: [
'/node_modules/(?!(marked|marked-alert|marked-gfm-heading-id|marked-linkify-it|linkify-it|uc\\.micro)/)'
]
}
11 changes: 8 additions & 3 deletions rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,19 @@ import packageJson from "./package.json" with { type: "json" };
export default [
{
input: "src/index.ts",
// Both outputs share `dir: "dist"` so that the single typescript plugin
// instance has one declarationDir inside both of them. The published file
// paths are unchanged.
output: [
{
file: packageJson.main,
dir: "dist",
entryFileNames: packageJson.main.replace(/^dist\//, ""),
format: "cjs",
sourcemap: true,
},
{
file: packageJson.module,
dir: "dist",
entryFileNames: packageJson.module.replace(/^dist\//, ""),
format: "esm",
sourcemap: true,
},
Expand All @@ -33,7 +38,7 @@ export default [
],
},
{
input: "dist/esm/types/src/index.d.ts",
input: "dist/types/index.d.ts",
output: [{ file: "dist/index.d.ts", format: "esm" }],
plugins: [dts()],
external: [/\.s?css$/],
Expand Down
66 changes: 66 additions & 0 deletions src/components/github-readme.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,70 @@ describe('GitHubReadme', () => {
global.fetch = originalFetch
}
})
// Regression test for https://github.com/lacymorrow/react-github-readme-md/issues/7
// A README rendered off github.com must point its relative images and links
// back at the repository instead of the host page's origin.
test('resolves relative images and links against the repository', async () => {
const markdown = [
'<p align="center">',
' <img src="images/logo.png" alt="Logo" width="128">',
'</p>',
'',
'![Demo](images/demo.gif)',
'',
'[![Badge](https://img.shields.io/badge.svg)](https://example.com)',
'',
'[Contributing](CONTRIBUTING.md)',
].join('\n')

const originalFetch = global.fetch
global.fetch = jest.fn((input: RequestInfo | URL) => {
const url = typeof input === 'string' ? input : input.toString()
if (new URL(url).hostname === 'api.github.com') {
return Promise.resolve(
new Response(
JSON.stringify({
path: 'README.md',
download_url:
'https://raw.githubusercontent.com/lacymorrow/vscode-if-end-marker/main/README.md',
}),
{ status: 200, headers: { 'Content-Type': 'application/json' } }
)
)
}
return Promise.resolve(new Response(markdown, { status: 200 }))
}) as jest.Mock

try {
const { container } = render(
<GitHubReadme username="lacymorrow" repo="vscode-if-end-marker" />
)

await waitFor(() => {
expect(container.querySelector('img')).not.toBeNull()
})

const sources = Array.from(container.querySelectorAll('img')).map((img) =>
img.getAttribute('src')
)
expect(sources).toContain(
'https://raw.githubusercontent.com/lacymorrow/vscode-if-end-marker/main/images/logo.png'
)
expect(sources).toContain(
'https://raw.githubusercontent.com/lacymorrow/vscode-if-end-marker/main/images/demo.gif'
)
// Absolute badge URLs are untouched.
expect(sources).toContain('https://img.shields.io/badge.svg')

const hrefs = Array.from(container.querySelectorAll('a')).map((a) =>
a.getAttribute('href')
)
expect(hrefs).toContain(
'https://github.com/lacymorrow/vscode-if-end-marker/blob/main/CONTRIBUTING.md'
)
expect(hrefs).toContain('https://example.com')
} finally {
global.fetch = originalFetch
}
})
})
41 changes: 31 additions & 10 deletions src/components/github-readme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import { gfmHeadingId } from "marked-gfm-heading-id";
import markedLinkifyIt from "marked-linkify-it";
import markedAlert from "marked-alert";

import {
buildReadmeBase,
rewriteRelativeUrls,
type ReadmeBase,
} from "./relative-urls";

import "./github-readme.scss";

type Props = {
Expand Down Expand Up @@ -42,7 +48,10 @@ const GitHubReadme: React.FC<Props> = ({
linkify = false,
theme = "auto",
}) => {
const [readmeContent, setReadmeContent] = useState<string>("");
const [readme, setReadme] = useState<{
markdown: string;
base?: ReadmeBase;
}>({ markdown: "" });

useEffect(() => {
if (!src && !username && !repo) {
Expand All @@ -63,6 +72,8 @@ const GitHubReadme: React.FC<Props> = ({
const fetchReadme = async () => {
try {
let readmeUrl = src;
// Repo-relative path of the README, used to find the repository root.
let readmePath: string | undefined;
if (!readmeUrl) {
const apiRes = await fetch(
`https://api.github.com/repos/${username}/${repo}/readme`
Expand All @@ -72,15 +83,17 @@ const GitHubReadme: React.FC<Props> = ({
`Failed to look up README (${apiRes.status} ${apiRes.statusText})`
);
}
const data: unknown = await apiRes.json();
const downloadUrl =
data && typeof data === "object" && "download_url" in data
? (data as { download_url: unknown }).download_url
: undefined;
const body: unknown = await apiRes.json();
const data: Record<string, unknown> =
body && typeof body === "object"
? (body as Record<string, unknown>)
: {};
const downloadUrl = data.download_url;
if (typeof downloadUrl !== "string" || !downloadUrl) {
throw new Error("README response missing download_url");
}
readmeUrl = downloadUrl;
readmePath = typeof data.path === "string" ? data.path : undefined;
}

const response = await fetch(readmeUrl);
Expand All @@ -89,8 +102,13 @@ const GitHubReadme: React.FC<Props> = ({
`Failed to fetch README (${response.status} ${response.statusText})`
);
}
const data = await response.text();
if (!cancelled && data) setReadmeContent(data);
const markdown = await response.text();
if (!cancelled && markdown) {
setReadme({
markdown,
base: buildReadmeBase(readmeUrl, readmePath),
});
}
} catch (error) {
console.error("react-github-readme-md:", error);
}
Expand All @@ -102,11 +120,14 @@ const GitHubReadme: React.FC<Props> = ({
};
}, [username, repo, src]);

if (!readmeContent) return null;
if (!readme.markdown) return null;

try {
const parser = getParser(addHeadingIds, linkify);
const ghContent = parser.parse(readmeContent) as string;
const parsed = parser.parse(readme.markdown) as string;
const ghContent = readme.base
? rewriteRelativeUrls(parsed, readme.base)
: parsed;
return (
<div className={`github-readme-md ${className ? className : ""}`}>
<div
Expand Down
Loading
Loading