-
Notifications
You must be signed in to change notification settings - Fork 1
/
parseLink.ts
37 lines (36 loc) · 1.11 KB
/
parseLink.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
export interface ScrapboxLink {
href: string;
pathType: "root" | "relative";
}
/** Scrapbox記法のリンクから、project, title, hashを取り出す
*
* @param link 構文解析したScrapbox記法のリンク
* @return 抽出したproject, title, hash
*/
export const parseLink = (
link: ScrapboxLink,
): { project: string; title?: string; hash?: string } | {
project?: string;
title: string;
hash?: string;
} => {
if (link.pathType === "root") {
const [, project = "", title = ""] = link.href.match(
/\/([\w\-]+)(?:\/?|\/(.*))$/,
) ?? ["", "", ""];
if (project === "") {
throw SyntaxError(`Failed to get a project name from "${link.href}"`);
}
const [, hash] = title?.match?.(/#([a-f\d]{24,32})$/) ?? ["", ""];
return title === ""
? { project }
: hash === ""
? { project, title }
: { project, title: title.slice(0, -1 - hash.length), hash };
} else {
const [, hash] = link.href.match(/#([a-f\d]{24,32})$/) ?? ["", ""];
return hash === ""
? { title: link.href }
: { title: link.href.slice(0, -1 - hash.length), hash };
}
};