Skip to content

Commit

Permalink
fix(backlinks): Improve backlink perf and fix aliased backlinks
Browse files Browse the repository at this point in the history
Backlink calculation is quadratic, similar to breadcrumbs before the
fix.

Apply a similar fix here.

Also added alias resolution, so this depends on `file.data.aliases`
from jackyzha0#1681, but that can be commented out easily if needed.
  • Loading branch information
necauqua committed Jan 18, 2025
1 parent 8cf3e30 commit 47b0227
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions quartz/components/Backlinks.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { QuartzComponent, QuartzComponentConstructor, QuartzComponentProps } from "./types"
import style from "./styles/backlinks.scss"
import { resolveRelative, simplifySlug } from "../util/path"
import { FullSlug, resolveRelative, SimpleSlug, simplifySlug } from "../util/path"
import { i18n } from "../i18n"
import { classNames } from "../util/lang"

Expand All @@ -15,14 +15,38 @@ const defaultOptions: BacklinksOptions = {
export default ((opts?: Partial<BacklinksOptions>) => {
const options: BacklinksOptions = { ...defaultOptions, ...opts }

let backlinks: Map<SimpleSlug, Array<{ slug: FullSlug; title: string }>> | undefined

const Backlinks: QuartzComponent = ({
fileData,
allFiles,
displayClass,
cfg,
}: QuartzComponentProps) => {
const slug = simplifySlug(fileData.slug!)
const backlinkFiles = allFiles.filter((file) => file.links?.includes(slug))
if (!backlinks) {
backlinks = new Map()

const aliasMap = new Map<SimpleSlug, SimpleSlug>()
for (const file of allFiles) {
for (const alias of file.aliases ?? []) {
aliasMap.set(simplifySlug(alias), simplifySlug(file.slug!))
}
}

for (const file of allFiles) {
for (let link of file.links ?? []) {
link = aliasMap.get(link) ?? link
let ref = backlinks.get(link)
if (!ref) {
backlinks.set(link, (ref = []))
}
ref.push({ slug: file.slug!, title: file.frontmatter?.title! })
}
}
}

const backlinkFiles = backlinks.get(simplifySlug(fileData.slug!)) ?? []

if (options.hideWhenEmpty && backlinkFiles.length == 0) {
return null
}
Expand All @@ -33,8 +57,8 @@ export default ((opts?: Partial<BacklinksOptions>) => {
{backlinkFiles.length > 0 ? (
backlinkFiles.map((f) => (
<li>
<a href={resolveRelative(fileData.slug!, f.slug!)} class="internal">
{f.frontmatter?.title}
<a href={resolveRelative(fileData.slug!, f.slug)} class="internal">
{f.title}
</a>
</li>
))
Expand Down

0 comments on commit 47b0227

Please sign in to comment.