Skip to content

Commit

Permalink
🔄 synced local 'quartz/' with remote 'quartz/'
Browse files Browse the repository at this point in the history
  • Loading branch information
Mara-Li committed Mar 9, 2024
1 parent 62e37b8 commit 3dfcdce
Show file tree
Hide file tree
Showing 14 changed files with 180 additions and 89 deletions.
6 changes: 6 additions & 0 deletions quartz/cfg.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ export type Analytics =
websiteId: string
host?: string
}
| {
provider: "goatcounter"
websiteId: string
host?: string
scriptSrc?: string
}

export interface GlobalConfiguration {
pageTitle: string
Expand Down
3 changes: 3 additions & 0 deletions quartz/components/Graph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export interface D3Config {
opacityScale: number
removeTags: string[]
showTags: boolean
focusOnHover?: boolean
}

interface GraphOptions {
Expand All @@ -37,6 +38,7 @@ const defaultOptions: GraphOptions = {
opacityScale: 1,
showTags: true,
removeTags: [],
focusOnHover: false,
},
globalGraph: {
drag: true,
Expand All @@ -50,6 +52,7 @@ const defaultOptions: GraphOptions = {
opacityScale: 1,
showTags: true,
removeTags: [],
focusOnHover: true,
},
}

Expand Down
2 changes: 1 addition & 1 deletion quartz/components/PageList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit }: Pr
class="internal tag-link"
href={resolveRelative(fileData.slug!, `tags/${tag}` as FullSlug)}
>
#{tag}
{tag}
</a>
</li>
))}
Expand Down
2 changes: 1 addition & 1 deletion quartz/components/RecentNotes.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export default ((userOpts?: Partial<Options>) => {
class="internal tag-link"
href={resolveRelative(fileData.slug!, `tags/${tag}` as FullSlug)}
>
#{tag}
{tag}
</a>
</li>
))}
Expand Down
3 changes: 1 addition & 2 deletions quartz/components/TagList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@ const TagList: QuartzComponent = ({ fileData, displayClass }: QuartzComponentPro
return (
<ul class={classNames(displayClass, "tags")}>
{tags.map((tag) => {
const display = `#${tag}`
const linkDest = baseDir + `/tags/${slugTag(tag)}`
return (
<li>
<a href={linkDest} class="internal tag-link">
{display}
{tag}
</a>
</li>
)
Expand Down
2 changes: 1 addition & 1 deletion quartz/components/pages/TagContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ const TagContent: QuartzComponent = (props: QuartzComponentProps) => {
<div>
<h2>
<a class="internal tag-link" href={`../tags/${tag}`}>
#{tag}
{tag}
</a>
</h2>
{content && <p>{content}</p>}
Expand Down
24 changes: 15 additions & 9 deletions quartz/components/renderPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ interface RenderComponents {
footer: QuartzComponent
}

const headerRegex = new RegExp(/h[1-6]/)
export function pageResources(
baseDir: FullSlug | RelativeURL,
staticResources: StaticResources,
Expand Down Expand Up @@ -105,18 +106,23 @@ export function renderPage(
// header transclude
blockRef = blockRef.slice(1)
let startIdx = undefined
let startDepth = undefined
let endIdx = undefined
for (const [i, el] of page.htmlAst.children.entries()) {
if (el.type === "element" && el.tagName.match(/h[1-6]/)) {
if (endIdx) {
break
}

if (startIdx !== undefined) {
endIdx = i
} else if (el.properties?.id === blockRef) {
// skip non-headers
if (!(el.type === "element" && el.tagName.match(headerRegex))) continue
const depth = Number(el.tagName.substring(1))

// lookin for our blockref
if (startIdx === undefined || startDepth === undefined) {
// skip until we find the blockref that matches
if (el.properties?.id === blockRef) {
startIdx = i
startDepth = Number(el.tagName.substring(1))
}
} else if (depth <= startDepth) {
// looking for new header that is same level or higher
endIdx = i
}
}

Expand Down Expand Up @@ -203,7 +209,7 @@ export function renderPage(
</div>
)

const lang = componentData.frontmatter?.lang ?? cfg.locale?.split("-")[0] ?? "en"
const lang = componentData.fileData.frontmatter?.lang ?? cfg.locale?.split("-")[0] ?? "en"
const doc = (
<html lang={lang}>
<Head {...componentData} />
Expand Down
29 changes: 22 additions & 7 deletions quartz/components/scripts/graph.inline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
opacityScale,
removeTags,
showTags,
focusOnHover,
} = JSON.parse(graph.dataset["cfg"]!);

const data: Map<SimpleSlug, ContentDetails> = new Map(
Expand Down Expand Up @@ -190,6 +191,8 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
return 2 + Math.sqrt(numLinks);
}

let connectedNodes: SimpleSlug[] = [];

// draw individual nodes
const node = graphNode
.append("circle")
Expand All @@ -203,17 +206,25 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
window.spaNavigate(new URL(targ, window.location.toString()));
})
.on("mouseover", function (_, d) {
const neighbours: SimpleSlug[] = data.get(slug)?.links ?? [];
const neighbourNodes = d3
.selectAll<HTMLElement, NodeData>(".node")
.filter((d) => neighbours.includes(d.id));
const currentId = d.id;
const linkNodes = d3
.selectAll(".link")
.filter((d: any) => d.source.id === currentId || d.target.id === currentId);

// highlight neighbour nodes
neighbourNodes.transition().duration(200).attr("fill", color);
if (focusOnHover) {
// fade out non-neighbour nodes
connectedNodes = linkNodes.data().flatMap((d: any) => [d.source.id, d.target.id]);

d3.selectAll<HTMLElement, NodeData>(".link")
.transition()
.duration(200)
.style("opacity", 0.2);
d3.selectAll<HTMLElement, NodeData>(".node")
.filter((d) => !connectedNodes.includes(d.id))
.transition()
.duration(200)
.style("opacity", 0.2);
}

// highlight links
linkNodes.transition().duration(200).attr("stroke", "var(--gray)").attr("stroke-width", 1);
Expand All @@ -232,6 +243,10 @@ async function renderGraph(container: string, fullSlug: FullSlug) {
.style("font-size", bigFont + "em");
})
.on("mouseleave", function (_, d) {
if (focusOnHover) {
d3.selectAll<HTMLElement, NodeData>(".link").transition().duration(200).style("opacity", 1);
d3.selectAll<HTMLElement, NodeData>(".node").transition().duration(200).style("opacity", 1);
}
const currentId = d.id;
const linkNodes = d3
.selectAll(".link")
Expand Down Expand Up @@ -328,4 +343,4 @@ document.addEventListener("nav", async (e: CustomEventMap["nav"]) => {
const containerIcon = document.getElementById("global-graph-icon");
containerIcon?.addEventListener("click", renderGlobalGraph);
window.addCleanup(() => containerIcon?.removeEventListener("click", renderGlobalGraph));
});
});
9 changes: 9 additions & 0 deletions quartz/plugins/emitters/componentResources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,15 @@ function addGlobalPageResources(
umamiScript.async = true
document.head.appendChild(umamiScript)
`);
} else if (cfg.analytics?.provider === "goatcounter") {
componentResources.afterDOMLoaded.push(`
const goatcounterScript = document.createElement("script")
goatcounterScript.src = "${cfg.analytics.scriptSrc ?? "https://gc.zgo.at/count.js"}"
goatcounterScript.async = true
goatcounterScript.setAttribute("data-goatcounter",
"https://${cfg.analytics.websiteId}.${cfg.analytics.host ?? "goatcounter.com"}/count")
document.head.appendChild(goatcounterScript)
`);
}

Expand Down
2 changes: 1 addition & 1 deletion quartz/plugins/emitters/tagPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ export const TagPage: QuartzEmitterPlugin<Partial<FullPageLayout>> = (userOpts)
const title =
tag === "index"
? i18n(cfg.locale).pages.tagContent.tagIndex
: `${i18n(cfg.locale).pages.tagContent.tag}: #${tag}`
: `${i18n(cfg.locale).pages.tagContent.tag}: ${tag}`
return [
tag,
defaultProcessedContent({
Expand Down
52 changes: 41 additions & 11 deletions quartz/plugins/transformers/description.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,19 @@ import { QuartzTransformerPlugin } from "../types";

export interface Options {
descriptionLength: number
replaceExternalLinks: boolean
}

const defaultOptions: Options = {
descriptionLength: 150,
replaceExternalLinks: true,
};

const urlRegex = new RegExp(
/(https?:\/\/)?(?<domain>([\da-z\.-]+)\.([a-z\.]{2,6})(:\d+)?)(?<path>[\/\w\.-]*)(\?[\/\w\.=&;-]*)?/,
"g",
);

export const Description: QuartzTransformerPlugin<Partial<Options> | undefined> = (userOpts) => {
const opts = { ...defaultOptions, ...userOpts };
return {
Expand All @@ -20,22 +27,45 @@ export const Description: QuartzTransformerPlugin<Partial<Options> | undefined>
return [
() => {
return async (tree: HTMLRoot, file) => {
const frontMatterDescription = file.data.frontmatter?.description;
const text = escapeHTML(toString(tree));
let frontMatterDescription = file.data.frontmatter?.description;
let text = escapeHTML(toString(tree));

if (opts.replaceExternalLinks) {
frontMatterDescription = frontMatterDescription?.replace(
urlRegex,
"$<domain>" + "$<path>",
);
text = text.replace(urlRegex, "$<domain>" + "$<path>");
}

const desc = frontMatterDescription ?? text;
const sentences = desc.replace(/\s+/g, " ").split(".");
let finalDesc = "";
let sentenceIdx = 0;
const sentences = desc.replace(/\s+/g, " ").split(/\.\s/);
const finalDesc: string[] = [];
const len = opts.descriptionLength;
while (finalDesc.length < len) {
const sentence = sentences[sentenceIdx];
if (!sentence) break;
finalDesc += sentence + ".";
sentenceIdx++;
let sentenceIdx = 0;
let currentDescriptionLength = 0;

if (sentences[0] !== undefined && sentences[0].length >= len) {
const firstSentence = sentences[0].split(" ");
while (currentDescriptionLength < len) {
const sentence = firstSentence[sentenceIdx];
if (!sentence) break;
finalDesc.push(sentence);
currentDescriptionLength += sentence.length;
sentenceIdx++;
}
finalDesc.push("...");
} else {
while (currentDescriptionLength < len) {
const sentence = sentences[sentenceIdx];
if (!sentence) break;
const currentSentence = sentence.endsWith(".") ? sentence : sentence + ".";
finalDesc.push(currentSentence);
currentDescriptionLength += currentSentence.length;
}
}

file.data.description = finalDesc;
file.data.description = finalDesc.join(" ");
file.data.text = text;
};
},
Expand Down
1 change: 1 addition & 0 deletions quartz/plugins/transformers/frontmatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ declare module "vfile" {
description: string
publish: boolean
draft: boolean
lang: string
enableToc: string
cssclasses: string[]
order: number
Expand Down
Loading

0 comments on commit 3dfcdce

Please sign in to comment.