Database and markdown refactoring
This commit is contained in:
parent
fb58a24170
commit
310a4accc4
8
app.vue
8
app.vue
|
|
@ -9,10 +9,6 @@ function hideLeftPanel(_: Event): void {
|
|||
</script>
|
||||
|
||||
<script setup lang="ts">
|
||||
const { data: tags } = await useAsyncData('descriptions', queryContent('/tags').findOne);
|
||||
|
||||
provide('tags/descriptions', tags);
|
||||
|
||||
onMounted(() => {
|
||||
icon = document.querySelector('.site-nav-bar .clickable-icon');
|
||||
icon?.removeEventListener('click', toggleLeftPanel);
|
||||
|
|
@ -37,8 +33,8 @@ onMounted(() => {
|
|||
<NuxtLink @click="hideLeftPanel" class="site-nav-bar-text" aria-label="Accueil" to="/">
|
||||
<ThemeIcon icon="logo" :width=40 :height=40 />
|
||||
</NuxtLink>
|
||||
<NuxtLink class="site-nav-bar-text mobile-hidden" aria-label="Systeme" to="/explorer"
|
||||
:class="{'mod-active': $route.path.startsWith('/explorer')}">Systeme</NuxtLink>
|
||||
<NuxtLink class="site-nav-bar-text mobile-hidden" aria-label="Projets" to="/explorer"
|
||||
:class="{'mod-active': $route.path.startsWith('/explorer')}">Projets</NuxtLink>
|
||||
<NuxtLink class="site-nav-bar-text mobile-hidden" aria-label="Outils" to="/tools"
|
||||
:class="{'mod-active': $route.path.startsWith('/tools')}">Outils</NuxtLink>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -3,22 +3,22 @@ function hideLeftPanel(_: Event)
|
|||
{
|
||||
document?.querySelector('.published-container')?.classList.remove('is-left-column-open');
|
||||
}
|
||||
|
||||
const route = useRoute();
|
||||
|
||||
const project = parseInt(Array.isArray(route.params.projectId) ? '' : route.params.projectId);
|
||||
|
||||
const { data: navigation } = await useFetch(() => isNaN(project) ? '' : `/api/project/${project}/navigation`);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="{'desktop-hidden': !$route.path.startsWith('/explorer')}" class="site-body-left-column">
|
||||
<div class="site-body-left-column">
|
||||
<div class="site-body-left-column-inner">
|
||||
<div class="nav-view-outer">
|
||||
<div class="nav-view">
|
||||
<div class="tree-item">
|
||||
<div class="tree-item-children">
|
||||
<NuxtLink @click="hideLeftPanel" class="site-nav-bar-text desktop-hidden" aria-label="Systeme" :href="'/explorer'"
|
||||
:class="{'mod-active': $route.path.startsWith('/explorer')}">Systeme</NuxtLink>
|
||||
<ContentNavigation v-slot="{ navigation }" queryContent="/">
|
||||
<NavigationLink :class="{'hidden': !$route.path.startsWith('/explorer')}" v-if="!!navigation" v-for="link of navigation.filter(e => !['/tags', '/'].includes(e?._path ?? ''))" :link="link" />
|
||||
</ContentNavigation>
|
||||
<NuxtLink @click="hideLeftPanel" class="site-nav-bar-text desktop-hidden" aria-label="Outils" :href="'/tools'"
|
||||
:class="{'mod-active': $route.path.startsWith('/tools')}">Outils</NuxtLink>
|
||||
<NavigationLink v-if="!!navigation" v-for="link of navigation" :project="project" :link="link" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
<script setup lang="ts">
|
||||
const props = defineProps<{
|
||||
content: string
|
||||
}>();
|
||||
const { data: ast, status } = await useAsyncData(`markdown`, () => parseMarkdown(props.content, {}));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="status === 'pending'" class="loading-circle"></div>
|
||||
<MDCRenderer v-else-if="status === 'success'" :body="ast?.body" :data="ast?.data" />
|
||||
<div v-else>Impossible de traiter le contenu.</div>
|
||||
</template>
|
||||
|
|
@ -3,8 +3,7 @@ const { data: nav } = await useAsyncData('search', () => fetchContentNavigation(
|
|||
const input = ref('');
|
||||
const pos = ref<DOMRect>();
|
||||
|
||||
function getPos(e: Event)
|
||||
{
|
||||
function getPos(e: Event) {
|
||||
pos.value = (e.currentTarget as HTMLElement)?.getBoundingClientRect();
|
||||
}
|
||||
function flatten(val: NavItem[]): NavItem[] {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
<script setup lang="ts">
|
||||
import type { NavItem } from '@nuxt/content';
|
||||
import type { Navigation } from '~/server/api/project/[projectId]/navigation.get';
|
||||
|
||||
interface Props {
|
||||
link: NavItem;
|
||||
link: Navigation;
|
||||
project?: number;
|
||||
}
|
||||
|
||||
const props = defineProps<Props>();
|
||||
|
|
@ -13,15 +14,17 @@ const hasChildren = computed(() => {
|
|||
if(hasChildren.value)
|
||||
{
|
||||
props.link.children?.sort((a, b) => {
|
||||
if(a._path === props.link._path)
|
||||
if(a.order && b.order)
|
||||
return a.order - b.order;
|
||||
if(a.path === props.link.path)
|
||||
return -1;
|
||||
if(b._path === props.link._path)
|
||||
if(b.path === props.link.path)
|
||||
return 1;
|
||||
return 0;
|
||||
});
|
||||
}
|
||||
|
||||
const collapsed = ref(!useRoute().path.startsWith('/explorer' + props.link._path));
|
||||
const collapsed = ref(!useRoute().path.startsWith('/explorer' + props.link.path));
|
||||
|
||||
function hideLeftPanel(_: Event)
|
||||
{
|
||||
|
|
@ -30,7 +33,7 @@ function hideLeftPanel(_: Event)
|
|||
</script>
|
||||
|
||||
<template>
|
||||
<div class="tree-item">
|
||||
<div class="tree-item" v-if="project && !isNaN(project)">
|
||||
<template v-if="hasChildren">
|
||||
<div class="tree-item-self" :class="{ 'is-collapsed': collapsed, 'mod-collapsible is-clickable': hasChildren }" data-path="{{ props.link.title }}" @click="collapsed = hasChildren && !collapsed">
|
||||
<div v-if="hasChildren" class="tree-item-icon collapse-icon">
|
||||
|
|
@ -43,10 +46,10 @@ function hideLeftPanel(_: Event)
|
|||
<div class="tree-item-inner">{{ link.title }}</div>
|
||||
</div>
|
||||
<div v-if="!collapsed" class="tree-item-children">
|
||||
<NavigationLink v-if="hasChildren" v-for="l of link.children" :link="l"/>
|
||||
<NavigationLink v-if="hasChildren" v-for="l of link.children" :link="l" :project="project"/>
|
||||
</div>
|
||||
</template>
|
||||
<NuxtLink @click="hideLeftPanel" v-else class="tree-item-self" :to="'/explorer' + link._path" :active-class="'mod-active'" >
|
||||
<NuxtLink @click="hideLeftPanel" v-else class="tree-item-self" :to="`/explorer/${project}${link.path}`" :active-class="'mod-active'" >
|
||||
<div class="tree-item-inner">{{ link.title }}</div>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -1,26 +1,19 @@
|
|||
<script setup lang="ts">
|
||||
interface Props
|
||||
{
|
||||
toc: Toc;
|
||||
comments?: Comment[];
|
||||
id: number;
|
||||
}
|
||||
const props = defineProps<Props>();
|
||||
|
||||
const { data: comments } = await useFetch(`/api/project/1/file/${props.id}/comment`);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="site-body-right-column">
|
||||
<div v-if="comments !== undefined && comments !== null" class="site-body-right-column">
|
||||
<div class="site-body-right-column-inner">
|
||||
<div v-if="comments !== undefined">
|
||||
<div>
|
||||
{{ comments.length }} commentaire{{ comments.length === 1 ? '' : 's' }}
|
||||
</div>
|
||||
<div v-if="!!toc" class="outline-view-outer node-insert-event">
|
||||
<div class="list-item published-section-header">
|
||||
<span>Sur cette page</span>
|
||||
</div>
|
||||
<div class="outline-view">
|
||||
<TocLink v-for="link of toc.links" :link="link"/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -1,8 +1,7 @@
|
|||
// https://nuxt.com/docs/api/configuration/nuxt-config
|
||||
import CanvasModule from './transformer/canvas/module'
|
||||
|
||||
export default defineNuxtConfig({
|
||||
modules: [CanvasModule, "@nuxt/content", "@nuxtjs/color-mode"],
|
||||
modules: ["@nuxtjs/color-mode", "@nuxtjs/mdc"],
|
||||
css: ['~/assets/common.css', '~/assets/global.css'],
|
||||
runtimeConfig: {
|
||||
dbFile: '',
|
||||
|
|
@ -14,41 +13,13 @@ export default defineNuxtConfig({
|
|||
pathPrefix: false,
|
||||
},
|
||||
],
|
||||
content: {
|
||||
ignores: [
|
||||
'98.Privé'
|
||||
],
|
||||
contentHead: true,
|
||||
markdown: {
|
||||
toc: { depth: 3, searchDepth: 3 },
|
||||
remarkPlugins: [
|
||||
'remark-breaks',
|
||||
'remark-ofm',
|
||||
'remark-mdc',
|
||||
'remark-emoji',
|
||||
'remark-gfm',
|
||||
]
|
||||
mdc: {
|
||||
remarkPlugins: {
|
||||
'remark-breaks': {},
|
||||
'remark-ofm': {}
|
||||
},
|
||||
canvas: {
|
||||
remarkPlugins: [
|
||||
'remark-breaks',
|
||||
'remark-ofm',
|
||||
'remark-mdc',
|
||||
'remark-emoji',
|
||||
'remark-gfm',
|
||||
],
|
||||
},
|
||||
sources: {
|
||||
content: {
|
||||
dir: "",
|
||||
driver: "github",
|
||||
repo: "peaceultime/system-aspect",
|
||||
branch: "master",
|
||||
ttl: 300,
|
||||
token: "0f44a3dd730bc7bb54343566a7d7cb930b40bbdd",
|
||||
apiURL: "https://git.peaceultime.com/api/v1",
|
||||
cdnURL: "https://git.peaceultime.com/",
|
||||
}
|
||||
components: {
|
||||
prose: true,
|
||||
}
|
||||
},
|
||||
compatibilityDate: '2024-07-25'
|
||||
|
|
|
|||
14
package.json
14
package.json
|
|
@ -1,20 +1,18 @@
|
|||
{
|
||||
"devDependencies": {
|
||||
"@nuxt/content": "^2.13.2",
|
||||
"@nuxtjs/color-mode": "^3.4.2",
|
||||
"@nuxtjs/mdc": "^0.8.3",
|
||||
"@types/bun": "^1.1.6",
|
||||
"nuxt": "^3.12.4",
|
||||
"vue": "^3.4.34",
|
||||
"vue-router": "^4.4.0"
|
||||
},
|
||||
"patchedDependencies": {
|
||||
"unstorage@1.10.2": "patches/unstorage@1.10.2.patch",
|
||||
"@nuxt/content@2.13.2": "patches/@nuxt%2Fcontent@2.13.2.patch"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue-router": "^4.4.0",
|
||||
"hast-util-to-html": "^9.0.1",
|
||||
"remark-breaks": "^4.0.0",
|
||||
"remark-ofm": "link:remark-ofm",
|
||||
"zod": "^3.23.8"
|
||||
},
|
||||
"patchedDependencies": {
|
||||
"unstorage@1.10.2": "patches/unstorage@1.10.2.patch",
|
||||
"@nuxt/content@2.13.2": "patches/@nuxt%2Fcontent@2.13.2.patch"
|
||||
}
|
||||
}
|
||||
|
|
@ -1,77 +0,0 @@
|
|||
<script lang="ts">
|
||||
let icon: HTMLDivElement | null;
|
||||
function toggleLeftPanel(_: Event) {
|
||||
icon!.parentElement!.parentElement!.parentElement!.parentElement!.classList.toggle('is-left-column-open');
|
||||
}
|
||||
</script>
|
||||
|
||||
<script setup lang="ts">
|
||||
const { hash, path } = useRoute();
|
||||
const route = path.substring(path.indexOf('/explorer') + '/explorer'.length);
|
||||
|
||||
const { data: page } = await useAsyncData('home', queryContent(route).findOne);
|
||||
const { data: comments } = await useFetch(`/api/comments`, {
|
||||
query: {
|
||||
route: route
|
||||
}
|
||||
});
|
||||
|
||||
if(page.value)
|
||||
{
|
||||
useContentHead(page.value!);
|
||||
}
|
||||
|
||||
const content = ref();
|
||||
|
||||
onMounted(() => {
|
||||
document.querySelectorAll('.callout.is-collapsible .callout-title').forEach(e => {
|
||||
e.addEventListener('click', (_) => {
|
||||
e.parentElement!.classList.toggle('is-collapsed');
|
||||
})
|
||||
})
|
||||
|
||||
document.querySelector(".published-container")?.classList.toggle('is-readable-line-width', !page.value || page.value._type !== 'canvas');
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="site-body-center-column">
|
||||
<div class="render-container">
|
||||
<template v-if="!!page && page._type == 'markdown' && page.body.children.length > 0">
|
||||
<div class="render-container-inner">
|
||||
<div class="publish-renderer">
|
||||
<div class="markdown-preview-view markdown-rendered node-insert-event hide-title">
|
||||
<div class="markdown-preview-sizer markdown-preview-section" style="padding-bottom: 0px;">
|
||||
<h1 v-if="!(page as MarkdownParsedContent).body.children.find((e: MarkdownNode) => e.tag === 'h1')">{{(page as MarkdownParsedContent).title}}</h1>
|
||||
<ContentRenderer :key="page._id" :value="page" />
|
||||
</div>
|
||||
</div>
|
||||
<div class="extra-title">
|
||||
<span class="extra-title-text">Home</span>
|
||||
<span aria-label="Close page" role="button">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="svg-icon lucide-x">
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<RightComponent v-if="page.body?.toc" :toc="page?.body?.toc" :comments="comments" />
|
||||
</template>
|
||||
<CanvasRenderer v-else-if="!!page && page._type == 'canvas'" :key="page._id" :canvas="page" />
|
||||
<div v-else-if="!!page">
|
||||
<div class="not-found-container">
|
||||
<div class="not-found-image"></div>
|
||||
<div class="not-found-title">Impossible d'afficher (ou vide)</div>
|
||||
<div class="not-found-description">Cette page est actuellement vide ou impossible à traiter</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="not-found-container">
|
||||
<div class="not-found-image"></div>
|
||||
<div class="not-found-title">Introuvable</div>
|
||||
<div class="not-found-description">Cette page n'existe pas</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -0,0 +1,44 @@
|
|||
<script setup lang="ts">
|
||||
const route = useRoute();
|
||||
const path = unifySlug(route.params.slug);
|
||||
|
||||
//const dummy = await useFetch(`/api/project`);
|
||||
const { data: content } = await useFetch(`/api/project/${route.params.projectId}/file`, {
|
||||
query: {
|
||||
path: path
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="site-body-center-column">
|
||||
<div class="render-container">
|
||||
<template v-if="!!content && content[0] && content[0].type == 'Markdown' && !!content[0].content">
|
||||
<div class="render-container-inner">
|
||||
<div class="publish-renderer">
|
||||
<div class="markdown-preview-view markdown-rendered node-insert-event hide-title">
|
||||
<div class="markdown-preview-sizer markdown-preview-section" style="padding-bottom: 0px;">
|
||||
<h1>{{ content[0].title }}</h1>
|
||||
<Markdown :content="content[0].content" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<RightComponent :id="content[0].id" />
|
||||
</template>
|
||||
<CanvasRenderer v-else-if="!!content && content[0] && content[0].type == 'Canvas' && !!content[0].content" :canvas="JSON.parse(content[0].content)" />
|
||||
<div v-else-if="!!content && content[0]">
|
||||
<div class="not-found-container">
|
||||
<div class="not-found-image"></div>
|
||||
<div class="not-found-title">Impossible d'afficher (ou vide)</div>
|
||||
<div class="not-found-description">Cette page est actuellement vide ou impossible à traiter</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else class="not-found-container">
|
||||
<div class="not-found-image"></div>
|
||||
<div class="not-found-title">Introuvable</div>
|
||||
<div class="not-found-description">Cette page n'existe pas</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
|
@ -1,25 +0,0 @@
|
|||
import useDatabase from '~/composables/useDatabase';
|
||||
|
||||
export interface Comment
|
||||
{
|
||||
user: number;
|
||||
file: string;
|
||||
position: number;
|
||||
length: number;
|
||||
sequence: number;
|
||||
text: string;
|
||||
}
|
||||
export default defineEventHandler(async (e) => {
|
||||
const query = getQuery(e);
|
||||
|
||||
if(query && query.route !== undefined)
|
||||
{
|
||||
const db = useDatabase();
|
||||
|
||||
const comments = db.query("SELECT * FROM comments WHERE file = ?1").all(query.route as string) as Comment[];
|
||||
|
||||
return comments;
|
||||
}
|
||||
|
||||
setResponseStatus(e, 404);
|
||||
});
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,54 @@
|
|||
import useDatabase from '~/composables/useDatabase';
|
||||
|
||||
export interface File
|
||||
{
|
||||
id: number;
|
||||
path: string;
|
||||
title: string;
|
||||
type: 'Markdown' | 'Canvas' | 'File';
|
||||
content: string;
|
||||
owner: number;
|
||||
}
|
||||
export default defineEventHandler(async (e) => {
|
||||
const project = getRouterParam(e, "projectId");
|
||||
const query = getQuery(e);
|
||||
|
||||
if(!project)
|
||||
{
|
||||
setResponseStatus(e, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
const where = ["project = $project"];
|
||||
const criteria: Record<string, any> = { $project: project };
|
||||
|
||||
if(query && query.path !== undefined)
|
||||
{
|
||||
where.push("path = $path");
|
||||
criteria["$path"] = query.path;
|
||||
}
|
||||
if(query && query.title !== undefined)
|
||||
{
|
||||
where.push("title = $title");
|
||||
criteria["$title"] = query.title;
|
||||
}
|
||||
if(query && query.type !== undefined)
|
||||
{
|
||||
where.push("type = $type");
|
||||
criteria["$type"] = query.type;
|
||||
}
|
||||
|
||||
if(where.length > 1)
|
||||
{
|
||||
const db = useDatabase();
|
||||
|
||||
const content = db.query(`SELECT * FROM explorer_files WHERE ${where.join(" and ")}`).all(criteria) as File[];
|
||||
|
||||
if(content.length > 0)
|
||||
{
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
setResponseStatus(e, 404);
|
||||
});
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import useDatabase from '~/composables/useDatabase';
|
||||
|
||||
export interface Comment
|
||||
{
|
||||
file: number;
|
||||
user_id: number;
|
||||
sequence: number;
|
||||
position: number;
|
||||
length: number;
|
||||
content: string;
|
||||
}
|
||||
export default defineEventHandler(async (e) => {
|
||||
const project = getRouterParam(e, "projectId");
|
||||
const file = getRouterParam(e, "fileId");
|
||||
const query = getQuery(e);
|
||||
|
||||
if(!project)
|
||||
{
|
||||
setResponseStatus(e, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
const where = ["project = $project", "file = $file"];
|
||||
const criteria: Record<string, any> = { $project: project, $file: file };
|
||||
|
||||
if(where.length > 1)
|
||||
{
|
||||
const db = useDatabase();
|
||||
|
||||
const content = db.query(`SELECT * FROM explorer_comments WHERE ${where.join(" and ")}`).all(criteria) as Comment[];
|
||||
|
||||
if(content.length > 0)
|
||||
{
|
||||
return content;
|
||||
}
|
||||
}
|
||||
|
||||
setResponseStatus(e, 404);
|
||||
});
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
import useDatabase from '~/composables/useDatabase';
|
||||
|
||||
export interface Navigation
|
||||
{
|
||||
title: string;
|
||||
path: string;
|
||||
type: string;
|
||||
order: number
|
||||
children?: Navigation[];
|
||||
}
|
||||
export default defineEventHandler(async (e) => {
|
||||
const project = getRouterParam(e, "projectId");
|
||||
|
||||
if(!project)
|
||||
{
|
||||
setResponseStatus(e, 404);
|
||||
return;
|
||||
}
|
||||
|
||||
const db = useDatabase();
|
||||
|
||||
const content = db.query(`SELECT "path", "title", "type", "order" FROM explorer_files WHERE project = ?1 and navigable = 1`).all(project!).sort((a: any, b: any) => a.path.length - b.path.length) as any[];
|
||||
|
||||
if(content.length > 0)
|
||||
{
|
||||
const navigation: Navigation[] = [];
|
||||
|
||||
for(const item of content)
|
||||
addChild(navigation, item);
|
||||
|
||||
return navigation;
|
||||
}
|
||||
|
||||
setResponseStatus(e, 404);
|
||||
});
|
||||
|
||||
function addChild(arr: Navigation[], e: Navigation): void
|
||||
{
|
||||
const parent = arr.find(f => e.path.startsWith(f.path));
|
||||
|
||||
if(parent)
|
||||
{
|
||||
if(!parent.children)
|
||||
parent.children = [];
|
||||
|
||||
addChild(parent.children, e);
|
||||
}
|
||||
else
|
||||
{
|
||||
arr.push({ title: e.title, path: e.path, type: e.type, order: e.order });
|
||||
}
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
import { resolve } from 'path'
|
||||
import { defineNuxtModule } from '@nuxt/kit'
|
||||
|
||||
export default defineNuxtModule({
|
||||
setup(_options, nuxt) {
|
||||
nuxt.options.nitro.externals = nuxt.options.nitro.externals || {}
|
||||
nuxt.options.nitro.externals.inline = nuxt.options.nitro.externals.inline || []
|
||||
nuxt.options.nitro.externals.inline.push(resolve('./transformer/canvas/module'))
|
||||
|
||||
// @ts-ignore
|
||||
nuxt.hook('content:context', (contentContext) => {
|
||||
contentContext.transformers.push(resolve('./transformer/canvas/transformer'))
|
||||
})
|
||||
}
|
||||
})
|
||||
|
|
@ -1,136 +0,0 @@
|
|||
import type { MarkdownOptions, MarkdownPlugin, MarkdownParsedContent } from '@nuxt/content/dist/runtime/types'
|
||||
import { defineTransformer } from '@nuxt/content/transformers'
|
||||
import slugify from 'slugify'
|
||||
import { withoutTrailingSlash, withLeadingSlash } from 'ufo'
|
||||
|
||||
import { parseMarkdown } from '@nuxtjs/mdc/dist/runtime'
|
||||
import { type State } from 'mdast-util-to-hast'
|
||||
import { normalizeUri } from 'micromark-util-sanitize-uri'
|
||||
import { type Properties, type Element } from 'hast'
|
||||
import { type Link } from 'mdast'
|
||||
import { isRelative } from 'ufo'
|
||||
import type { CanvasEdge, CanvasGroup, CanvasNode } from '~/types/canvas'
|
||||
|
||||
export default defineTransformer({
|
||||
name: 'canvas',
|
||||
extensions: ['.canvas'],
|
||||
async parse(_id, rawContent, options) {
|
||||
const config = { ...options } as MarkdownOptions
|
||||
config.rehypePlugins = await importPlugins(config.rehypePlugins)
|
||||
config.remarkPlugins = await importPlugins(config.remarkPlugins)
|
||||
|
||||
await Promise.all(rawContent.nodes?.map(async (e: any) => {
|
||||
if(e.text !== undefined)
|
||||
{
|
||||
e.text = await parseMarkdown(e.text as string, {
|
||||
remark: {
|
||||
plugins: config.remarkPlugins
|
||||
},
|
||||
rehype: {
|
||||
options: {
|
||||
handlers: {
|
||||
link: link as any
|
||||
}
|
||||
},
|
||||
plugins: config.rehypePlugins
|
||||
}
|
||||
})
|
||||
}
|
||||
}));
|
||||
|
||||
rawContent.groups = getGroups(rawContent);
|
||||
|
||||
return {
|
||||
_id,
|
||||
body: rawContent,
|
||||
_type: 'canvas',
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
function contains(group: CanvasNode, node: CanvasNode): boolean
|
||||
{
|
||||
return group.x < node.x && group.y < node.y && group.x + group.width > node.x + node.width && group.y + group.height > node.y + node.height;
|
||||
}
|
||||
function getGroups(content: { nodes: CanvasNode[], edges: CanvasEdge[] }): CanvasGroup[]
|
||||
{
|
||||
const groups = content.nodes.filter(e => e.type === "group");
|
||||
|
||||
return groups.map(group => { return { name: group.label!, nodes: [group.id, ...content.nodes.filter(node => node.type !== "group" && contains(group, node)).map(e => e.id)] }} );
|
||||
}
|
||||
|
||||
async function importPlugins(plugins: Record<string, false | MarkdownPlugin> = {}) {
|
||||
const resolvedPlugins: Record<string, false | MarkdownPlugin & { instance: any }> = {}
|
||||
for (const [name, plugin] of Object.entries(plugins)) {
|
||||
if (plugin) {
|
||||
resolvedPlugins[name] = {
|
||||
instance: plugin.instance || await import(/* @vite-ignore */ name).then(m => m.default || m),
|
||||
options: plugin
|
||||
}
|
||||
} else {
|
||||
resolvedPlugins[name] = false
|
||||
}
|
||||
}
|
||||
return resolvedPlugins
|
||||
}
|
||||
|
||||
function link(state: State, node: Link & { attributes?: Properties }) {
|
||||
const properties: Properties = {
|
||||
...((node.attributes || {})),
|
||||
href: normalizeUri(normalizeLink(node.url))
|
||||
}
|
||||
|
||||
if (node.title !== null && node.title !== undefined) {
|
||||
properties.title = node.title
|
||||
}
|
||||
|
||||
const result: Element = {
|
||||
type: 'element',
|
||||
tagName: 'a',
|
||||
properties,
|
||||
children: state.all(node)
|
||||
}
|
||||
state.patch(node, result)
|
||||
return state.applyData(node, result)
|
||||
}
|
||||
|
||||
function normalizeLink(link: string) {
|
||||
const match = link.match(/#.+$/)
|
||||
const hash = match ? match[0] : ''
|
||||
if (link.replace(/#.+$/, '').endsWith('.md') && (isRelative(link) || (!/^https?/.test(link) && !link.startsWith('/')))) {
|
||||
return (generatePath(link.replace('.md' + hash, ''), { forceLeadingSlash: false }) + hash)
|
||||
} else {
|
||||
return link
|
||||
}
|
||||
}
|
||||
|
||||
const generatePath = (path: string, { forceLeadingSlash = true, respectPathCase = false } = {}): string => {
|
||||
path = path.split('/').map(part => slugify(refineUrlPart(part), { lower: !respectPathCase })).join('/')
|
||||
return forceLeadingSlash ? withLeadingSlash(withoutTrailingSlash(path)) : path
|
||||
}
|
||||
|
||||
const SEMVER_REGEX = /^(\d+)(\.\d+)*(\.x)?$/
|
||||
|
||||
function refineUrlPart(name: string): string {
|
||||
name = name.split(/[/:]/).pop()!
|
||||
// Match 1, 1.2, 1.x, 1.2.x, 1.2.3.x,
|
||||
if (SEMVER_REGEX.test(name)) {
|
||||
return name
|
||||
}
|
||||
|
||||
return (
|
||||
name
|
||||
/**
|
||||
* Remove numbering
|
||||
*/
|
||||
.replace(/(\d+\.)?(.*)/, '$2')
|
||||
/**
|
||||
* Remove index keyword
|
||||
*/
|
||||
.replace(/^index(\.draft)?$/, '')
|
||||
/**
|
||||
* Remove draft keyword
|
||||
*/
|
||||
.replace(/\.draft$/, '')
|
||||
)
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
export function unifySlug(slug: string | string[]): string
|
||||
{
|
||||
return '/' + (Array.isArray(slug) ? slug.join('/') : slug);
|
||||
}
|
||||
Loading…
Reference in New Issue