Jacky Zhao
2023-08-24 953ef29f4e238ef9ae186ab79eeec1bf4f3921a6
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import { slug } from "github-slugger"
// this file must be isomorphic so it can't use node libs (e.g. path)
 
export const QUARTZ = "quartz"
 
/// Utility type to simulate nominal types in TypeScript
type SlugLike<T> = string & { __brand: T }
 
/** Cannot be relative and must have a file extension. */
export type FilePath = SlugLike<"filepath">
export function isFilePath(s: string): s is FilePath {
  const validStart = !s.startsWith(".")
  return validStart && _hasFileExtension(s)
}
 
/** Cannot be relative and may not have leading or trailing slashes. It can have `index` as it's last segment. Use this wherever possible is it's the most 'general' interpretation of a slug. */
export type FullSlug = SlugLike<"full">
export function isFullSlug(s: string): s is FullSlug {
  const validStart = !(s.startsWith(".") || s.startsWith("/"))
  const validEnding = !s.endsWith("/")
  return validStart && validEnding && !_containsForbiddenCharacters(s)
}
 
/** Shouldn't be a relative path and shouldn't have `/index` as an ending or a file extension. It _can_ however have a trailing slash to indicate a folder path. */
export type SimpleSlug = SlugLike<"simple">
export function isSimpleSlug(s: string): s is SimpleSlug {
  const validStart = !(s.startsWith(".") || s.startsWith("/"))
  const validEnding = !(s.endsWith("/index") || s === "index")
  return validStart && !_containsForbiddenCharacters(s) && validEnding && !_hasFileExtension(s)
}
 
/** Can be found on `href`s but can also be constructed for client-side navigation (e.g. search and graph) */
export type RelativeURL = SlugLike<"relative">
export function isRelativeURL(s: string): s is RelativeURL {
  const validStart = /^\.{1,2}/.test(s)
  const validEnding = !(s.endsWith("/index") || s === "index")
  return validStart && validEnding && ![".md", ".html"].includes(_getFileExtension(s) ?? "")
}
 
export function getFullSlug(window: Window): FullSlug {
  const res = window.document.body.dataset.slug! as FullSlug
  return res
}
 
export function slugifyFilePath(fp: FilePath, excludeExt?: boolean): FullSlug {
  fp = _stripSlashes(fp) as FilePath
  let ext = _getFileExtension(fp)
  const withoutFileExt = fp.replace(new RegExp(ext + "$"), "")
  if (excludeExt || [".md", ".html", undefined].includes(ext)) {
    ext = ""
  }
 
  let slug = withoutFileExt
    .split("/")
    .map((segment) => segment.replace(/\s/g, "-").replace(/%/g, "-percent")) // slugify all segments
    .join("/") // always use / as sep
    .replace(/\/$/, "") // remove trailing slash
 
  // treat _index as index
  if (_endsWith(slug, "_index")) {
    slug = slug.replace(/_index$/, "index")
  }
 
  return (slug + ext) as FullSlug
}
 
export function simplifySlug(fp: FullSlug): SimpleSlug {
  return _stripSlashes(_trimSuffix(fp, "index"), true) as SimpleSlug
}
 
export function transformInternalLink(link: string): RelativeURL {
  let [fplike, anchor] = splitAnchor(decodeURI(link))
 
  const folderPath = _isFolderPath(fplike)
  let segments = fplike.split("/").filter((x) => x.length > 0)
  let prefix = segments.filter(_isRelativeSegment).join("/")
  let fp = segments.filter((seg) => !_isRelativeSegment(seg) && seg !== "").join("/")
 
  // manually add ext here as we want to not strip 'index' if it has an extension
  const simpleSlug = simplifySlug(slugifyFilePath(fp as FilePath))
  const joined = joinSegments(_stripSlashes(prefix), _stripSlashes(simpleSlug))
  const trail = folderPath ? "/" : ""
  const res = (_addRelativeToStart(joined) + trail + anchor) as RelativeURL
  return res
}
 
