Создание собственного компонента Quartz

Справка по теме

Проще всего начать с дублирования и модификации уже имеющегося компонента.

Дублируем файл ../quartz/components/ContentMeta.tsx в k0ContentMeta.tsx.

Далее можно поискать все вхождения ContentMeta и внести соответствующие корректировки.

В файле ../quartz/components/index.ts добавляем наш новый компонент (ниже неважные строки пропущены):

Было:

import ContentMeta from "./ContentMeta"

export {
  ContentMeta,
}

Стало:

import ContentMeta from "./ContentMeta"
import k0ContentMeta from "./k0ContentMeta"

export {
  ContentMeta,
  k0ContentMeta,
}

В файле ../quartz.layout.ts меняем старый компонент на новый:

Было:

beforeBody: [
    Component.Breadcrumbs(),
    Component.ArticleTitle(),
    Component.ContentMeta(),
    Component.TagList(),
  ],

export const defaultListPageLayout: PageLayout = {
  beforeBody: [Component.Breadcrumbs(), Component.ArticleTitle(), Component.ContentMeta()],

Стало:

beforeBody: [
    Component.Breadcrumbs(),
    Component.ArticleTitle(),
    Component.k0ContentMeta(),
    Component.TagList(),
  ],

export const defaultListPageLayout: PageLayout = {
  beforeBody: [Component.Breadcrumbs(), Component.ArticleTitle(), Component.k0ContentMeta()],

Теперь можно вносить правки в наш новый компонент ../quartz/components/k0ContentMeta.tsx. Например, [[Quartz 4 post time remover|скрыть отображение даты в начале заметок]].

Оформление Quartz 4

Установка иконки сайта для Quartz 4

Для установки иконки сайта достаточно поменять файл ./quartz/static/icon.png на свой собственный.

Удаление даты у поста в Quartz 4

Дублируем файл ../quartz/components/ContentMeta.tsx в k0ContentMeta.tsx. Далее ищем все вхождения ContentMeta и вносим соответствующие [[Quartz 4 component creation|корректировки]].

Вносим в наш новый компонент ../quartz/components/k0ContentMeta.tsx (или редактируем старый).

Было:

import { formatDate, getDate } from "./Date"
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
import readingTime from "reading-time"
import { classNames } from "../util/lang"
import { i18n } from "../i18n"

interface ContentMetaOptions {
  /**
   * Whether to display reading time
   */
  showReadingTime: boolean
}

const defaultOptions: ContentMetaOptions = {
  showReadingTime: true,
}

export default ((opts?: Partial<ContentMetaOptions>) => {
  // Merge options with defaults
  const options: ContentMetaOptions = { ...defaultOptions, ...opts }

  function ContentMetadata({ cfg, fileData, displayClass }: QuartzComponentProps) {
    const text = fileData.text

    if (text) {
      const segments: string[] = []

      if (fileData.dates) {
        segments.push(formatDate(getDate(cfg, fileData)!, cfg.locale))
      }

      // Display reading time if enabled
      if (options.showReadingTime) {
        const { minutes, words: _words } = readingTime(text)
        const displayedTime = i18n(cfg.locale).components.contentMeta.readingTime({
          minutes: Math.ceil(minutes),
        })
        segments.push(displayedTime)
      }

      return <p class={classNames(displayClass, "content-meta")}>{segments.join(", ")}</p>
    } else {
      return null
    }
  }

  ContentMetadata.css = `
  .content-meta {
    margin-top: 0;
    color: var(--gray);
  }
  `
  return ContentMetadata
}) satisfies QuartzComponentConstructor

Стало:

import { formatDate, getDate } from "./Date"
import { QuartzComponentConstructor, QuartzComponentProps } from "./types"
import readingTime from "reading-time"
import { classNames } from "../util/lang"
import { i18n } from "../i18n"

interface ContentMetaOptions {
  /**
   * Whether to display reading time
   */
  showReadingTime: boolean
}

const defaultOptions: ContentMetaOptions = {
  showReadingTime: true,
}

export default ((opts?: Partial<ContentMetaOptions>) => {
  // Merge options with defaults
  const options: ContentMetaOptions = { ...defaultOptions, ...opts }

  function ContentMetadata({ cfg, fileData, displayClass }: QuartzComponentProps) {
    const text = fileData.text

    if (text) {
      const segments: string[] = []
      
      // k0: Нам не нужна дата
      //if (fileData.dates) {
        //segments.push(formatDate(getDate(cfg, fileData)!, cfg.locale))
      //}

      // Display reading time if enabled
      if (options.showReadingTime) {
        const { minutes, words: _words } = readingTime(text)
        const displayedTime = i18n(cfg.locale).components.contentMeta.readingTime({
          minutes: Math.ceil(minutes),
        })
        segments.push(displayedTime)
      }

      return <p class={classNames(displayClass, "content-meta")}>{segments.join(", ")}</p>
    } else {
      return null
    }
  }

  ContentMetadata.css = `
  .content-meta {
    margin-top: 0;
    color: var(--gray);
  }
  `
  return ContentMetadata
}) satisfies QuartzComponentConstructor

Изменение стиля вывода списка страниц

Нужно отредактировать файл quartz/components/styles/listPage.scss. Для удобства старую версию можно сохранить в quartz/components/styles/listPage_old.scss

Например, можно уменьшить ширину первой колонки (в ней указывается дата).

Было:

@use "../../styles/variables.scss" as *;

ul.section-ul {
  list-style: none;
  margin-top: 2em;
  padding-left: 0;
}

li.section-li {
  margin-bottom: 1em;

  & > .section {
    display: grid;
    grid-template-columns: 6em 3fr 1fr;

    @media all and (max-width: $mobileBreakpoint) {
      & > .tags {
        display: none;
      }
    }

    & > .desc > h3 > a {
      background-color: transparent;
    }

    & > .meta {
      margin: 0;
      flex-basis: 6em;
      opacity: 0.6;
    }
  }
}

// modifications in popover context
.popover .section {
  grid-template-columns: 6em 1fr !important;
  & > .tags {
    display: none;
  }
}

Стало:

@use "../../styles/variables.scss" as *;

ul.section-ul {
  list-style: none;
  margin-top: 2em;
  padding-left: 0;
}

li.section-li {
  margin-bottom: 1em;

  & > .section {
    display: grid;
    grid-template-columns: 1em 2fr 1fr;

    @media all and (max-width: $mobileBreakpoint) {
      & > .tags {
        display: none;
      }
    }

    & > .desc > h3 > a {
      background-color: transparent;
    }

    & > .meta {
      margin: 0;
      flex-basis: 6em;
      opacity: 0.6;
    }
  }
}

// modifications in popover context
.popover .section {
  grid-template-columns: 1em 1fr !important;
  & > .tags {
    display: none;
  }
}

Можно и вовсе не показывать дату, а вместо неё выводить точку:

Для этого файл quartz/components/PageList.tsx сохраним в quartz/components/PageList_old.tsx и отредактируем.

Было:

import { FullSlug, resolveRelative } from "../util/path"
import { QuartzPluginData } from "../plugins/vfile"
import { Date, getDate } from "./Date"
import { QuartzComponent, QuartzComponentProps } from "./types"
import { GlobalConfiguration } from "../cfg"

export function byDateAndAlphabetical(
  cfg: GlobalConfiguration,
): (f1: QuartzPluginData, f2: QuartzPluginData) => number {
  return (f1, f2) => {
    if (f1.dates && f2.dates) {
      // sort descending
      return getDate(cfg, f2)!.getTime() - getDate(cfg, f1)!.getTime()
    } else if (f1.dates && !f2.dates) {
      // prioritize files with dates
      return -1
    } else if (!f1.dates && f2.dates) {
      return 1
    }

    // otherwise, sort lexographically by title
    const f1Title = f1.frontmatter?.title.toLowerCase() ?? ""
    const f2Title = f2.frontmatter?.title.toLowerCase() ?? ""
    return f1Title.localeCompare(f2Title)
  }
}

type Props = {
  limit?: number
} & QuartzComponentProps

export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit }: Props) => {
  let list = allFiles.sort(byDateAndAlphabetical(cfg))
  if (limit) {
    list = list.slice(0, limit)
  }

  return (
    <ul class="section-ul">
      {list.map((page) => {
        const title = page.frontmatter?.title
        const tags = page.frontmatter?.tags ?? []

        return (
          <li class="section-li">
            <div class="section">
              {page.dates && (
                <p class="meta">
                  <Date date={getDate(cfg, page)!} locale={cfg.locale} />
                </p>
              )}
              <div class="desc">
                <h3>
                  <a href={resolveRelative(fileData.slug!, page.slug!)} class="internal">
                    {title}
                  </a>
                </h3>
              </div>
              <ul class="tags">
                {tags.map((tag) => (
                  <li>
                    <a
                      class="internal tag-link"
                      href={resolveRelative(fileData.slug!, `tags/${tag}` as FullSlug)}
                    >
                      {tag}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          </li>
        )
      })}
    </ul>
  )
}

PageList.css = `
.section h3 {
  margin: 0;
}

.section > .tags {
  margin: 0;
}
`

Стало:

import { FullSlug, resolveRelative } from "../util/path"
import { QuartzPluginData } from "../plugins/vfile"
import { Date, getDate } from "./Date"
import { QuartzComponent, QuartzComponentProps } from "./types"
import { GlobalConfiguration } from "../cfg"

export function byDateAndAlphabetical(
  cfg: GlobalConfiguration,
): (f1: QuartzPluginData, f2: QuartzPluginData) => number {
  return (f1, f2) => {
    if (f1.dates && f2.dates) {
      // sort descending
      return getDate(cfg, f2)!.getTime() - getDate(cfg, f1)!.getTime()
    } else if (f1.dates && !f2.dates) {
      // prioritize files with dates
      return -1
    } else if (!f1.dates && f2.dates) {
      return 1
    }

    // otherwise, sort lexographically by title
    const f1Title = f1.frontmatter?.title.toLowerCase() ?? ""
    const f2Title = f2.frontmatter?.title.toLowerCase() ?? ""
    return f1Title.localeCompare(f2Title)
  }
}

type Props = {
  limit?: number
} & QuartzComponentProps

export const PageList: QuartzComponent = ({ cfg, fileData, allFiles, limit }: Props) => {
  let list = allFiles.sort(byDateAndAlphabetical(cfg))
  if (limit) {
    list = list.slice(0, limit)
  }

  return (
    <ul class="section-ul">
      {list.map((page) => {
        const title = page.frontmatter?.title
        const tags = page.frontmatter?.tags ?? []

        return (
          <li class="section-li">
            <div class="section">
              {<p class="meta"></p>}
              <div class="desc">
                <h3>
                  <a href={resolveRelative(fileData.slug!, page.slug!)} class="internal">
                    {title}
                  </a>
                </h3>
              </div>
              <ul class="tags">
                {tags.map((tag) => (
                  <li>
                    <a
                      class="internal tag-link"
                      href={resolveRelative(fileData.slug!, `tags/${tag}` as FullSlug)}
                    >
                      {tag}
                    </a>
                  </li>
                ))}
              </ul>
            </div>
          </li>
        )
      })}
    </ul>
  )
}

PageList.css = `
.section h3 {
  margin: 0;
}

.section > .tags {
  margin: 0;
}
`