UNPKG

@nolebase/vitepress-plugin-page-properties

Version:

A VitePress plugin that renders frontmatter as page properties, and makes them editable.

68 lines (67 loc) 2.74 kB
import VirtualPagePropertiesData from "virtual:nolebase-page-properties"; import { computed, ref, toValue } from "vue"; function normalizeProperties(frontmatter, propertyConfig, calculatedPropertiesActualData) { const { key } = propertyConfig; const baseResolvedProperties = { key: "unknown", pageProperty: propertyConfig, value: "", omitEmpty: true }; if (propertyConfig.type === "dynamic") { if (propertyConfig.key) baseResolvedProperties.key = propertyConfig.key; else baseResolvedProperties.key = propertyConfig.type; baseResolvedProperties.value = calculatedPropertiesActualData || ""; baseResolvedProperties.omitEmpty = false; return baseResolvedProperties; } if (!key) return baseResolvedProperties; baseResolvedProperties.key = propertyConfig.key; if ("omitEmpty" in propertyConfig) baseResolvedProperties.omitEmpty = !!propertyConfig.omitEmpty; if (!Object.keys(frontmatter).length || !frontmatter[String(key)]) return baseResolvedProperties; baseResolvedProperties.value = frontmatter[String(key)]; return baseResolvedProperties; } export function usePageProperties(pageData, userConfiguredPageProperties) { const pagePropertiesData = ref({ ...VirtualPagePropertiesData }); if (!pagePropertiesData.value) pagePropertiesData.value = {}; return { config: computed(() => { if (!userConfiguredPageProperties.value || !userConfiguredPageProperties.value.length) return []; const currentPath = toValue(pageData.value.filePath).toLowerCase(); const matchedPagePropertiesForCurrentPath = pagePropertiesData.value[currentPath]; if (!matchedPagePropertiesForCurrentPath || !Object.keys(matchedPagePropertiesForCurrentPath).length) return []; const mPageProperties = userConfiguredPageProperties.value.map((item) => normalizeProperties( pageData.value.frontmatter, item, matchedPagePropertiesForCurrentPath )); return mPageProperties.filter((item) => { if (item.omitEmpty && !item.value) return false; return true; }); }), data: computed(() => { const currentPath = toValue(pageData.value.filePath).toLowerCase(); const matchedPagePropertiesForCurrentPath = pagePropertiesData.value[currentPath]; if (!matchedPagePropertiesForCurrentPath || !Object.keys(matchedPagePropertiesForCurrentPath).length) return { readingTime: 0, wordsCount: 0 }; return { readingTime: matchedPagePropertiesForCurrentPath.readingTime || 0, wordsCount: matchedPagePropertiesForCurrentPath.wordsCount || 0 }; }), update(data) { pagePropertiesData.value = { ...data }; } }; }