nested tag support and tag index page

This commit is contained in:
Jacky Zhao 2023-07-25 21:10:37 -07:00
parent 1ee77893ac
commit dfee2f3b6e
13 changed files with 125 additions and 37 deletions

View File

@ -1,3 +1,8 @@
---
tags:
- plugin/transformer
---
Quartz uses [Katex](https://katex.org/) by default to typeset both inline and block math expressions at build time. Quartz uses [Katex](https://katex.org/) by default to typeset both inline and block math expressions at build time.
## Formatting ## Formatting

View File

@ -1,5 +1,7 @@
--- ---
title: Syntax Highlighting title: Syntax Highlighting
tags:
- plugin/transformer
--- ---
Syntax highlighting in Quartz is completely done at build-time. This means that Quartz only ships pre-calculated CSS to highlight the right words so there is no heavy client-side bundle that does the syntax highlighting. Syntax highlighting in Quartz is completely done at build-time. This means that Quartz only ships pre-calculated CSS to highlight the right words so there is no heavy client-side bundle that does the syntax highlighting.

View File

@ -4,9 +4,7 @@ draft: true
## high priority ## high priority
- local fonts
- images in same folder are broken on shortest path mode - images in same folder are broken on shortest path mode
- https://help.obsidian.md/Editing+and+formatting/Tags#Nested+tags nested tags?? and big tag listing
- watch mode for config/source code - watch mode for config/source code
- https://help.obsidian.md/Editing+and+formatting/Basic+formatting+syntax#Task+lists task list styling - https://help.obsidian.md/Editing+and+formatting/Basic+formatting+syntax#Task+lists task list styling
- publish metadata https://help.obsidian.md/Editing+and+formatting/Metadata#Metadata+for+Obsidian+Publish - publish metadata https://help.obsidian.md/Editing+and+formatting/Metadata#Metadata+for+Obsidian+Publish

View File

@ -20,11 +20,20 @@ function byDateAndAlphabetical(f1: QuartzPluginData, f2: QuartzPluginData): numb
return f1Title.localeCompare(f2Title) return f1Title.localeCompare(f2Title)
} }
export function PageList({ fileData, allFiles }: QuartzComponentProps) { type Props = {
limit?: number
} & QuartzComponentProps
export function PageList({ fileData, allFiles, limit }: Props) {
const slug = canonicalizeServer(fileData.slug!) const slug = canonicalizeServer(fileData.slug!)
let list = allFiles.sort(byDateAndAlphabetical)
if (limit) {
list = list.slice(0, limit)
}
return ( return (
<ul class="section-ul"> <ul class="section-ul">
{allFiles.sort(byDateAndAlphabetical).map((page) => { {list.map((page) => {
const title = page.frontmatter?.title const title = page.frontmatter?.title
const pageSlug = canonicalizeServer(page.slug!) const pageSlug = canonicalizeServer(page.slug!)
const tags = page.frontmatter?.tags ?? [] const tags = page.frontmatter?.tags ?? []

View File

@ -1,6 +1,5 @@
import { canonicalizeServer, pathToRoot } from "../path" import { canonicalizeServer, pathToRoot, slugTag } from "../path"
import { QuartzComponentConstructor, QuartzComponentProps } from "./types" import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
import { slug as slugAnchor } from "github-slugger"
function TagList({ fileData }: QuartzComponentProps) { function TagList({ fileData }: QuartzComponentProps) {
const tags = fileData.frontmatter?.tags const tags = fileData.frontmatter?.tags
@ -11,7 +10,7 @@ function TagList({ fileData }: QuartzComponentProps) {
<ul class="tags"> <ul class="tags">
{tags.map((tag) => { {tags.map((tag) => {
const display = `#${tag}` const display = `#${tag}`
const linkDest = baseDir + `/tags/${slugAnchor(tag)}` const linkDest = baseDir + `/tags/${slugTag(tag)}`
return ( return (
<li> <li>
<a href={linkDest} class="internal tag-link"> <a href={linkDest} class="internal tag-link">

View File

@ -3,33 +3,75 @@ import { Fragment, jsx, jsxs } from "preact/jsx-runtime"
import { toJsxRuntime } from "hast-util-to-jsx-runtime" import { toJsxRuntime } from "hast-util-to-jsx-runtime"
import style from "../styles/listPage.scss" import style from "../styles/listPage.scss"
import { PageList } from "../PageList" import { PageList } from "../PageList"
import { ServerSlug, canonicalizeServer } from "../../path" import { ServerSlug, canonicalizeServer, getAllSegmentPrefixes } from "../../path"
import { QuartzPluginData } from "../../plugins/vfile"
const numPages = 10
function TagContent(props: QuartzComponentProps) { function TagContent(props: QuartzComponentProps) {
const { tree, fileData, allFiles } = props const { tree, fileData, allFiles } = props
const slug = fileData.slug const slug = fileData.slug
if (slug?.startsWith("tags/")) { if (!slug?.startsWith("tags/")) {
const tag = canonicalizeServer(slug.slice("tags/".length) as ServerSlug) throw new Error(`Component "TagContent" tried to render a non-tag page: ${slug}`)
const allPagesWithTag = allFiles.filter((file) => (file.frontmatter?.tags ?? []).includes(tag))
const listProps = {
...props,
allFiles: allPagesWithTag,
} }
const tag = canonicalizeServer(slug.slice("tags/".length) as ServerSlug)
const allPagesWithTag = (tag: string) =>
allFiles.filter((file) =>
(file.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes).includes(tag),
)
// @ts-ignore // @ts-ignore
const content = toJsxRuntime(tree, { Fragment, jsx, jsxs, elementAttributeNameCase: "html" }) const content = toJsxRuntime(tree, { Fragment, jsx, jsxs, elementAttributeNameCase: "html" })
if (tag === "") {
const tags = [...new Set(allFiles.flatMap((data) => data.frontmatter?.tags ?? []))]
const tagItemMap: Map<string, QuartzPluginData[]> = new Map()
for (const tag of tags) {
tagItemMap.set(tag, allPagesWithTag(tag))
}
return ( return (
<div class="popover-hint"> <div class="popover-hint">
<article>{content}</article> <article>{content}</article>
<p>{allPagesWithTag.length} items with this tag.</p> <p>Found {tags.length} total tags.</p>
<div>
{tags.map((tag) => {
const pages = tagItemMap.get(tag)!
const listProps = {
...props,
allFiles: pages,
}
return (
<div>
<h2>
<a class="internal tag-link" href={`./tags/${tag}`}>
#{tag}
</a>
</h2>
<p>{pages.length} items with this tag. {pages.length > numPages && `Showing first ${numPages}.`}</p>
<PageList limit={numPages} {...listProps} />
</div>
)
})}
</div>
</div>
)
} else {
const pages = allPagesWithTag(tag)
const listProps = {
...props,
allFiles: pages,
}
return (
<div class="popover-hint">
<article>{content}</article>
<p>{pages.length} items with this tag.</p>
<div> <div>
<PageList {...listProps} /> <PageList {...listProps} />
</div> </div>
</div> </div>
) )
} else {
throw new Error(`Component "TagContent" tried to render a non-tag page: ${slug}`)
} }
} }

View File

@ -24,7 +24,7 @@
position: relative; position: relative;
width: 30rem; width: 30rem;
max-height: 20rem; max-height: 20rem;
padding: 0 1rem 2rem 1rem; padding: 0 1rem 1rem 1rem;
font-weight: initial; font-weight: initial;
line-height: normal; line-height: normal;
font-size: initial; font-size: initial;

View File

@ -1,4 +1,4 @@
import { slug as slugAnchor } from "github-slugger" import { slug } from "github-slugger"
import { trace } from "./trace" import { trace } from "./trace"
// Quartz Paths // Quartz Paths
@ -197,10 +197,30 @@ export function splitAnchor(link: string): [string, string] {
return [fp, 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 { export function joinSegments(...args: string[]): string {
return args.filter((segment) => segment !== "").join("/") 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 const QUARTZ = "quartz" export const QUARTZ = "quartz"
function _canonicalize(fp: string): string { function _canonicalize(fp: string): string {

View File

@ -160,7 +160,7 @@ export const ComponentResources: QuartzEmitterPlugin<Options> = (opts?: Partial<
content: transform({ content: transform({
filename: "index.css", filename: "index.css",
code: Buffer.from(stylesheet), code: Buffer.from(stylesheet),
minify: true minify: true,
}).code.toString(), }).code.toString(),
}), }),
emit({ emit({

View File

@ -5,7 +5,13 @@ import BodyConstructor from "../../components/Body"
import { pageResources, renderPage } from "../../components/renderPage" import { pageResources, renderPage } from "../../components/renderPage"
import { ProcessedContent, defaultProcessedContent } from "../vfile" import { ProcessedContent, defaultProcessedContent } from "../vfile"
import { FullPageLayout } from "../../cfg" import { FullPageLayout } from "../../cfg"
import { CanonicalSlug, FilePath, ServerSlug, joinSegments } from "../../path" import {
CanonicalSlug,
FilePath,
ServerSlug,
getAllSegmentPrefixes,
joinSegments,
} from "../../path"
export const TagPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => { export const TagPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
if (!opts) { if (!opts) {
@ -26,15 +32,23 @@ export const TagPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
const allFiles = content.map((c) => c[1].data) const allFiles = content.map((c) => c[1].data)
const cfg = ctx.cfg.configuration const cfg = ctx.cfg.configuration
const tags: Set<string> = new Set(allFiles.flatMap((data) => data.frontmatter?.tags ?? [])) const tags: Set<string> = new Set(
allFiles.flatMap((data) => data.frontmatter?.tags ?? []).flatMap(getAllSegmentPrefixes),
)
// add base tag
tags.add("")
const tagDescriptions: Record<string, ProcessedContent> = Object.fromEntries( const tagDescriptions: Record<string, ProcessedContent> = Object.fromEntries(
[...tags].map((tag) => [ [...tags].map((tag) => {
const title = tag === "" ? "Tag Index" : `Tag: #${tag}`
return [
tag, tag,
defaultProcessedContent({ defaultProcessedContent({
slug: `tags/${tag}/index` as ServerSlug, slug: joinSegments("tags", tag, "index") as ServerSlug,
frontmatter: { title: `Tag: ${tag}`, tags: [] }, frontmatter: { title, tags: [] },
}),
]
}), }),
]),
) )
for (const [tree, file] of content) { for (const [tree, file] of content) {
@ -48,7 +62,7 @@ export const TagPage: QuartzEmitterPlugin<FullPageLayout> = (opts) => {
} }
for (const tag of tags) { for (const tag of tags) {
const slug = `tags/${tag}/index` as CanonicalSlug const slug = joinSegments("tags", tag) as CanonicalSlug
const externalResources = pageResources(slug, resources) const externalResources = pageResources(slug, resources)
const [tree, file] = tagDescriptions[tag] const [tree, file] = tagDescriptions[tag]
const componentData: QuartzComponentProps = { const componentData: QuartzComponentProps = {

View File

@ -2,7 +2,7 @@ import matter from "gray-matter"
import remarkFrontmatter from "remark-frontmatter" import remarkFrontmatter from "remark-frontmatter"
import { QuartzTransformerPlugin } from "../types" import { QuartzTransformerPlugin } from "../types"
import yaml from "js-yaml" import yaml from "js-yaml"
import { slug as slugAnchor } from "github-slugger" import { slugTag } from "../../path"
export interface Options { export interface Options {
language: "yaml" | "toml" language: "yaml" | "toml"
@ -43,7 +43,7 @@ export const FrontMatter: QuartzTransformerPlugin<Partial<Options> | undefined>
} }
// slug them all!! // slug them all!!
data.tags = data.tags?.map((tag: string) => slugAnchor(tag)) ?? [] data.tags = data.tags?.map((tag: string) => slugTag(tag)) ?? []
// fill in frontmatter // fill in frontmatter
file.data.frontmatter = { file.data.frontmatter = {

View File

@ -9,7 +9,7 @@ import path from "path"
import { JSResource } from "../../resources" import { JSResource } from "../../resources"
// @ts-ignore // @ts-ignore
import calloutScript from "../../components/scripts/callout.inline.ts" import calloutScript from "../../components/scripts/callout.inline.ts"
import { FilePath, canonicalizeServer, pathToRoot, slugifyFilePath } from "../../path" import { FilePath, canonicalizeServer, pathToRoot, slugTag, slugifyFilePath } from "../../path"
export interface Options { export interface Options {
comments: boolean comments: boolean
@ -337,7 +337,7 @@ export const ObsidianFlavoredMarkdown: QuartzTransformerPlugin<Partial<Options>
return { return {
type: "link", type: "link",
url: base + `/tags/${slugAnchor(tag)}`, url: base + `/tags/${slugTag(tag)}`,
data: { data: {
hProperties: { hProperties: {
className: ["tag-link"], className: ["tag-link"],

View File

@ -60,5 +60,4 @@ ${stylesheet.join("\n\n")}
--highlight: ${theme.colors.darkMode.highlight}; --highlight: ${theme.colors.darkMode.highlight};
} }
` `
} }