New useContent composable to store global navigation state. Fixes for Markdown and Canvas

This commit is contained in:
Peaceultime 2024-12-30 20:46:24 +01:00
parent 031a51c2fe
commit 9515132659
31 changed files with 320 additions and 220 deletions

View File

@ -5,7 +5,7 @@
<TooltipProvider> <TooltipProvider>
<NuxtLayout> <NuxtLayout>
<div class="xl:px-12 xl:py-8 lg:px-8 lg:py-6 px-6 py-3 flex flex-1 justify-center overflow-auto max-h-full relative"> <div class="xl:px-12 xl:py-8 lg:px-8 lg:py-6 px-6 py-3 flex flex-1 justify-center overflow-auto max-h-full relative">
<NuxtPage></NuxtPage> <NuxtPage />
</div> </div>
</NuxtLayout> </NuxtLayout>
<Toaster v-model="list" /> <Toaster v-model="list" />

BIN
bun.lockb

Binary file not shown.

View File

@ -13,7 +13,7 @@ import type { Root } from 'hast';
const { content, proses, filter } = defineProps<{ const { content, proses, filter } = defineProps<{
content: string content: string
proses?: Array<string | Component> proses?: Record<string, string | Component>
filter?: string filter?: string
}>(); }>();
@ -39,7 +39,7 @@ watch([node], () => {
while(end < node.value.children.length) while(end < node.value.children.length)
{ {
end++; end++;
if(heading(node.value.children[end]) && headingRank(node.value.children[end])! >= rank) if(heading(node.value.children[end]) && headingRank(node.value.children[end])! <= rank)
break; break;
} }
data.value = { ...node.value, children: node.value.children.slice(start, end) }; data.value = { ...node.value, children: node.value.children.slice(start, end) };

View File

@ -1,5 +1,5 @@
<template> <template>
<span :class="{'w-6 h-6 border-4 after:-top-[4px] after:-left-[4px] after:w-6 after:h-6 after:border-4': size === 'normal', 'w-4 h-4 border-2 after:-top-[2px] after:-left-[2px] after:w-4 after:h-4 after:border-2': size === 'small', 'w-12 h-12 border-[6px] after:-top-[6px] after:-left-[6px] after:w-12 after:h-12 after:border-[6px]': size === 'large'}" class="rounded-full border-light-35 dark:border-dark-35 after:block after:relative after:rounded-full after:border-transparent after:border-t-accent-purple after:animate-spin"></span> <span :class="{'w-6 h-6 after:-top-[4px] after:-left-[4px] after:w-6 after:h-6 after:border-4': size === 'normal', 'w-4 h-4 after:-top-[2px] after:-left-[2px] after:w-4 after:h-4 after:border-2': size === 'small', 'w-12 h-12 after:-top-[6px] after:-left-[6px] after:w-12 after:h-12 after:border-[6px]': size === 'large'}" class="after:block after:relative after:rounded-full after:border-transparent after:border-t-accent-purple after:animate-spin"></span>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">

View File

@ -4,7 +4,6 @@ import type { CanvasNode } from '~/types/canvas';
interface Props { interface Props {
node: CanvasNode; node: CanvasNode;
zoom: number;
} }
const props = defineProps<Props>(); const props = defineProps<Props>();
@ -35,16 +34,9 @@ const colors = computed(() => {
<div class="absolute" :style="{transform: `translate(${node.x}px, ${node.y}px)`, width: `${node.width}px`, height: `${node.height}px`, '--canvas-color': node.color?.hex}" :class="{'-z-10': node.type === 'group', 'z-10': node.type !== 'group'}"> <div class="absolute" :style="{transform: `translate(${node.x}px, ${node.y}px)`, width: `${node.width}px`, height: `${node.height}px`, '--canvas-color': node.color?.hex}" :class="{'-z-10': node.type === 'group', 'z-10': node.type !== 'group'}">
<div :class="[colors.border]" class="border-2 bg-light-20 dark:bg-dark-20 overflow-hidden contain-strict w-full h-full flex"> <div :class="[colors.border]" class="border-2 bg-light-20 dark:bg-dark-20 overflow-hidden contain-strict w-full h-full flex">
<div class="w-full h-full py-2 px-4 flex !bg-opacity-[0.07]" :class="colors.bg"> <div class="w-full h-full py-2 px-4 flex !bg-opacity-[0.07]" :class="colors.bg">
<template v-if="node.type === 'group' || zoom > Math.min(0.4, 1000 / size)">
<div v-if="node.text?.length > 0" class="flex items-center"> <div v-if="node.text?.length > 0" class="flex items-center">
<MarkdownRenderer :content="node.text" /> <MarkdownRenderer :content="node.text" />
</div> </div>
</template>
<template v-else>
<div class="flex flex-1 justify-center items-center bg-light-30 dark:bg-dark-30">
<Icon icon="radix-icons:text-align-left" class="w-8 h-8"/>
</div>
</template>
</div> </div>
</div> </div>
<div v-if="node.type === 'group' && node.label !== undefined" :class="[colors.border]" style="max-width: 100%; font-size: calc(18px * var(--zoom-multiplier))" class="origin-bottom-left tracking-wider border-4 truncate inline-block text-light-100 dark:text-dark-100 absolute bottom-[100%] mb-2 px-2 py-1 font-thin">{{ node.label }}</div> <div v-if="node.type === 'group' && node.label !== undefined" :class="[colors.border]" style="max-width: 100%; font-size: calc(18px * var(--zoom-multiplier))" class="origin-bottom-left tracking-wider border-4 truncate inline-block text-light-100 dark:text-dark-100 absolute bottom-[100%] mb-2 px-2 py-1 font-thin">{{ node.label }}</div>

View File

@ -1,7 +1,7 @@
<template> <template>
<div class="absolute top-0 left-0 w-full h-full origin-center pointer-events-none *:pointer-events-auto *:select-none"> <div class="absolute top-0 left-0 w-full h-full origin-center pointer-events-none *:pointer-events-auto *:select-none" v-if="canvas">
<div> <div>
<CanvasNode v-for="node of canvas.nodes" :key="node.id" :node="node" :zoom="zoom" /> <CanvasNode v-for="node of canvas.nodes" :key="node.id" :node="node" />
</div> </div>
<template v-for="edge of canvas.edges"> <template v-for="edge of canvas.edges">
<div :key="edge.id" v-if="edge.label" class="absolute z-10" <div :key="edge.id" v-if="edge.label" class="absolute z-10"
@ -11,17 +11,29 @@
</template> </template>
<svg class="absolute top-0 left-0 overflow-visible w-full h-full origin-top pointer-events-none"> <svg class="absolute top-0 left-0 overflow-visible w-full h-full origin-top pointer-events-none">
<CanvasEdge v-for="edge of canvas.edges" :key="edge.id" <CanvasEdge v-for="edge of canvas.edges" :key="edge.id"
:path="path(getNode(canvas.nodes, edge.fromNode)!, edge.fromSide, getNode(canvas.nodes, edge.toNode)!, edge.toSide)" :path="getPath(getNode(canvas.nodes, edge.fromNode)!, edge.fromSide, getNode(canvas.nodes, edge.toNode)!, edge.toSide)"
:color="edge.color" :label="edge.label" /> :color="edge.color" :label="edge.label" />
</svg> </svg>
</div> </div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
const { canvas, zoom } = defineProps<{ const { path } = defineProps<{
canvas: CanvasContent path: string
zoom: number
}>(); }>();
const { content, get } = useContent();
const overview = computed(() => content.value.find(e => e.path === path));
const loading = ref(false);
if(overview.value && !overview.value.content)
{
loading.value = true;
await get(path);
loading.value = false;
}
const canvas = computed(() => overview.value && overview.value.content ? JSON.parse(overview.value.content) as CanvasContent : undefined);
</script> </script>
<script lang="ts"> <script lang="ts">
@ -71,7 +83,7 @@ function posFromDir(e: { minX: number, minY: number, maxX: number, maxY: number
function getBbox(node: CanvasNode): { minX: number, minY: number, maxX: number, maxY: number } { function getBbox(node: CanvasNode): { minX: number, minY: number, maxX: number, maxY: number } {
return { minX: node.x, minY: node.y, maxX: node.x + node.width, maxY: node.y + node.height }; return { minX: node.x, minY: node.y, maxX: node.x + node.width, maxY: node.y + node.height };
} }
function path(from: CanvasNode, fromSide: 'bottom' | 'top' | 'left' | 'right', to: CanvasNode, toSide: 'bottom' | 'top' | 'left' | 'right'): any { function getPath(from: CanvasNode, fromSide: 'bottom' | 'top' | 'left' | 'right', to: CanvasNode, toSide: 'bottom' | 'top' | 'left' | 'right'): any {
if(from === undefined || to === undefined) if(from === undefined || to === undefined)
{ {
return { return {

View File

@ -7,21 +7,15 @@ function cancelEvent(e: Event)
<script setup lang="ts"> <script setup lang="ts">
import { useDrag, useHover, usePinch, useWheel } from '@vueuse/gesture'; import { useDrag, useHover, usePinch, useWheel } from '@vueuse/gesture';
import type { CanvasContent } from '~/types/canvas';
import { Icon } from '@iconify/vue/dist/iconify.js'; import { Icon } from '@iconify/vue/dist/iconify.js';
import { clamp } from '#shared/general.utils'; import { clamp } from '#shared/general.utils';
type CanvasOverview = any; const { path } = defineProps<{ path: string }>();
const { overview } = defineProps<{
overview: CanvasOverview
}>();
const { data: canvas, status } = await useFetch(`/api/file/content/${encodeURIComponent(overview.path)}`, {
transform: (input) => input && input.content ? JSON.parse(input?.content) as CanvasContent : undefined
});
const { user } = useUserSession(); const { user } = useUserSession();
const isOwner = computed(() => user.value?.id === overview.owner); const { content } = useContent();
const overview = computed(() => content.value.find(e => e.path === path));
const isOwner = computed(() => user.value?.id === overview.value?.owner);
const dispX = ref(0), dispY = ref(0), minZoom = ref(0.1), zoom = ref(0.5); const dispX = ref(0), dispY = ref(0), minZoom = ref(0.1), zoom = ref(0.5);
const canvasRef = useTemplateRef('canvasRef'); const canvasRef = useTemplateRef('canvasRef');
@ -86,7 +80,7 @@ dark:border-dark-purple
*/ */
const cancelEvent = (e: Event) => e.preventDefault() /*const cancelEvent = (e: Event) => e.preventDefault()
useHover(({ hovering }) => { useHover(({ hovering }) => {
if (!hovering) { if (!hovering) {
//@ts-ignore //@ts-ignore
@ -101,32 +95,27 @@ useHover(({ hovering }) => {
document.addEventListener('gesturechange', cancelEvent) document.addEventListener('gesturechange', cancelEvent)
}, { }, {
domTarget: canvasRef, domTarget: canvasRef,
}) });*/
const dragHandler = useDrag(({ delta: [x, y] }: { delta: number[] }) => { const dragHandler = useDrag(({ delta: [x, y] }: { delta: number[] }) => {
dispX.value += x / zoom.value; dispX.value += x / zoom.value;
dispY.value += y / zoom.value; dispY.value += y / zoom.value;
}, { }, {
domTarget: canvasRef, domTarget: canvasRef,
passive: true,
}); });
const wheelHandler = useWheel(({ delta: [x, y] }: { delta: number[] }) => { const wheelHandler = useWheel(({ delta: [x, y] }: { delta: number[] }) => {
zoom.value = clamp(zoom.value + y * -0.001, minZoom.value, 3); zoom.value = clamp(zoom.value + y * -0.001, minZoom.value, 3);
}, { }, {
domTarget: canvasRef, domTarget: canvasRef,
passive: true,
}); });
const pinchHandler = usePinch(({ offset: [z] }: { offset: number[] }) => { const pinchHandler = usePinch(({ offset: [z] }: { offset: number[] }) => {
zoom.value = clamp(z / 2048, minZoom.value, 3); zoom.value = clamp(z / 2048, minZoom.value, 3);
}, { }, {
domTarget: canvasRef, domTarget: canvasRef,
passive: true,
}); });
</script> </script>
<template> <template>
<Loading v-if="status === 'pending'" />
<div v-else-if="canvas">
<div ref="canvasRef" class="absolute top-0 left-0 overflow-hidden w-full h-full touch-none" :style="{ '--zoom-multiplier': (1 / Math.pow(zoom, 0.7)) }"> <div ref="canvasRef" class="absolute top-0 left-0 overflow-hidden w-full h-full touch-none" :style="{ '--zoom-multiplier': (1 / Math.pow(zoom, 0.7)) }">
<div class="flex flex-col absolute sm:top-2 top-10 left-2 z-[35] overflow-hidden gap-4"> <div class="flex flex-col absolute sm:top-2 top-10 left-2 z-[35] overflow-hidden gap-4">
<div class="border border-light-35 dark:border-dark-35 bg-light-10 dark:bg-dark-10"> <div class="border border-light-35 dark:border-dark-35 bg-light-10 dark:bg-dark-10">
@ -153,13 +142,14 @@ const pinchHandler = usePinch(({ offset: [z] }: { offset: number[] }) => {
</div> </div>
<div class="border border-light-35 dark:border-dark-35 bg-light-10 dark:bg-dark-10" v-if="isOwner"> <div class="border border-light-35 dark:border-dark-35 bg-light-10 dark:bg-dark-10" v-if="isOwner">
<Tooltip message="Modifier" side="right"> <Tooltip message="Modifier" side="right">
<NuxtLink :to="{ name: 'explore-edit', hash: '#' + overview.path }" class="w-8 h-8 flex justify-center items-center p-2 hover:bg-light-30 dark:hover:bg-dark-30 cursor-pointer"> <NuxtLink :to="{ name: 'explore-edit', hash: '#' + path }" class="w-8 h-8 flex justify-center items-center p-2 hover:bg-light-30 dark:hover:bg-dark-30 cursor-pointer">
<Icon icon="radix-icons:pencil-1" /> <Icon icon="radix-icons:pencil-1" />
</NuxtLink> </NuxtLink>
</Tooltip> </Tooltip>
</div> </div>
</div> </div>
<CanvasRenderer :style="{transform: `scale(${zoom}) translate(${dispX}px, ${dispY}px)`}" :canvas="canvas" :zoom="zoom" /> <div :style="{transform: `scale(${zoom}) translate(${dispX}px, ${dispY}px)`}" >
<CanvasRenderer :path="path" />
</div> </div>
</div> </div>
</template> </template>

View File

@ -1,26 +1,38 @@
<script setup lang="ts"> <script setup lang="ts">
type MarkdownOverview = any;
const { overview } = defineProps<{ const { path } = defineProps<{
overview: MarkdownOverview path: string
filter?: string,
popover?: boolean
}>(); }>();
const { data: content, status } = await useFetch(`/api/file/content/${encodeURIComponent(overview.path)}`, { watch: [overview] });
const { user } = useUserSession(); const { user } = useUserSession();
const isOwner = computed(() => user.value?.id === overview.owner); const { content, get } = useContent();
const overview = computed(() => content.value.find(e => e.path === path));
const isOwner = computed(() => user.value?.id === overview.value?.owner);
const loading = ref(false);
if(overview.value && !overview.value.content)
{
loading.value = true;
await get(path);
loading.value = false;
}
</script> </script>
<template> <template>
<div class="flex flex-1 justify-start items-start flex-col xl:px-24 md:px-8 px-4 py-6"> <div class="flex flex-1 justify-start items-start flex-col xl:px-24 md:px-8 px-4 py-6">
<Loading v-if="status === 'pending'" /> <Loading v-if="loading" />
<template v-else> <template v-else-if="overview">
<div class="flex flex-1 flex-row justify-between items-center"> <div v-if="!popover" class="flex flex-1 flex-row justify-between items-center">
<ProseH1>{{ overview.title }}</ProseH1> <ProseH1>{{ overview.title }}</ProseH1>
<div class="flex gap-4"> <div class="flex gap-4">
<NuxtLink :href="{ name: 'explore-edit', hash: '#' + overview.path }" v-if="isOwner"><Button>Modifier</Button></NuxtLink> <NuxtLink :href="{ name: 'explore-edit', hash: '#' + overview.path }" v-if="isOwner"><Button>Modifier</Button></NuxtLink>
</div> </div>
</div> </div>
<MarkdownRenderer v-if="content" :content="content.content" /> <MarkdownRenderer v-if="overview.content" :content="overview.content" :filter="filter" />
</template>
<template v-else>
<div><ProseH2>Impossible d'afficher le contenu demandé</ProseH2></div>
</template> </template>
</div> </div>
</template> </template>

View File

@ -1,16 +1,14 @@
<template> <template>
<NuxtLink class="text-accent-blue inline-flex items-center" <NuxtLink class="text-accent-blue inline-flex items-center" :to="overview ? { name: 'explore-path', params: { path: overview.path }, hash: hash } : href" :class="class">
:to="overview ? { name: 'explore-path', params: { path: overview.path }, hash: hash } : href" :class="class"> <HoverCard nuxt-client class="max-w-[600px] max-h-[600px] w-full overflow-auto z-[45]" :class="{'overflow-hidden !p-0': overview?.type === 'canvas'}" :disabled="!overview">
<HoverCard class="max-w-[600px] max-h-[600px] w-full overflow-auto z-[45]" :class="{'overflow-hidden !p-0': overview?.type === 'canvas'}" @open="load" :disabled="!overview">
<template #content> <template #content>
<Loading v-if="loading" /> <Markdown v-if="overview?.type === 'markdown'" class="!px-10" :path="pathname" :filter="hash.substring(1)" popover />
<MarkdownRenderer v-else-if="overview?.type === 'markdown'" class="px-10" :content="content!.content" :filter="hash.substring(1)" /> <template v-else-if="overview?.type === 'canvas'"><div class="w-[600px] h-[600px] relative"><Canvas :path="pathname" /></div></template>
<Canvas v-else-if="overview?.type === 'canvas'" class="w-[600px] h-[600px] relative" :canvas="JSON.parse(content!.content)" />
</template> </template>
<template #default> <span>
<slot v-bind="$attrs"></slot> <slot v-bind="$attrs"></slot>
<Icon class="w-4 h-4 inline-block" v-if="overview && overview.type !== 'markdown'" :icon="iconByType[overview.type]" /> <Icon class="w-4 h-4 inline-block" v-if="overview && overview.type !== 'markdown'" :icon="iconByType[overview.type]" />
</template> </span>
</HoverCard> </HoverCard>
</NuxtLink> </NuxtLink>
</template> </template>
@ -25,37 +23,8 @@ const { href } = defineProps<{
class?: string class?: string
}>(); }>();
const { hash, pathname, protocol } = parseURL(href); const { hash, pathname } = parseURL(href);
const overview = ref<{
path: string;
owner: number;
title: string;
type: "file" | "folder" | "markdown" | "canvas";
navigable: boolean;
private: boolean;
order: number;
visit: number;
}>(), content = ref<{
content: string;
}>(), loading = ref(false), fetched = ref(false);
if(!!pathname && !protocol) const { content } = useContent();
{ const overview = computed(() => content.value.find(e => e.path === pathname));
try {
overview.value = await $fetch(`/api/file/overview/${encodeURIComponent(pathname)}`);
} catch(e) {}
}
async function load()
{
if(fetched.value === true)
return;
fetched.value = true;
loading.value = true;
try {
content.value = await $fetch(`/api/file/content/${encodeURIComponent(pathname)}`);
} catch(e) { }
loading.value = false;
}
</script> </script>

59
composables/useContent.ts Normal file
View File

@ -0,0 +1,59 @@
import type { ExploreContent, ContentComposable, TreeItem } from '~/types/content';
const useContentState = () => useState<ExploreContent[]>('content', () => []);
export function useContent(): ContentComposable {
const contentState = useContentState();
return {
content: contentState,
tree: computed(() => {
const arr: TreeItem[] = [];
for(const element of contentState.value)
{
addChild(arr, element);
}
return arr;
}),
fetch,
get,
}
}
async function fetch(force: boolean) {
const content = useContentState();
if(content.value.length === 0 || force)
content.value = await $fetch('/api/file/overview');
}
async function get(path: string) {
const content = useContentState()
const value = content.value;
const item = value.find(e => e.path === path);
if(item)
{
item.content = await $fetch(`/api/file/content/${encodeURIComponent(path)}`);
}
content.value = value;
}
function addChild(arr: TreeItem[], e: ExploreContent): 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({ ...e });
arr.sort((a, b) => {
if(a.order !== b.order)
return a.order - b.order;
return a.title.localeCompare(b.title);
});
}
}

BIN
db.sqlite

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -89,10 +89,10 @@
<script setup lang="ts"> <script setup lang="ts">
import { Icon } from '@iconify/vue/dist/iconify.js'; import { Icon } from '@iconify/vue/dist/iconify.js';
import type { NavigationTreeItem } from '~/server/api/navigation.get';
import { iconByType } from '#shared/general.utils'; import { iconByType } from '#shared/general.utils';
import type { DropdownOption } from '~/components/base/DropdownMenu.vue'; import type { DropdownOption } from '~/components/base/DropdownMenu.vue';
import { hasPermissions } from '~/shared/auth.util'; import { hasPermissions } from '~/shared/auth.util';
import type { TreeItem } from '~/types/content';
const options = ref<DropdownOption[]>([{ const options = ref<DropdownOption[]>([{
type: 'item', type: 'item',
@ -114,13 +114,10 @@ watch(route, () => {
open.value = false; open.value = false;
}); });
const { data: pages } = await useLazyFetch('/api/navigation', { const { tree } = useContent();
transform: transform, const pages = computed(() => transform(tree.value));
watch: [useRouter().currentRoute] function transform(list: TreeItem[] | undefined): TreeItem[] | undefined
});
function transform(list: NavigationTreeItem[] | undefined): NavigationTreeItem[] | undefined
{ {
return list?.map(e => ({ ...e, open: path.value?.startsWith(e.path), children: transform(e.children) })); return list?.filter(e => e.navigable)?.map(e => ({ ...e, open: path.value?.startsWith(e.path), children: transform(e.children) }));
} }
</script> </script>

View File

@ -34,5 +34,8 @@ export default defineNuxtRouteMiddleware(async (to, from) => {
} }
} }
const { fetch: fetchContent } = useContent();
await fetchContent(false);
return; return;
}); });

View File

@ -157,6 +157,9 @@ export default defineNuxtConfig({
sources: ['/api/__sitemap__/urls'] sources: ['/api/__sitemap__/urls']
}, },
experimental: { experimental: {
componentIslands: {
selectiveClient: true,
},
defaults: { defaults: {
nuxtLink: { nuxtLink: {
prefetchOn: { prefetchOn: {

View File

@ -9,9 +9,9 @@
"dependencies": { "dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^1.4.0", "@atlaskit/pragmatic-drag-and-drop": "^1.4.0",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.0.3", "@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.0.3",
"@iconify/vue": "^4.1.2", "@iconify/vue": "^4.2.0",
"@nuxtjs/color-mode": "^3.5.2", "@nuxtjs/color-mode": "^3.5.2",
"@nuxtjs/sitemap": "^7.0.0", "@nuxtjs/sitemap": "^7.0.1",
"@nuxtjs/tailwindcss": "^6.12.2", "@nuxtjs/tailwindcss": "^6.12.2",
"@vueuse/gesture": "^2.0.0", "@vueuse/gesture": "^2.0.0",
"@vueuse/math": "^11.3.0", "@vueuse/math": "^11.3.0",
@ -26,7 +26,7 @@
"nodemailer": "^6.9.16", "nodemailer": "^6.9.16",
"nuxt": "^3.14.1592", "nuxt": "^3.14.1592",
"nuxt-security": "^2.1.5", "nuxt-security": "^2.1.5",
"radix-vue": "^1.9.10", "radix-vue": "^1.9.11",
"rehype-raw": "^7.0.0", "rehype-raw": "^7.0.0",
"remark-breaks": "^4.0.0", "remark-breaks": "^4.0.0",
"remark-frontmatter": "^5.0.0", "remark-frontmatter": "^5.0.0",
@ -39,15 +39,15 @@
"unist-util-visit": "^5.0.0", "unist-util-visit": "^5.0.0",
"vue": "latest", "vue": "latest",
"vue-router": "latest", "vue-router": "latest",
"zod": "^3.23.8" "zod": "^3.24.1"
}, },
"devDependencies": { "devDependencies": {
"@types/bun": "^1.1.14", "@types/bun": "^1.1.14",
"@types/lodash.capitalize": "^4.2.9", "@types/lodash.capitalize": "^4.2.9",
"@types/nodemailer": "^6.4.17", "@types/nodemailer": "^6.4.17",
"@types/unist": "^3.0.3", "@types/unist": "^3.0.3",
"better-sqlite3": "^11.6.0", "better-sqlite3": "^11.7.0",
"bun-types": "^1.1.38", "bun-types": "^1.1.42",
"drizzle-kit": "^0.26.2", "drizzle-kit": "^0.26.2",
"mdast-util-to-string": "^4.0.0", "mdast-util-to-string": "^4.0.0",
"rehype-stringify": "^10.0.1" "rehype-stringify": "^10.0.1"

View File

@ -40,7 +40,6 @@ async function fetch()
if(schema) if(schema)
{ {
console.log(payload);
const parsedPayload = schema.parse(payload); const parsedPayload = schema.parse(payload);
} }

View File

@ -1,24 +1,12 @@
<template> <template>
<div v-if="status === 'pending'" class="flex"> <div class="flex flex-1 justify-start items-start" v-if="overview">
<Head>
<Title>d[any] - Chargement</Title>
</Head>
<Loading />
</div>
<div class="flex flex-1 justify-start items-start" v-else-if="overview">
<Head> <Head>
<Title>d[any] - {{ overview.title }}</Title> <Title>d[any] - {{ overview.title }}</Title>
</Head> </Head>
<Markdown v-if="overview.type === 'markdown'" :overview="overview" /> <Markdown v-if="overview.type === 'markdown'" :path="path" />
<Canvas v-else-if="overview.type === 'canvas'" :overview="overview" /> <Canvas v-else-if="overview.type === 'canvas'" :path="path" />
<ProseH2 v-else class="flex-1 text-center">Impossible d'afficher le contenu demandé</ProseH2> <ProseH2 v-else class="flex-1 text-center">Impossible d'afficher le contenu demandé</ProseH2>
</div> </div>
<div v-else-if="status === 'error'">
<Head>
<Title>d[any] - Erreur</Title>
</Head>
<span>{{ error?.message }}</span>
</div>
<div v-else> <div v-else>
<Head> <Head>
<Title>d[any] - Erreur</Title> <Title>d[any] - Erreur</Title>
@ -31,5 +19,6 @@
const route = useRouter().currentRoute; const route = useRouter().currentRoute;
const path = computed(() => Array.isArray(route.value.params.path) ? route.value.params.path[0] : route.value.params.path); const path = computed(() => Array.isArray(route.value.params.path) ? route.value.params.path[0] : route.value.params.path);
const { data: overview, status, error } = await useFetch(`/api/file/overview/${encodeURIComponent(path.value)}`, { watch: [route, path], }); const { content } = useContent();
const overview = computed(() => content.value.find(e => e.path === path.value));
</script> </script>

View File

@ -83,7 +83,7 @@
</div> </div>
</div> </div>
<DraggableTree class="ps-4 pe-2 xl:text-base text-sm" <DraggableTree class="ps-4 pe-2 xl:text-base text-sm"
:items="navigation ?? undefined" :get-key="(item: Partial<ProjectExtendedItem>) => item.path !== undefined ? getPath(item as ProjectExtendedItem) : ''" @updateTree="drop" :items="navigation ?? undefined" :get-key="(item: Partial<TreeItemEditable>) => item.path !== undefined ? getPath(item as TreeItemEditable) : ''" @updateTree="drop"
v-model="selected" :defaultExpanded="defaultExpanded" > v-model="selected" :defaultExpanded="defaultExpanded" >
<template #default="{ handleToggle, handleSelect, isExpanded, isSelected, isDragging, item }"> <template #default="{ handleToggle, handleSelect, isExpanded, isSelected, isDragging, item }">
<div class="flex flex-1 items-center px-2 max-w-full pe-4" :class="{ 'opacity-50': isDragging }" :style="{ 'padding-left': `${item.level - 0.5}em` }"> <div class="flex flex-1 items-center px-2 max-w-full pe-4" :class="{ 'opacity-50': isDragging }" :style="{ 'padding-left': `${item.level - 0.5}em` }">
@ -175,20 +175,16 @@
import { Icon } from '@iconify/vue/dist/iconify.js'; import { Icon } from '@iconify/vue/dist/iconify.js';
import type { Instruction } from '@atlaskit/pragmatic-drag-and-drop-hitbox/dist/types/tree-item'; import type { Instruction } from '@atlaskit/pragmatic-drag-and-drop-hitbox/dist/types/tree-item';
import { parsePath } from '#shared/general.utils'; import { parsePath } from '#shared/general.utils';
import type { ProjectItem } from '~/schemas/project'; import type { FileType, TreeItem } from '~/types/content';
import type { FileType } from '~/schemas/file';
import { iconByType } from '#shared/general.utils'; import { iconByType } from '#shared/general.utils';
import FakeA from '~/components/prose/FakeA.vue'; import FakeA from '~/components/prose/FakeA.vue';
interface ProjectExtendedItem extends ProjectItem export interface TreeItemEditable extends TreeItem
{ {
customPath: boolean parent: string;
content?: string name: string;
children?: ProjectExtendedItem[] customPath: boolean;
} children?: TreeItemEditable[];
interface ProjectExtended
{
items: ProjectExtendedItem[]
} }
definePageMeta({ definePageMeta({
@ -202,27 +198,9 @@ const open = ref(true);
const toaster = useToast(); const toaster = useToast();
const saveStatus = ref<'idle' | 'pending' | 'success' | 'error'>('idle'); const saveStatus = ref<'idle' | 'pending' | 'success' | 'error'>('idle');
const { data: project } = await useFetch(`/api/project`, { const { content: complete, tree: project } = useContent();
transform: (project) => { const navigation = ref<TreeItemEditable[]>(transform(JSON.parse(JSON.stringify(project.value)))!);
if(project) const selected = ref<TreeItemEditable>(), edited = ref(false);
(project as ProjectExtended).items = transform(project.items)!;
return project as ProjectExtended;
}
});
const navigation = computed<ProjectExtendedItem[] | undefined>({
get: () => project.value?.items,
set: (value) => {
const proj = project.value;
edited.value = true;
if(proj && value)
proj.items = value;
project.value = proj;
}
});
const selected = ref<ProjectExtendedItem>(), edited = ref(false);
const contentStatus = ref<'idle' | 'pending' | 'success' | 'error'>('idle'), contentError = ref<string>(); const contentStatus = ref<'idle' | 'pending' | 'success' | 'error'>('idle'), contentError = ref<string>();
watch(selected, async (value, old) => { watch(selected, async (value, old) => {
@ -242,7 +220,7 @@ watch(selected, async (value, old) => {
} }
else else
{ {
selected.value.content = (await $fetch(`/api/file/content/${encodeURIComponent(selected.value.path)}`, { query: { type: 'editing'} }))?.content; selected.value.content = (await $fetch(`/api/file/content/${encodeURIComponent(selected.value.path)}`, { query: { type: 'editing'} }));
contentStatus.value = 'success'; contentStatus.value = 'success';
} }
@ -282,7 +260,7 @@ useShortcuts({
}) })
const tree = { const tree = {
remove(data: ProjectExtendedItem[], id: string): ProjectExtendedItem[] { remove(data: TreeItemEditable[], id: string): TreeItemEditable[] {
return data return data
.filter(item => getPath(item) !== id) .filter(item => getPath(item) !== id)
.map((item) => { .map((item) => {
@ -295,7 +273,7 @@ const tree = {
return item; return item;
}); });
}, },
insertBefore(data: ProjectExtendedItem[], targetId: string, newItem: ProjectExtendedItem): ProjectExtendedItem[] { insertBefore(data: TreeItemEditable[], targetId: string, newItem: TreeItemEditable): TreeItemEditable[] {
return data.flatMap((item) => { return data.flatMap((item) => {
if (getPath(item) === targetId) if (getPath(item) === targetId)
return [newItem, item]; return [newItem, item];
@ -309,7 +287,7 @@ const tree = {
return item; return item;
}); });
}, },
insertAfter(data: ProjectExtendedItem[], targetId: string, newItem: ProjectExtendedItem): ProjectExtendedItem[] { insertAfter(data: TreeItemEditable[], targetId: string, newItem: TreeItemEditable): TreeItemEditable[] {
return data.flatMap((item) => { return data.flatMap((item) => {
if (getPath(item) === targetId) if (getPath(item) === targetId)
return [item, newItem]; return [item, newItem];
@ -324,7 +302,7 @@ const tree = {
return item; return item;
}); });
}, },
insertChild(data: ProjectExtendedItem[], targetId: string, newItem: ProjectExtendedItem): ProjectExtendedItem[] { insertChild(data: TreeItemEditable[], targetId: string, newItem: TreeItemEditable): TreeItemEditable[] {
return data.flatMap((item) => { return data.flatMap((item) => {
if (getPath(item) === targetId) { if (getPath(item) === targetId) {
// already a parent: add as first child // already a parent: add as first child
@ -345,7 +323,7 @@ const tree = {
}; };
}); });
}, },
find(data: ProjectExtendedItem[], itemId: string): ProjectExtendedItem | undefined { find(data: TreeItemEditable[], itemId: string): TreeItemEditable | undefined {
for (const item of data) { for (const item of data) {
if (getPath(item) === itemId) if (getPath(item) === itemId)
return item; return item;
@ -357,7 +335,7 @@ const tree = {
} }
} }
}, },
search(data: ProjectExtendedItem[], prop: keyof ProjectExtendedItem, value: string): ProjectExtendedItem[] { search(data: TreeItemEditable[], prop: keyof TreeItemEditable, value: string): TreeItemEditable[] {
const arr = []; const arr = [];
for (const item of data) for (const item of data)
@ -377,7 +355,7 @@ const tree = {
targetId, targetId,
parentIds = [], parentIds = [],
}: { }: {
current: ProjectExtendedItem[] current: TreeItemEditable[]
targetId: string targetId: string
parentIds?: string[] parentIds?: string[]
}): string[] | undefined { }): string[] | undefined {
@ -394,7 +372,7 @@ const tree = {
return nested; return nested;
} }
}, },
hasChildren(item: ProjectExtendedItem): boolean { hasChildren(item: TreeItemEditable): boolean {
return (item.children ?? []).length > 0; return (item.children ?? []).length > 0;
}, },
} }
@ -408,7 +386,7 @@ function add(type: FileType): void
const news = [...tree.search(navigation.value, 'title', 'Nouveau')].filter((e, i, a) => a.indexOf(e) === i); const news = [...tree.search(navigation.value, 'title', 'Nouveau')].filter((e, i, a) => a.indexOf(e) === i);
const title = `Nouveau${news.length > 0 ? ' (' + news.length +')' : ''}`; const title = `Nouveau${news.length > 0 ? ' (' + news.length +')' : ''}`;
const item: ProjectExtendedItem = { navigable: true, private: false, parent: '', path: '', title: title, name: parsePath(title), type: type, order: 0, children: type === 'folder' ? [] : undefined, customPath: false, content: type === 'markdown' ? '' : undefined }; const item: TreeItemEditable = { navigable: true, private: false, parent: '', path: '', title: title, name: parsePath(title), type: type, order: 0, children: type === 'folder' ? [] : undefined, customPath: false, content: type === 'markdown' ? '' : undefined, owner: -1, timestamp: new Date(), visit: 0 };
if(!selected.value) if(!selected.value)
{ {
@ -424,7 +402,7 @@ function add(type: FileType): void
navigation.value = tree.insertAfter(navigation.value, getPath(selected.value), item); navigation.value = tree.insertAfter(navigation.value, getPath(selected.value), item);
} }
} }
function updateTree(instruction: Instruction, itemId: string, targetId: string) : ProjectExtendedItem[] | undefined { function updateTree(instruction: Instruction, itemId: string, targetId: string) : TreeItemEditable[] | undefined {
if(!navigation.value) if(!navigation.value)
return; return;
@ -478,15 +456,25 @@ function updateTree(instruction: Instruction, itemId: string, targetId: string)
return navigation.value; return navigation.value;
} }
function transform(items: ProjectItem[] | undefined): ProjectExtendedItem[] | undefined function transform(items: TreeItem[] | undefined): TreeItemEditable[] | undefined
{ {
return items?.map(e => ({...e, customPath: e.name !== parsePath(e.title), children: transform(e.children)})); return items?.map(e => ({
...e,
parent: e.path.substring(0, e.path.lastIndexOf('/')),
name: e.path.substring(e.path.lastIndexOf('/') + 1),
customPath: e.path.substring(e.path.lastIndexOf('/') + 1) !== parsePath(e.title),
children: transform(e.children)
})) as TreeItemEditable[] | undefined;
}
function flatten(items: TreeItemEditable[] | undefined): TreeItemEditable[]
{
return items?.flatMap(e => [e, ...flatten(e.children)]) ?? [];
} }
function drop(instruction: Instruction, itemId: string, targetId: string) function drop(instruction: Instruction, itemId: string, targetId: string)
{ {
navigation.value = updateTree(instruction, itemId, targetId) ?? navigation.value ?? []; navigation.value = updateTree(instruction, itemId, targetId) ?? navigation.value ?? [];
} }
function rebuildPath(tree: ProjectExtendedItem[] | null | undefined, parentPath: string) function rebuildPath(tree: TreeItemEditable[] | null | undefined, parentPath: string)
{ {
if(!tree) if(!tree)
return; return;
@ -500,9 +488,9 @@ async function save(redirect: boolean): Promise<void>
{ {
saveStatus.value = 'pending'; saveStatus.value = 'pending';
try { try {
await $fetch(`/api/project`, { const result = await $fetch(`/api/project`, {
method: 'post', method: 'post',
body: project.value, body: navigation.value,
}); });
saveStatus.value = 'success'; saveStatus.value = 'success';
edited.value = false; edited.value = false;
@ -513,6 +501,7 @@ async function save(redirect: boolean): Promise<void>
type: 'success', content: 'Contenu enregistré', timer: true, duration: 10000 type: 'success', content: 'Contenu enregistré', timer: true, duration: 10000
}); });
complete.value = result;
if(redirect) router.go(-1); if(redirect) router.go(-1);
} catch(e: any) { } catch(e: any) {
toaster.add({ toaster.add({
@ -521,7 +510,7 @@ async function save(redirect: boolean): Promise<void>
saveStatus.value = 'error'; saveStatus.value = 'error';
} }
} }
function getPath(item: ProjectExtendedItem): string function getPath(item: TreeItemEditable): string
{ {
return [item.parent, parsePath(item.customPath ? item.name : item.title)].filter(e => !!e).join('/'); return [item.parent, parsePath(item.customPath ? item.name : item.title)].filter(e => !!e).join('/');
} }

View File

@ -15,11 +15,9 @@ const baseItem = z.object({
export const item: z.ZodType<ProjectItem> = baseItem.extend({ export const item: z.ZodType<ProjectItem> = baseItem.extend({
children: z.lazy(() => item.array().optional()), children: z.lazy(() => item.array().optional()),
}); });
export const project = z.object({ export const project = z.array(item);
items: z.array(item),
});
export type Project = z.infer<typeof project>; type Project = z.infer<typeof project>;
export type ProjectItem = z.infer<typeof baseItem> & { type ProjectItem = z.infer<typeof baseItem> & {
children?: ProjectItem[] children?: ProjectItem[]
}; };

View File

@ -50,7 +50,7 @@ export default defineEventHandler(async (e) => {
content.content = convertFromStorableLinks(content.content); content.content = convertFromStorableLinks(content.content);
} }
return { content: content.content }; return content.content;
} }
setResponseStatus(e, 404); setResponseStatus(e, 404);

View File

@ -0,0 +1,41 @@
import useDatabase from '~/composables/useDatabase';
import { getTableColumns } from 'drizzle-orm';
import { explorerContentTable } from '~/db/schema';
export default defineEventHandler(async (e) => {
const { user } = await getUserSession(e);
const db = useDatabase();
const { content: _, ...columns } = getTableColumns(explorerContentTable);
const content = db.select(columns).from(explorerContentTable).all();
content.sort((a, b) => {
return a.path.split('/').length - b.path.split('/').length;
});
if(content.length > 0)
{
for(const idx in content)
{
const item = content[idx];
if(!!item.private && (user?.id ?? -1) !== item.owner)
{
delete content[idx];
continue;
}
const parent = item.path.includes('/') ? item.path.substring(0, item.path.lastIndexOf('/')) : undefined;
if(parent && !content.find(e => e && e.path === parent))
{
delete content[idx];
continue;
}
}
return content.filter(e => !!e);
}
setResponseStatus(e, 404);
return;
});

View File

@ -1,9 +1,11 @@
import { hasPermissions } from "#shared/auth.util"; import { hasPermissions } from "#shared/auth.util";
import useDatabase from '~/composables/useDatabase'; import useDatabase from '~/composables/useDatabase';
import { explorerContentTable } from '~/db/schema'; import { explorerContentTable } from '~/db/schema';
import { project, type ProjectItem } from '~/schemas/project'; import { project } from '~/schemas/project';
import { parsePath } from "#shared/general.utils"; import { parsePath } from "#shared/general.utils";
import { eq, getTableColumns, sql } from "drizzle-orm"; import { eq, getTableColumns, sql } from "drizzle-orm";
import type { ExploreContent } from "~/types/content";
import type { TreeItemEditable } from "~/pages/explore/edit/index.vue";
export default defineEventHandler(async (e) => { export default defineEventHandler(async (e) => {
const { user } = await getUserSession(e); const { user } = await getUserSession(e);
@ -20,7 +22,7 @@ export default defineEventHandler(async (e) => {
throw body.error; throw body.error;
} }
const items = buildOrder(body.data.items) as Array<ProjectItem & { match?: number }>; const items = buildOrder(body.data) as Array<TreeItemEditable & { match?: number }>;
const db = useDatabase(); const db = useDatabase();
const { ...cols } = getTableColumns(explorerContentTable); const { ...cols } = getTableColumns(explorerContentTable);
@ -78,6 +80,19 @@ export default defineEventHandler(async (e) => {
tx.delete(explorerContentTable).where(eq(explorerContentTable.path, full[i].path)).run(); tx.delete(explorerContentTable).where(eq(explorerContentTable.path, full[i].path)).run();
} }
}); });
return items.map(e => ({
path: e.path,
owner: e.owner,
title: e.title,
type: e.type,
content: e.content,
navigable: e.navigable,
private: e.private,
order: e.order,
visit: e.visit,
timestamp: e.timestamp,
})) as ExploreContent[];
}); });
function buildOrder(items: ProjectItem[]): ProjectItem[] function buildOrder(items: ProjectItem[]): ProjectItem[]

View File

@ -45,7 +45,6 @@ export default defineEventHandler(async (e) => {
throw body.error; throw body.error;
const db = useDatabase(); const db = useDatabase();
console.log(body.data.oldPassword, await Bun.password.hash(body.data.oldPassword));
const check = db.select({ hash: usersTable.hash }).from(usersTable).where(eq(usersTable.id, session.user.id)).get(); const check = db.select({ hash: usersTable.hash }).from(usersTable).where(eq(usersTable.id, session.user.id)).get();
if(!check || !check.hash) if(!check || !check.hash)

View File

@ -1,6 +1,6 @@
import useDatabase from "~/composables/useDatabase"; import useDatabase from "~/composables/useDatabase";
import { extname, basename } from 'node:path'; import { extname, basename } from 'node:path';
import type { FileType } from '~/types/api'; import type { FileType } from '~/types/content';
import type { CanvasColor, CanvasContent } from "~/types/canvas"; import type { CanvasColor, CanvasContent } from "~/types/canvas";
import { explorerContentTable } from "~/db/schema"; import { explorerContentTable } from "~/db/schema";
import { convertToStorableLinks } from "../api/file.post"; import { convertToStorableLinks } from "../api/file.post";

View File

@ -1,5 +1,5 @@
import useDatabase from "~/composables/useDatabase"; import useDatabase from "~/composables/useDatabase";
import type { FileType } from '~/types/api'; import type { FileType } from '~/types/content';
import { explorerContentTable } from "~/db/schema"; import { explorerContentTable } from "~/db/schema";
import { eq, ne } from "drizzle-orm"; import { eq, ne } from "drizzle-orm";

View File

@ -1,4 +1,4 @@
import type { FileType } from "~/schemas/file"; import type { FileType } from '~/types/content';
export function unifySlug(slug: string | string[]): string export function unifySlug(slug: string | string[]): string
{ {

4
types/api.d.ts vendored
View File

@ -1,3 +1,5 @@
import type { FileType } from '~/types/content';
export interface SuccessHandler export interface SuccessHandler
{ {
success: true; success: true;
@ -25,9 +27,7 @@ export interface Navigation {
children?: Navigation[]; children?: Navigation[];
} }
export type FileMetadata = Record<string, boolean | string | number>; export type FileMetadata = Record<string, boolean | string | number>;
export type FileType = 'markdown' | 'canvas' | 'file' | 'folder';
export interface File { export interface File {
project: number;
path: string; path: string;
owner: number; owner: number;
title: string; title: string;

4
types/auth.d.ts vendored
View File

@ -30,8 +30,8 @@ export interface UserRawData {
} }
export interface UserExtendedData { export interface UserExtendedData {
signin: Date; signin: string;
lastTimestamp: Date; lastTimestamp: string;
logCount: number; logCount: number;
} }

33
types/content.d.ts vendored Normal file
View File

@ -0,0 +1,33 @@
import { explorerContentTable } from "~/db/schema";
import type { CanvasContent } from "./canvas";
export type FileType = typeof explorerContentTable.$inferSelect.type;
export type Overview = Omit<typeof explorerContentTable.$inferSelect, 'content'>;
export type Content = { content: string };
export type ExploreContent= Overview & Partial<Content>;
export type TreeItem = ExploreContent & { children?: TreeItem[] };
export interface ContentComposable {
content: Ref<ExploreContent[]>
tree: ComputedRef<TreeItem[]>
/**
* Fetch the overview of every content from the server.
*/
fetch: (force: boolean) => Promise<void>
/**
* Get the given content from the server.
*/
get: (path: string) => Promise<void>
}
export type MarkdownContent = string;
export type FileContent = any;
export type FolderContent = null;
export interface ContentTypeMap
{
markdown: MarkdownContent;
canvas: CanvasContent;
file: FileContent;
folder: FolderContent;
}