From 435e6cf8990c60fb2aad44677373e469747a5aa9 Mon Sep 17 00:00:00 2001 From: Stephen Tse Date: Sat, 3 May 2025 17:41:01 -0700 Subject: [PATCH] Added ability to open image links in new tabs --- quartz.config.ts | 2 +- quartz/plugins/transformers/images.ts | 19 ++++++++++++++----- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/quartz.config.ts b/quartz.config.ts index d3bd90f8d..c53cbfe9a 100644 --- a/quartz.config.ts +++ b/quartz.config.ts @@ -74,7 +74,7 @@ const config: QuartzConfig = { Plugin.CrawlLinks({ markdownLinkResolution: "shortest" }), Plugin.Description(), Plugin.Latex({ renderEngine: "katex" }), - Plugin.Images(), + Plugin.Images({ openLinksInNewTab: true }), ], filters: [Plugin.RemoveDrafts()], emitters: [ diff --git a/quartz/plugins/transformers/images.ts b/quartz/plugins/transformers/images.ts index 8f8b82d77..dda762b40 100644 --- a/quartz/plugins/transformers/images.ts +++ b/quartz/plugins/transformers/images.ts @@ -6,9 +6,16 @@ import { imageExtsToOptimize, previewImageMap, targetOptimizedImageExt } from ". import { FullSlug, getFileExtension, isAbsoluteURL, RelativeURL } from "../../util/path" import { parseSelector } from "hast-util-parse-selector" -export interface Options {} +export interface Options { + /** + * If true, opens image links in a new tab. + */ + openLinksInNewTab: boolean +} -const defaultOptions: Options = {} +const defaultOptions: Options = { + openLinksInNewTab: false, +} /** * File extensions of all supported image format. Files with an extension @@ -34,7 +41,6 @@ export const supportedImageExts: ReadonlySet = new Set([ * Add this plugin after all Markdown parser plugins in quartz.config. */ export const Images: QuartzTransformerPlugin> = (userOpts) => { - //@ts-ignore const opts = { ...defaultOptions, ...userOpts } return { @@ -43,7 +49,7 @@ export const Images: QuartzTransformerPlugin> = (userOpts) => { const plugins: PluggableList = [] if (ctx.cfg.configuration.optimizeImages) { - plugins.push(OptimizeImages) + plugins.push([OptimizeImages, opts]) } return plugins @@ -63,7 +69,7 @@ export const Images: QuartzTransformerPlugin> = (userOpts) => { * * ``` */ -const OptimizeImages: Plugin<[], HtmlRoot> = () => { +const OptimizeImages: Plugin<[Options], HtmlRoot> = (opts: Options) => { const transformer: Transformer = (tree: HtmlRoot) => { visit(tree, "element", (node, index, parent) => { if (node.tagName === "img" && typeof node.properties.src === "string") { @@ -115,6 +121,9 @@ const OptimizeImages: Plugin<[], HtmlRoot> = () => { // Disable SPA router click event that always forces link redirection // (to make image links compatible with lightbox plugins) wrapper.properties["data-router-ignore"] = true + if (opts.openLinksInNewTab) { + wrapper.properties["target"] = "_blank" + } wrapper.children = [node] parent!.children[index!] = wrapper