// resolve /a/b/c to ../..
export function pathToRoot(slug: FullSlug): RelativeURL {
  let rootPath = slug
    .split("/")
    .filter((x) => x !== "")
    .slice(0, -1)
    .map((_) => "..")
    .join("/")
 
  if (rootPath.length === 0) {
    rootPath = "."
  }
 
  return rootPath as RelativeURL
}
 
export function resolveRelative(current: FullSlug, target: FullSlug | SimpleSlug): RelativeURL {
  const res = joinSegments(pathToRoot(current), simplifySlug(target as FullSlug)) as RelativeURL
  return res
}
 
export function splitAnchor(link: string): [string, string] {
  let [fp, anchor] = link.split("#", 2)
  anchor = anchor === undefined ? "" : "#" + slugAnchor(anchor)
  return [fp, anchor]
}
 
export function slugAnchor(anchor: string) {
  return slug(anchor)
}
 
export function slugTag(tag: string) {
  return tag
    .split("/")
    .map((tagSegment) => slug(tagSegment))
    .join("/")
}
 
export function joinSegments(...args: string[]): string {
  return args.filter((segment) => segment !== "").join("/")
}
 
export function getAllSegmentPrefixes(tags: string): string[] {
  const segments = tags.split("/")
  const results: string[] = []
  for (let i = 0; i < segments.length; i++) {
    results.push(segments.slice(0, i + 1).join("/"))
  }
  return results
}
 
export interface TransformOptions {
  strategy: "absolute" | "relative" | "shortest"
  allSlugs: FullSlug[]
}
 
export function transformLink(src: FullSlug, target: string, opts: TransformOptions): RelativeURL {
  let targetSlug = transformInternalLink(target)
 
  if (opts.strategy === "relative") {
    return targetSlug as RelativeURL
  } else {
    const folderTail = _isFolderPath(targetSlug) ? "/" : ""
    const canonicalSlug = _stripSlashes(targetSlug.slice(".".length))
    let [targetCanonical, targetAnchor] = splitAnchor(canonicalSlug)
 
    if (opts.strategy === "shortest") {
      // if the file name is unique, then it's just the filename
      const matchingFileNames = opts.allSlugs.filter((slug) => {
        const parts = slug.split("/")
        const fileName = parts.at(-1)
        return targetCanonical === fileName
      })
 
      // only match, just use it
      if (matchingFileNames.length === 1) {
        const targetSlug = matchingFileNames[0]
        return (resolveRelative(src, targetSlug) + targetAnchor) as RelativeURL
      }
    }
 
    // if it's not unique, then it's the absolute path from the vault root
    return (joinSegments(pathToRoot(src), canonicalSlug) + folderTail) as RelativeURL
  }
}
 
function _isFolderPath(fplike: string): boolean {
  return (
    fplike.endsWith("/") ||
    _endsWith(fplike, "index") ||
    _endsWith(fplike, "index.md") ||
    _endsWith(fplike, "index.html")
  )
}
 
function _endsWith(s: string, suffix: string): boolean {
  return s === suffix || s.endsWith("/" + suffix)
}
 
function _trimSuffix(s: string, suffix: string): string {
  if (_endsWith(s, suffix)) {
    s = s.slice(0, -suffix.length)
  }
  return s
}
 
function _containsForbiddenCharacters(s: string): boolean {
  return s.includes(" ") || s.includes("#") || s.includes("?")
}
 
function _hasFileExtension(s: string): boolean {
  return _getFileExtension(s) !== undefined
}
 
function _getFileExtension(s: string): string | undefined {
  return s.match(/\.[A-Za-z0-9]+$/)?.[0]
}
 
function _isRelativeSegment(s: string): boolean {
  return /^\.{0,2}$/.test(s)
}
 
export function _stripSlashes(s: string, onlyStripPrefix?: boolean): string {
  if (s.startsWith("/")) {
    s = s.substring(1)
  }
 
  if (!onlyStripPrefix && s.endsWith("/")) {
    s = s.slice(0, -1)
  }
 
  return s
}
 
function _addRelativeToStart(s: string): string {
  if (s === "") {
    s = "."
  }
 
  if (!s.startsWith(".")) {
    s = joinSegments(".", s)
  }
 
  return s
}