Skip to content

Commit a9e4de3

Browse files
authored
Merge pull request #1263 from vim-jp/feature-hash-redirect
2 parents 00228ee + 28a37eb commit a9e4de3

File tree

3 files changed

+48
-2
lines changed

3 files changed

+48
-2
lines changed

src/components/ArticleInArchive.astro

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,29 @@
11
---
2+
import dayjs from "dayjs";
23
import type { ProcessedArticle } from "@/lib/article.js";
34
import type { SetOptional } from "type-fest";
45
import RunnerImage from "/public/1f3c3.svg";
56
67
type Props = SetOptional<ProcessedArticle, "runner">;
78
8-
const { title, url, originalIndex, runner, runnerPath, published, shortDate } =
9-
Astro.props;
9+
const {
10+
title,
11+
url,
12+
originalIndex,
13+
runner,
14+
runnerPath,
15+
published,
16+
shortDate,
17+
year,
18+
} = Astro.props;
19+
20+
const fullDate = dayjs(shortDate).format("MM-DD");
1021
---
1122

1223
<div class="mb-4 pb-2 [&+div]:border-t">
1324
<div
1425
class:list={["w-full", published && "hover:bg-[#efefef] hover:shadow-md"]}
26+
id={`article-${year}-${fullDate}`}
1527
>
1628
<a href={published ? url : undefined}>
1729
<div class="p-2">

src/lib/hashRedirect.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import * as ufo from "ufo";
2+
import contents from "@/content.json";
3+
import type { Article } from "./type.js";
4+
5+
/** hashの移動先がない場合、archivesへ遷移 */
6+
export const hashRedirect = () => {
7+
const hash = window.location.hash;
8+
9+
if (hash) {
10+
const id = hash.substring(1);
11+
const element = document.getElementById(id);
12+
13+
if (!element) {
14+
if (!/article-[0-9]{4}-[0-9]{2}-[0-9]{2}/.test(id)) {
15+
return;
16+
}
17+
const articles: Article[] = contents.articles;
18+
const hashDate = id.replace("article-", "");
19+
if (!articles.find((x) => x.date === hashDate)) {
20+
return;
21+
}
22+
23+
window.location.href = `${ufo.withTrailingSlash(
24+
ufo.joinURL(import.meta.env.baseURL, "archives"),
25+
)}${hash}`;
26+
}
27+
}
28+
};

src/pages/index.astro

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,9 @@ const newestArticle = getArticles({ isPublished: true }).at(-1);
7272
scroll-behavior: smooth;
7373
}
7474
</style>
75+
76+
<script>
77+
import { hashRedirect } from "@/lib/hashRedirect.js";
78+
document.addEventListener("astro:page-load", () => hashRedirect());
79+
window.addEventListener("hashchange", () => hashRedirect(), false);
80+
</script>

0 commit comments

Comments
 (0)