22 Commits

Author SHA1 Message Date
5fb708051b Small fixes 2024-11-29 23:52:57 +01:00
9a69a92ef8 Build fixes 2024-11-26 16:49:07 +01:00
f22e63bd4d Small fixes 2024-11-26 16:38:58 +01:00
e83d8e802f Add revalidation email 2024-11-26 16:23:33 +01:00
3e463ea286 Switch pull and push to make more sense 2024-11-26 15:29:31 +01:00
4125cbb3a2 Send registration email, add mail validation page, stabilize mail generation 2024-11-26 15:22:57 +01:00
4df9297d47 Add mail template, mail HTML generation and a few UI fixes 2024-11-25 17:37:43 +01:00
d71e8b7910 Small UI improvements and fixes to project edition 2024-11-28 00:01:57 +01:00
20ab51a66c Visual edits and fixes, navigation sorting fix 2024-11-23 19:18:50 +01:00
2855d4ba2e Add deletion of files, add slots to tree and a global icon by type. Project update needs rework. 2024-11-20 22:51:51 +01:00
4f2fc31695 Add new files in project config 2024-11-20 17:36:33 +01:00
6e7243982b Small progress on new (file/folder) and remove in project settings 2024-11-19 23:30:43 +01:00
9c52494f8e Mail sending ready 2024-11-19 18:07:48 +01:00
d0de943df2 Starting to setup emails 2024-11-19 00:37:41 +01:00
1c239f161b Finished project configuration page with reorder 2024-11-18 17:21:52 +01:00
a9363e8c06 Progressing on the draggable tree for the project configuration 2024-11-18 00:10:23 +01:00
d708e9ceb6 Finish Dropdown menu and start project config page 2024-11-14 17:32:13 +01:00
0c17dbf7bc Merge branch 'dev' of https://git.peaceultime.com/Peaceultime/obsidian-visualiser into dev 2024-11-13 13:41:35 +01:00
ac17134b7e Add title to every pages + new pull/push jobs + DropdownMenu 2024-11-13 13:41:32 +01:00
adb37b255a Add order in file schema and main projecct edition 2024-11-13 00:25:18 +01:00
b54402fc19 Fix canvas control buttons being unusable on mobile 2024-11-11 00:00:34 +01:00
0882eb1dd0 Add collapsible properties to editor splitter for better mobile accessibility 2024-11-10 23:45:53 +01:00
64 changed files with 2299 additions and 299 deletions

BIN
bun.lockb

Binary file not shown.

View File

@@ -1,6 +1,10 @@
<script lang="ts">
const External = Annotation.define<boolean>();
</script>
<script setup lang="ts">
import { dropCursor, crosshairCursor, keymap, EditorView } from '@codemirror/view';
import { EditorState } from '@codemirror/state';
import { dropCursor, crosshairCursor, keymap, EditorView, ViewUpdate } from '@codemirror/view';
import { Annotation, EditorState } from '@codemirror/state';
import { indentOnInput, syntaxHighlighting, defaultHighlightStyle, bracketMatching, foldKeymap } from '@codemirror/language';
import { history, defaultKeymap, historyKeymap } from '@codemirror/commands';
import { searchKeymap } from '@codemirror/search';
@@ -36,7 +40,13 @@ onMounted(() => {
...foldKeymap,
...completionKeymap,
...lintKeymap
])
]),
EditorView.updateListener.of((viewUpdate: ViewUpdate) => {
if (viewUpdate.docChanged && !viewUpdate.transactions.some(tr => tr.annotation(External)))
{
model.value = viewUpdate.state.doc.toString();
}
})
]
});
view.value = new EditorView({
@@ -60,16 +70,15 @@ watchEffect(() => {
const currentValue = view.value ? view.value.state.doc.toString() : "";
if (view.value && model.value !== currentValue) {
view.value.dispatch({
changes: { from: 0, to: currentValue.length, insert: model.value || "" }
changes: { from: 0, to: currentValue.length, insert: model.value || "" },
annotations: [External.of(true)],
});
}
});
</script>
<template>
<div class="flex flex-1 justify-center items-start p-12">
<div ref="editor" class="flex flex-1 justify-center items-stretch border border-light-35 dark:border-dark-35 caret-light-100 dark:caret-dark-100" />
</div>
<div ref="editor" class="flex flex-1 w-full justify-stretch items-stretch border border-light-35 dark:border-dark-35 caret-light-100 dark:caret-dark-100" />
</template>
<style>

View File

@@ -0,0 +1,80 @@
<template>
<TreeRoot v-bind="forward" v-slot="{ flattenItems }" class="list-none select-none border border-light-35 dark:border-dark-35 text-light-100 dark:text-dark-100 p-2 xl:text-base text-sm overflow-auto w-[450px] max-h-full">
<DraggableTreeItem v-for="item in flattenItems" :key="item._id" v-bind="item" class="flex items-center outline-none relative cursor-pointer hover:bg-light-20 dark:hover:bg-dark-20 data-[selected]:bg-light-35 dark:data-[selected]:bg-dark-35" @select.prevent @toggle.prevent>
<template #default="{ handleToggle, handleSelect, isExpanded, isSelected, isDragging, isDraggedOver }">
<slot :handleToggle="handleToggle"
:handleSelect="handleSelect"
:isExpanded="isExpanded"
:isSelected="isSelected"
:isDragging="isDragging"
:isDraggedOver="isDraggedOver"
:item="item"
/>
</template>
<template #hint="{ instruction }">
<div v-if="instruction">
<slot name="hint" :instruction="instruction" />
</div>
</template>
</DraggableTreeItem>
</TreeRoot>
</template>
<script setup lang="ts" generic="T extends Record<string, any>">
import { useForwardPropsEmits, type FlattenedItem, type TreeRootEmits, type TreeRootProps } from 'radix-vue';
import { type Instruction, extractInstruction } from '@atlaskit/pragmatic-drag-and-drop-hitbox/tree-item'
import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'
import { monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
const props = defineProps<TreeRootProps<T>>();
const emits = defineEmits<TreeRootEmits<T> & {
'updateTree': [instruction: Instruction, itemId: string, targetId: string];
}>();
defineSlots<{
default: (props: {
handleToggle: () => void,
handleSelect: () => void,
isExpanded: boolean,
isSelected: boolean,
isDragging: boolean,
isDraggedOver: boolean,
item: FlattenedItem<T>,
}) => any,
hint: (props: {
instruction: Extract<Instruction, { type: 'reorder-above' | 'reorder-below' | 'make-child' }> | null
}) => any,
}>();
const forward = useForwardPropsEmits(props, emits);
watchEffect((onCleanup) => {
const dndFunction = combine(
monitorForElements({
onDrop(args) {
const { location, source } = args;
if (!location.current.dropTargets.length)
return;
const itemId = source.data.id as string;
const target = location.current.dropTargets[0];
const targetId = target.data.id as string;
const instruction: Instruction | null = extractInstruction(
target.data,
);
if (instruction !== null)
{
emits('updateTree', instruction, itemId, targetId);
}
},
}),
)
onCleanup(() => {
dndFunction();
})
})
</script>

View File

@@ -0,0 +1,140 @@
<template>
<TreeItem ref="el" v-bind="forward" v-slot="{ isExpanded, isSelected, isIndeterminate, handleToggle, handleSelect }">
<slot
:is-expanded="isExpanded"
:is-selected="isSelected"
:is-indeterminate="isIndeterminate"
:handle-select="handleSelect"
:handle-toggle="handleToggle"
:isDragging="isDragging"
:isDraggedOver="isDraggedOver"
/>
<div v-if="instruction">
<slot name="hint" :instruction="instruction" />
</div>
</TreeItem>
</template>
<script setup lang="ts" generic="T extends Record<string, any>">
import { useForwardPropsEmits, type FlattenedItem, type TreeItemEmits, type TreeItemProps } from 'radix-vue';
import { draggable, dropTargetForElements, monitorForElements } from '@atlaskit/pragmatic-drag-and-drop/element/adapter'
import { type Instruction, attachInstruction, extractInstruction } from '@atlaskit/pragmatic-drag-and-drop-hitbox/tree-item'
import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine'
const props = defineProps<TreeItemProps<T> & FlattenedItem<T>>();
const emits = defineEmits<TreeItemEmits<T>>();
defineSlots<{
default: (props: {
isExpanded: boolean
isSelected: boolean
isIndeterminate: boolean | undefined
isDragging: boolean
isDraggedOver: boolean
handleToggle: () => void
handleSelect: () => void
}) => any,
hint: (props: {
instruction: Extract<Instruction, { type: 'reorder-above' | 'reorder-below' | 'make-child' }> | null
}) => any,
}>()
const forward = useForwardPropsEmits(props, emits);
const element = templateRef('el');
const isDragging = ref(false);
const isDraggedOver = ref(false);
const isInitialExpanded = ref(false);
const instruction = ref<Extract<Instruction, { type: 'reorder-above' | 'reorder-below' | 'make-child' }> | null>(null);
const mode = computed(() => {
if (props.hasChildren)
return 'expanded'
if (props.index + 1 === props.parentItem?.children?.length)
return 'last-in-group'
return 'standard'
});
watchEffect((onCleanup) => {
const currentElement = unrefElement(element) as HTMLElement;
if (!currentElement)
return
const item = { ...props.value, level: props.level, id: props._id }
const expandItem = () => {
if (!element.value?.isExpanded) {
element.value?.handleToggle()
}
}
const closeItem = () => {
if (element.value?.isExpanded) {
element.value?.handleToggle()
}
}
const dndFunction = combine(
draggable({
element: currentElement,
getInitialData: () => item,
onDragStart: () => {
isDragging.value = true
isInitialExpanded.value = element.value?.isExpanded ?? false
closeItem()
},
onDrop: () => {
isDragging.value = false
if (isInitialExpanded.value)
expandItem()
},
}),
dropTargetForElements({
element: currentElement,
getData: ({ input, element }) => {
const data = { id: item.id }
return attachInstruction(data, {
input,
element,
indentPerLevel: 16,
currentLevel: props.level,
mode: mode.value,
block: [],
})
},
canDrop: ({ source }) => {
return source.data.id !== item.id
},
onDrag: ({ self }) => {
instruction.value = extractInstruction(self.data) as typeof instruction.value
},
onDragEnter: ({ source }) => {
if (source.data.id !== item.id) {
isDraggedOver.value = true
}
},
onDragLeave: () => {
isDraggedOver.value = false
instruction.value = null
},
onDrop: ({ location }) => {
isDraggedOver.value = false
instruction.value = null
},
getIsSticky: () => true,
}),
monitorForElements({
canMonitor: ({ source }) => {
return source.data.id !== item.id
},
}),
)
// Cleanup dnd function
onCleanup(() => dndFunction())
})
</script>

View File

@@ -0,0 +1,70 @@
<template>
<template v-for="(item, idx) of options">
<template v-if="item.type === 'item'">
<DropdownMenuItem :disabled="item.disabled" :textValue="item.label" @select="item.select" :class="{'!pe-1': item.kbd}" class="group cursor-pointer text-base text-light-100 dark:text-dark-100 leading-none flex items-center py-1.5 relative ps-7 pe-4 select-none outline-none data-[disabled]:text-light-60 dark:data-[disabled]:text-dark-60 data-[disabled]:pointer-events-none data-[highlighted]:bg-light-35 dark:data-[highlighted]:bg-dark-35">
<Icon v-if="item.icon" :icon="item.icon" class="absolute left-1.5" />
<div class="flex flex-1 justify-between">
<span>{{ item.label }}</span>
<span v-if="item.kbd" class="mx-2 text-xs font-mono text-light-70 dark:text-dark-70 relative top-0.5"> {{ item.kbd }} </span>
</div>
</DropdownMenuItem>
</template>
<!-- TODO -->
<template v-else-if="item.type === 'checkbox'">
<DropdownMenuCheckboxItem :disabled="item.disabled" :textValue="item.label" @update:checked="item.select">
<DropdownMenuItemIndicator>
<Icon icon="radix-icons:check" />
</DropdownMenuItemIndicator>
<span>{{ item.label }}</span>
<span v-if="item.kbd"> {{ item.kbd }} </span>
</DropdownMenuCheckboxItem>
</template>
<!-- TODO -->
<template v-if="item.type === 'radio'">
<DropdownMenuLabel>{{ item.label }}</DropdownMenuLabel>
<DropdownMenuRadioGroup @update:model-value="item.change">
<DropdownMenuRadioItem v-for="option in item.items" :disabled="(option as any)?.disabled ?? false" :value="(option as any)?.value ?? option">
<DropdownMenuItemIndicator>
<Icon icon="radix-icons:dot-filled" />
</DropdownMenuItemIndicator>
<span>{{ (option as any)?.label || option }}</span>
</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
<DropdownMenuSeparator v-if="idx !== options.length - 1" />
</template>
<template v-if="item.type === 'submenu'">
<DropdownMenuSub>
<DropdownMenuSubTrigger class="group cursor-pointer text-base text-light-100 dark:text-dark-100 leading-none flex items-center py-1.5 relative ps-7 select-none outline-none data-[disabled]:text-light-60 dark:data-[disabled]:text-dark-60 data-[disabled]:pointer-events-none data-[highlighted]:bg-light-35 dark:data-[highlighted]:bg-dark-35">
<Icon v-if="item.icon" :icon="item.icon" />
<span>{{ item.label }}</span>
<Icon icon="radix-icons:chevron-right" class="absolute right-1" />
</DropdownMenuSubTrigger>
<DropdownMenuPortal>
<DropdownMenuSubContent class="z-50 outline-none bg-light-20 dark:bg-dark-20 will-change-[opacity,transform] data-[side=top]:animate-slideDownAndFade data-[side=right]:animate-slideLeftAndFade data-[side=bottom]:animate-slideUpAndFade data-[side=left]:animate-slideRightAndFade border border-light-35 dark:border-dark-35">
<DropdownContentRender :options="item.items" />
</DropdownMenuSubContent>
</DropdownMenuPortal>
</DropdownMenuSub>
</template>
<template v-if="item.type === 'group'">
<DropdownMenuLabel class="text-light-70 dark:text-dark-70 text-sm text-center pt-1">{{ item.label }}</DropdownMenuLabel>
<DropdownContentRender :options="item.items" />
<DropdownMenuSeparator v-if="idx !== options.length - 1" />
</template>
</template>
</template>
<script setup lang="ts">
import type { DropdownOption } from './DropdownMenu.vue';
import { Icon } from '@iconify/vue/dist/iconify.js';
const { options } = defineProps<{
options: DropdownOption[]
}>();
</script>

View File

@@ -0,0 +1,58 @@
<template>
<DropdownMenuRoot>
<DropdownMenuTrigger :disabled="disabled" ><slot /></DropdownMenuTrigger>
<DropdownMenuPortal>
<DropdownMenuContent :align="align" :side="side" class="z-50 outline-none bg-light-20 dark:bg-dark-20 will-change-[opacity,transform] data-[side=top]:animate-slideDownAndFade data-[side=right]:animate-slideLeftAndFade data-[side=bottom]:animate-slideUpAndFade data-[side=left]:animate-slideRightAndFade border border-light-35 dark:border-dark-35">
<DropdownContentRender :options="options" />
<DropdownMenuArrow class="fill-light-35 dark:fill-dark-35" />
</DropdownMenuContent>
</DropdownMenuPortal>
</DropdownMenuRoot>
</template>
<script setup lang="ts">
export interface DropdownItem {
type: 'item';
label: string;
disabled?: boolean;
select?: () => void;
icon?: string;
kbd?: string;
}
export interface DropdownCheckbox {
type: 'checkbox';
label: string;
disabled?: boolean;
checked?: boolean | Ref<boolean>
select?: (state: boolean) => void;
kbd?: string;
}
export interface DropdownRadioGroup {
type: 'radio';
label: string;
value?: string | Ref<string>
items: (string | {label: string, value?: string, disabled?: boolean})[];
change?: (value: string) => void;
}
export interface DropdownSubmenu {
type: 'submenu';
label: string;
disabled?: boolean;
items: DropdownOption[];
icon?: string;
}
export interface DropdownGroup {
type: 'group';
label?: string;
items: DropdownOption[];
}
export type DropdownOption = DropdownItem | DropdownCheckbox | DropdownRadioGroup | DropdownSubmenu | DropdownGroup;
const { options, disabled = false, side, align } = defineProps<{
options: DropdownOption[]
disabled?: boolean
side?: 'top' | 'right' | 'bottom' | 'left'
align?: 'start' | 'center' | 'end'
}>();
</script>

View File

@@ -1,6 +1,6 @@
<template>
<Label class="py-4 flex flex-row justify-center items-center">
<span>{{ label }}</span>
<Label class="my-2 flex flex-1 items-center justify-between flex-col md:flex-row">
<span class="pb-1 md:p-0">{{ label }}</span>
<SelectRoot v-model="model">
<SelectTrigger :disabled="disabled" class="mx-4 inline-flex min-w-[160px] items-center justify-between px-3 text-sm font-semibold leading-none h-8 gap-1
bg-light-20 dark:bg-dark-20 border border-light-35 dark:border-dark-35 outline-none data-[placeholder]:font-normal

View File

@@ -5,7 +5,7 @@
class="mx-4 caret-light-50 dark:caret-dark-50 text-light-100 dark:text-dark-100 placeholder:text-light-50 dark:placeholder:text-dark-50
bg-light-20 dark:bg-dark-20 appearance-none outline-none px-3 py-1 focus:shadow-raw transition-[box-shadow] focus:shadow-light-40 dark:focus:shadow-dark-40
border border-light-35 dark:border-dark-35 hover:border-light-50 dark:hover:border-dark-50 data-[disabled]:bg-light-20 dark:data-[disabled]:bg-dark-20 data-[disabled]:border-light-20 dark:data-[disabled]:border-dark-20"
:type="type" v-model="model" :data-disabled="disabled || undefined" v-bind="$attrs">
:type="type" v-model="model" :data-disabled="disabled || undefined" v-bind="$attrs" @change="(e) => emits('change', e)" @input="(e) => emits('input', e)">
</Label>
</template>
@@ -16,5 +16,10 @@ const { type = 'text', label, disabled = false, placeholder } = defineProps<{
disabled?: boolean
placeholder?: string
}>();
const emits = defineEmits<{
change: [Event]
input: [Event]
}>();
const model = defineModel<string>();
</script>

View File

@@ -1,50 +1,20 @@
<template>
<TreeRoot v-slot="{ flattenItems }" class="list-none select-none text-light-100 dark:text-dark-100 p-2 xl:text-base text-sm" :items="model" :get-key="(item) => item.link ?? item.label">
<TreeRoot v-slot="{ flattenItems }" class="list-none select-none text-light-100 dark:text-dark-100 p-2 xl:text-base text-sm" :items="model" :get-key="getKey" :defaultExpanded="flatten(model)">
<TreeItem v-for="item in flattenItems" v-slot="{ isExpanded }" :key="item._id" :style="{ 'padding-left': `${item.level - 0.5}em` }" v-bind="item.bind" class="flex items-center px-2 outline-none relative cursor-pointer">
<NuxtLink :href="item.value.link && !item.hasChildren ? { name: 'explore-path', params: { path: item.value.link } } : undefined" no-prefetch class="flex flex-1 items-center border-light-35 dark:border-dark-35 hover:border-accent-blue" :class="{ 'border-s': !item.hasChildren, 'font-medium': item.hasChildren }" active-class="text-accent-blue border-s-2 !border-accent-blue">
<Icon v-if="item.hasChildren" icon="radix-icons:chevron-right" :class="{ 'rotate-90': isExpanded }" class="h-4 w-4 transition-transform absolute" :style="{ 'left': `${item.level - 1}em` }" />
<div class="pl-3 py-1 flex-1 truncate" :data-tag="item.value.tag">
{{ item.value.label }}
</div>
</NuxtLink>
<slot :isExpanded="isExpanded" :item="item" />
</TreeItem>
</TreeRoot>
</template>
<script setup lang="ts">
import { Icon } from '@iconify/vue/dist/iconify.js';
<script setup lang="ts" generic="T extends Record<string, any>">
const { getKey } = defineProps<{
getKey: (val: T) => string
}>();
interface TreeItem
{
label: string
link?: string
tag?: string
children?: TreeItem[]
}
const model = defineModel<TreeItem[]>();
</script>
const model = defineModel<T[]>();
<style>
[data-tag="canvas"]:after,
[data-tag="private"]:after
function flatten(arr: T[]): string[]
{
@apply text-sm;
@apply font-normal;
@apply float-end;
@apply border ;
@apply border-light-35 ;
@apply dark:border-dark-35;
@apply px-1;
@apply bg-light-20;
@apply dark:bg-dark-20;
font-variant: small-caps;
return arr.filter(e => e.open).flatMap(e => [getKey(e), ...flatten(e.children ?? [])]);
}
[data-tag="canvas"]:after
{
content: 'Canvas'
}
[data-tag="private"]:after
{
content: 'Privé'
}
</style>
</script>

View File

@@ -2,7 +2,7 @@
import { useDrag, usePinch, useWheel } from '@vueuse/gesture';
import type { CanvasContent, CanvasNode } from '~/types/canvas';
import { Icon } from '@iconify/vue/dist/iconify.js';
import { clamp } from '#imports';
import { clamp } from '#shared/general.utils';
interface Props
{
@@ -150,24 +150,20 @@ dark:border-dark-purple
*/
const dragHandler = useDrag(({ event: Event, delta: [x, y] }: { event: Event, delta: number[] }) => {
event?.preventDefault();
const pinchHandler = usePinch(({ event, offset: [z] }: { event: Event, offset: number[] }) => {
zoom.value = clamp(z / 2048, minZoom.value, 3);
}, {
domTarget: canvas,
eventOptions: { passive: false, }
})
const dragHandler = useDrag(({ event, delta: [x, y] }: { event: Event, delta: number[] }) => {
dispX.value += x / zoom.value;
dispY.value += y / zoom.value;
}, {
domTarget: canvas,
eventOptions: { passive: false, }
})
const pinchHandler = usePinch(({ event: Event, offset: [z] }: { event: Event, offset: number[] }) => {
event?.preventDefault();
console.log(z);
zoom.value = clamp(z / 2048, minZoom.value, 3);
}, {
domTarget: canvas,
eventOptions: { passive: false, }
})
const wheelHandler = useWheel(({ event: Event, delta: [x, y] }: { event: Event, delta: number[] }) => {
event?.preventDefault();
const wheelHandler = useWheel(({ event, delta: [x, y] }: { event: Event, delta: number[] }) => {
zoom.value = clamp(zoom.value + y * -0.001, minZoom.value, 3);
}, {
domTarget: canvas,
@@ -180,7 +176,7 @@ const wheelHandler = useWheel(({ event: Event, delta: [x, y] }: { event: Event,
<template #default>
<div id="canvas" ref="canvas" 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="border border-light-35 dark:border-dark-35 bg-light-10 dark:bg-dark-10 absolute sm:top-2 top-10 left-2 z-30 overflow-hidden">
<div class="border border-light-35 dark:border-dark-35 bg-light-10 dark:bg-dark-10 absolute sm:top-2 top-10 left-2 z-[35] overflow-hidden">
<Tooltip message="Zoom avant" side="right">
<div @click="zoom = clamp(zoom * 1.1, minZoom, 3)" 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:plus" />

View File

@@ -31,12 +31,8 @@
<script setup lang="ts">
import { parseURL } from 'ufo';
import { Icon } from '@iconify/vue/dist/iconify.js';
import { iconByType } from '#shared/general.utils';
const iconByType: Record<string, string> = {
'folder': 'circum:folder-on',
'canvas': 'ph:graph-light',
'file': 'radix-icons:file',
}
const { href } = defineProps<{
href: string
class?: string

View File

@@ -5,5 +5,6 @@
</template>
<script setup lang="ts">
import { parseId } from '#shared/general.utils';
const props = defineProps<{ id?: string }>()
</script>

View File

@@ -5,6 +5,7 @@
</template>
<script setup lang="ts">
import { parseId } from '#shared/general.utils';
const props = defineProps<{ id?: string }>()
const generate = computed(() => props.id)

View File

@@ -5,6 +5,7 @@
</template>
<script setup lang="ts">
import { parseId } from '#shared/general.utils';
const props = defineProps<{ id?: string }>()
const generate = computed(() => props.id)

View File

@@ -5,5 +5,6 @@
</template>
<script setup lang="ts">
import { parseId } from '#shared/general.utils';
const props = defineProps<{ id?: string }>()
</script>

View File

@@ -5,6 +5,7 @@
</template>
<script setup lang="ts">
import { parseId } from '#shared/general.utils';
const props = defineProps<{ id?: string }>()
const generate = computed(() => props.id)

View File

@@ -5,6 +5,7 @@
</template>
<script setup lang="ts">
import { parseId } from '#shared/general.utils';
const props = defineProps<{ id?: string }>()
const generate = computed(() => props.id)

View File

@@ -1,57 +1,5 @@
<template>
<!-- <HoverPopup @before-show="fetch">
<template #content>
<Suspense suspensible>
<div class="mw-[400px]">
<div v-if="fetched === false" class="loading w-[400px] h-[150px]"></div>
<template v-else-if="!!data">
<div v-if="data.description" class="pb-4 pt-3 px-8">
<span class="text-2xl font-semibold">#{{ data.tag }}</span>
<Markdown :content="data.description"></Markdown>
</div>
<div class="h-100 w-100 flex flex-1 flex-col justify-center items-center" v-else>
<div class="text-3xl font-extralight tracking-wide text-light-60 dark:text-dark-60">Fichier vide</div>
<div class="text-lg text-light-60 dark:text-dark-60">Cette page est vide</div>
</div>
</template>
<div class="h-100 w-100 flex flex-1 flex-col justify-center items-center" v-else>
<div class="text-3xl font-extralight tracking-wide text-light-60 dark:text-dark-60">Impossible d'afficher</div>
<div class="text-lg text-light-60 dark:text-dark-60">Cette page est impossible à traiter</div>
</div>
</div>
<template #fallback><div class="loading w-[400px] h-[150px]"></div></template>
</Suspense>
</template>
<template #default>
<span class="before:content-['#'] cursor-default bg-accent-blue bg-opacity-10 hover:bg-opacity-20 text-accent-blue text-sm px-1 ms-1 pb-0.5 rounded-full rounded-se-none border border-accent-blue border-opacity-30">
<slot></slot>
</span>
</template>
</HoverPopup> -->
<span class="before:content-['#'] cursor-default bg-accent-blue bg-opacity-10 hover:bg-opacity-20 text-accent-blue text-sm px-1 ms-1 pb-0.5 rounded-full rounded-se-none border border-accent-blue border-opacity-30">
<slot></slot>
</span>
</template>
<!-- <script setup lang="ts">
import type { Tag } from '~/types/api';
const { tag } = defineProps({
tag: {
type: String,
required: true,
}
});
const data = ref<Tag>(), fetched = ref(false);
const route = useRoute();
const project = computed(() => parseInt(Array.isArray(route.params.projectId) ? '0' : route.params.projectId));
async function fetch()
{
if(fetched.value)
return;
data.value = await $fetch(`/api/project/${project.value}/tags/${encodeURIComponent(tag)}`);
fetched.value = true;
}
</script> -->
</template>

View File

@@ -9,7 +9,7 @@ export default function useDatabase()
{
const database = useRuntimeConfig().database;
const sqlite = new Database(database);
instance = drizzle({ client: sqlite, schema });
instance = drizzle({ client: sqlite, schema, /* logger: true */ });
instance.run("PRAGMA journal_mode = WAL;");
instance.run("PRAGMA foreign_keys = true;");

191
composables/useShortcuts.ts Normal file
View File

@@ -0,0 +1,191 @@
import { ref, computed } from 'vue'
import type { ComputedRef, WatchSource } from 'vue'
import { logicAnd, logicNot } from '@vueuse/math'
import { useEventListener, useDebounceFn, createSharedComposable, useActiveElement } from '@vueuse/core'
export interface ShortcutConfig {
handler: Function
usingInput?: string | boolean
whenever?: WatchSource<boolean>[]
}
export interface ShortcutsConfig {
[key: string]: ShortcutConfig | Function
}
export interface ShortcutsOptions {
chainDelay?: number
}
interface Shortcut {
handler: Function
condition: ComputedRef<boolean>
chained: boolean
// KeyboardEvent attributes
key: string
ctrlKey: boolean
metaKey: boolean
shiftKey: boolean
altKey: boolean
// code?: string
// keyCode?: number
}
const chainedShortcutRegex = /^[^-]+.*-.*[^-]+$/
const combinedShortcutRegex = /^[^_]+.*_.*[^_]+$/
export const useShortcuts = (config: ShortcutsConfig, options: ShortcutsOptions = {}) => {
const { macOS, usingInput } = _useShortcuts()
let shortcuts: Shortcut[] = []
const chainedInputs = ref<string[]>([])
const clearChainedInput = () => {
chainedInputs.value.splice(0, chainedInputs.value.length)
}
const debouncedClearChainedInput = useDebounceFn(clearChainedInput, options.chainDelay ?? 800)
const onKeyDown = (e: KeyboardEvent) => {
// Input autocomplete triggers a keydown event
if (!e.key) { return }
const alphabeticalKey = /^[a-z]{1}$/i.test(e.key)
let chainedKey
chainedInputs.value.push(e.key)
// try matching a chained shortcut
if (chainedInputs.value.length >= 2) {
chainedKey = chainedInputs.value.slice(-2).join('-')
for (const shortcut of shortcuts.filter(s => s.chained)) {
if (shortcut.key !== chainedKey) { continue }
if (shortcut.condition.value) {
e.preventDefault()
shortcut.handler()
}
clearChainedInput()
return
}
}
// try matching a standard shortcut
for (const shortcut of shortcuts.filter(s => !s.chained)) {
if (e.key.toLowerCase() !== shortcut.key) { continue }
if (e.metaKey !== shortcut.metaKey) { continue }
if (e.ctrlKey !== shortcut.ctrlKey) { continue }
// shift modifier is only checked in combination with alphabetical keys
// (shift with non-alphabetical keys would change the key)
if (alphabeticalKey && e.shiftKey !== shortcut.shiftKey) { continue }
// alt modifier changes the combined key anyways
// if (e.altKey !== shortcut.altKey) { continue }
if (shortcut.condition.value) {
e.preventDefault()
shortcut.handler()
}
clearChainedInput()
return
}
debouncedClearChainedInput()
}
// Map config to full detailled shortcuts
shortcuts = Object.entries(config).map(([key, shortcutConfig]) => {
if (!shortcutConfig) {
return null
}
// Parse key and modifiers
let shortcut: Partial<Shortcut>
if (key.includes('-') && key !== '-' && !key.match(chainedShortcutRegex)?.length) {
console.trace(`[Shortcut] Invalid key: "${key}"`)
}
if (key.includes('_') && key !== '_' && !key.match(combinedShortcutRegex)?.length) {
console.trace(`[Shortcut] Invalid key: "${key}"`)
}
const chained = key.includes('-') && key !== '-'
if (chained) {
shortcut = {
key: key.toLowerCase(),
metaKey: false,
ctrlKey: false,
shiftKey: false,
altKey: false
}
} else {
const keySplit = key.toLowerCase().split('_').map(k => k)
shortcut = {
key: keySplit.filter(k => !['meta', 'ctrl', 'shift', 'alt'].includes(k)).join('_'),
metaKey: keySplit.includes('meta'),
ctrlKey: keySplit.includes('ctrl'),
shiftKey: keySplit.includes('shift'),
altKey: keySplit.includes('alt')
}
}
shortcut.chained = chained
// Convert Meta to Ctrl for non-MacOS
if (!macOS.value && shortcut.metaKey && !shortcut.ctrlKey) {
shortcut.metaKey = false
shortcut.ctrlKey = true
}
// Retrieve handler function
if (typeof shortcutConfig === 'function') {
shortcut.handler = shortcutConfig
} else if (typeof shortcutConfig === 'object') {
shortcut = { ...shortcut, handler: shortcutConfig.handler }
}
if (!shortcut.handler) {
console.trace('[Shortcut] Invalid value')
return null
}
// Create shortcut computed
const conditions: ComputedRef<boolean>[] = []
if (!(shortcutConfig as ShortcutConfig).usingInput) {
conditions.push(logicNot(usingInput))
} else if (typeof (shortcutConfig as ShortcutConfig).usingInput === 'string') {
conditions.push(computed(() => usingInput.value === (shortcutConfig as ShortcutConfig).usingInput))
}
shortcut.condition = logicAnd(...conditions, ...((shortcutConfig as ShortcutConfig).whenever || []))
return shortcut as Shortcut
}).filter(Boolean) as Shortcut[]
useEventListener('keydown', onKeyDown)
}
export const _useShortcuts = () => {
const macOS = computed(() => process.client && navigator && navigator.userAgent && navigator.userAgent.match(/Macintosh;/))
const metaSymbol = ref(' ')
const activeElement = useActiveElement()
const usingInput = computed(() => {
const usingInput = !!(activeElement.value?.tagName === 'INPUT' || activeElement.value?.tagName === 'TEXTAREA' || activeElement.value?.contentEditable === 'true')
if (usingInput) {
return ((activeElement.value as any)?.name as string) || true
}
return false
})
onMounted(() => {
metaSymbol.value = macOS.value ? '⌘' : 'Ctrl'
})
return {
macOS,
metaSymbol,
activeElement,
usingInput
}
}

BIN
db.sqlite

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -39,8 +39,9 @@ export const explorerContentTable = sqliteTable("explorer_content", {
title: text().notNull(),
type: text({ enum: ['file', 'folder', 'markdown', 'canvas'] }).notNull(),
content: blob({ mode: 'buffer' }),
navigable: int({ mode: 'boolean' }).default(true),
private: int({ mode: 'boolean' }).default(false),
navigable: int({ mode: 'boolean' }).notNull().default(true),
private: int({ mode: 'boolean' }).notNull().default(false),
order: int().unique('order').notNull(),
});
export const usersRelation = relations(usersTable, ({ one, many }) => ({

View File

@@ -0,0 +1,2 @@
ALTER TABLE `explorer_content` ADD `order` integer;--> statement-breakpoint
CREATE UNIQUE INDEX `order` ON `explorer_content` (`order`);

View File

@@ -0,0 +1,313 @@
{
"version": "6",
"dialect": "sqlite",
"id": "a1a7b478-d0c3-4fc6-b74a-1a010c1d8ca1",
"prevId": "6da7ff20-0db8-4055-a353-bb0ea2fa5e0b",
"tables": {
"explorer_content": {
"name": "explorer_content",
"columns": {
"path": {
"name": "path",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"owner": {
"name": "owner",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"content": {
"name": "content",
"type": "blob",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"navigable": {
"name": "navigable",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": true
},
"private": {
"name": "private",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": false
},
"order": {
"name": "order",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"order": {
"name": "order",
"columns": [
"order"
],
"isUnique": true
}
},
"foreignKeys": {
"explorer_content_owner_users_id_fk": {
"name": "explorer_content_owner_users_id_fk",
"tableFrom": "explorer_content",
"tableTo": "users",
"columnsFrom": [
"owner"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "cascade"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_permissions": {
"name": "user_permissions",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"permission": {
"name": "permission",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"user_permissions_id_users_id_fk": {
"name": "user_permissions_id_users_id_fk",
"tableFrom": "user_permissions",
"tableTo": "users",
"columnsFrom": [
"id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "cascade"
}
},
"compositePrimaryKeys": {
"user_permissions_id_permission_pk": {
"columns": [
"id",
"permission"
],
"name": "user_permissions_id_permission_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"user_sessions": {
"name": "user_sessions",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"timestamp": {
"name": "timestamp",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"user_sessions_user_id_users_id_fk": {
"name": "user_sessions_user_id_users_id_fk",
"tableFrom": "user_sessions",
"tableTo": "users",
"columnsFrom": [
"user_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "cascade"
}
},
"compositePrimaryKeys": {
"user_sessions_id_user_id_pk": {
"columns": [
"id",
"user_id"
],
"name": "user_sessions_id_user_id_pk"
}
},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users_data": {
"name": "users_data",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"signin": {
"name": "signin",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"users_data_id_users_id_fk": {
"name": "users_data_id_users_id_fk",
"tableFrom": "users_data",
"tableTo": "users",
"columnsFrom": [
"id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "cascade"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"users": {
"name": "users",
"columns": {
"id": {
"name": "id",
"type": "integer",
"primaryKey": true,
"notNull": true,
"autoincrement": true
},
"username": {
"name": "username",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"email": {
"name": "email",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"hash": {
"name": "hash",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"state": {
"name": "state",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
}
},
"indexes": {
"users_username_unique": {
"name": "users_username_unique",
"columns": [
"username"
],
"isUnique": true
},
"users_email_unique": {
"name": "users_email_unique",
"columns": [
"email"
],
"isUnique": true
},
"users_hash_unique": {
"name": "users_hash_unique",
"columns": [
"hash"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}

View File

@@ -22,6 +22,13 @@
"when": 1730985155814,
"tag": "0002_messy_solo",
"breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1731344368953,
"tag": "0003_cultured_skaar",
"breakpoints": true
}
]
}

View File

@@ -1,12 +1,15 @@
<template>
<Head>
<Title>d[any] - Erreur {{ error?.statusCode }}</Title>
</Head>
<div class="text-light-100 dark:text-dark-100 flex bg-light-0 dark:bg-dark-0 h-screen overflow-hidden justify-center items-center flex-col gap-4">
<NuxtRouteAnnouncer/>
<div class="flex gap-4 items-center">
<Icon icon="si:error-line" class="w-12 h-12 text-light-60 dark:text-dark-60"/>
<div class="text-3xl">Une erreur est survenue.</div>
</div>
<pre class="">Erreur {{ error?.statusCode }}: {{ error?.message }}</pre>
<NuxtLink :href="{ name: 'index' }"><Button>Revenir en lieu sûr</Button></NuxtLink>
<pre class="text-center text-wrap">Erreur {{ error?.statusCode }}: {{ error?.message }}</pre>
<Button @click="handleError">Revenir en lieu sûr</Button>
</div>
</template>

View File

@@ -12,12 +12,27 @@
</div>
<div class="flex items-center px-2">
<Tooltip message="Changer de theme" side="left"><ThemeSwitch /></Tooltip>
<Tooltip :message="loggedIn ? 'Mon profil' : 'Se connecter'" side="right">
<NuxtLink class="" :to="{ name: 'user-profile' }">
<Tooltip v-if="!loggedIn" :message="'Se connecter'" side="right">
<div class="hover:border-opacity-70 flex">
<Icon :icon="'radix-icons:person'" class="w-7 h-7 p-1" />
</div>
</Tooltip>
<Tooltip v-else :message="'Mon profil'" side="right">
<DropdownMenu :options="[{
type: 'item',
label: 'Mon profil',
icon: 'radix-icons:avatar',
select: () => useRouter().push({ name: 'user-profile' }),
}, {
type: 'item',
label: 'Deconnexion',
icon: 'radix-icons:close',
select: () => clear(),
}]" side="right" align="start">
<div class="hover:border-opacity-70 flex">
<Icon :icon="loggedIn ? 'radix-icons:avatar' : 'radix-icons:person'" class="w-7 h-7 p-1" />
<Icon :icon="'radix-icons:avatar'" class="w-7 h-7 p-1" />
</div>
</NuxtLink>
</DropdownMenu>
</Tooltip>
</div>
</div>
@@ -32,19 +47,50 @@
</NuxtLink>
<div class="flex gap-4 items-center">
<Tooltip message="Changer de theme" side="left"><ThemeSwitch /></Tooltip>
<Tooltip :message="loggedIn ? 'Mon profil' : 'Se connecter'" side="right">
<NuxtLink class="" :to="{ name: 'user-profile' }">
<Tooltip v-if="!loggedIn" :message="'Se connecter'" side="right">
<NuxtLink :to="{ name: 'user-login' }">
<div class="bg-light-20 dark:bg-dark-20 hover:border-opacity-70 flex border p-px border-light-50 dark:border-dark-50">
<Icon :icon="loggedIn ? 'radix-icons:avatar' : 'radix-icons:person'" class="w-7 h-7 p-1" />
<Icon :icon="'radix-icons:person'" class="w-7 h-7 p-1" />
</div>
</NuxtLink>
</Tooltip>
<Tooltip v-else :message="'Mon profil'" side="right">
<DropdownMenu :options="[{
type: 'item',
label: 'Mon profil',
select: () => useRouter().push({ name: 'user-profile' }),
}, {
type: 'item',
label: 'Deconnexion',
select: () => clear(),
}]" side="right" align="start">
<div class="bg-light-20 dark:bg-dark-20 hover:border-opacity-70 flex border p-px border-light-50 dark:border-dark-50">
<Icon :icon="'radix-icons:avatar'" class="w-7 h-7 p-1" />
</div>
</DropdownMenu>
</Tooltip>
</div>
</div>
</div>
<Tree v-if="pages" v-model="pages" class="flex-1 xl:px-6 px-3 max-w-full max-h-full overflow-y-auto overflow-x-hidden"/>
<div class="flex-1 xl:px-6 px-3 max-w-full max-h-full overflow-y-auto overflow-x-hidden">
<NuxtLink :href="{ name: 'explore' }" no-prefetch class="flex flex-1 font-bold text-lg items-center border-light-35 dark:border-dark-35 hover:border-accent-blue" active-class="text-accent-blue border-s-2 !border-accent-blue">
<div class="pl-3 py-1 flex-1 truncate">Projet</div>
</NuxtLink>
<Tree v-if="pages" v-model="pages" :getKey="(item) => item.path">
<template #default="{ item, isExpanded }">
<NuxtLink :href="item.value.path && !item.hasChildren ? { name: 'explore-path', params: { path: item.value.path } } : undefined" no-prefetch class="flex flex-1 items-center hover:border-accent-blue hover:text-accent-purple" :class="{ 'font-medium': item.hasChildren }" active-class="text-accent-blue" :data-private="item.value.private">
<Icon v-if="item.hasChildren" icon="radix-icons:chevron-right" :class="{ 'rotate-90': isExpanded }" class="h-4 w-4 transition-transform absolute" :style="{ 'left': `${item.level - 1}em` }" />
<Icon v-else-if="iconByType[item.value.type]" :icon="iconByType[item.value.type]" class="w-5 h-5" />
<div class="pl-3 py-1 flex-1 truncate">
{{ item.value.title }}
</div>
<Tooltip message="Privé" side="right"><Icon v-show="item.value.private" icon="radix-icons:lock-closed" /></Tooltip>
</NuxtLink>
</template>
</Tree>
</div>
<div class="xl:px-12 px-6 text-start text-xs text-light-60 dark:text-dark-60 relative top-4">
<NuxtLink class="hover:underline italic" :to="{ name: 'legal' }">Mentions légales</NuxtLink>
<NuxtLink class="hover:underline italic" :to="{ name: 'roadmap' }">Roadmap</NuxtLink> - <NuxtLink class="hover:underline italic" :to="{ name: 'legal' }">Mentions légales</NuxtLink>
<p>Copyright Peaceultime - 2024</p>
</div>
</div>
@@ -56,20 +102,26 @@
<script setup lang="ts">
import { Icon } from '@iconify/vue/dist/iconify.js';
import type { NavigationTreeItem } from '~/server/api/navigation.get';
import { iconByType } from '#shared/general.utils';
const open = ref(true);
const { loggedIn } = useUserSession();
const open = ref(false);
const { loggedIn, clear } = useUserSession();
const { data: pages } = await useLazyFetch('/api/navigation', {
transform: transform,
});
const route = useRouter().currentRoute;
const path = computed(() => route.value.params.path ? Array.isArray(route.value.params.path) ? route.value.params.path[0] : route.value.params.path : undefined);
watch(useRouter().currentRoute, () => {
watch(route, () => {
open.value = false;
});
function transform(list: any[]): any[]
const { data: pages } = await useLazyFetch('/api/navigation', {
transform: transform,
watch: [useRouter().currentRoute]
});
function transform(list: NavigationTreeItem[] | undefined): NavigationTreeItem[] | undefined
{
return list?.map(e => ({ label: e.title, children: transform(e.children), link: e.path, tag: e.private ? 'private' : e.type }))
return list?.map(e => ({ ...e, open: path.value?.startsWith(e.path), children: transform(e.children) }));
}
</script>

View File

@@ -1,3 +1,5 @@
import { hasPermissions } from "#shared/auth.util";
export default defineNuxtRouteMiddleware(async (to, from) => {
const { loggedIn, fetch, user } = useUserSession();
const meta = to.meta;

View File

@@ -1,4 +1,7 @@
// https://nuxt.com/docs/api/configuration/nuxt-config
import vuePlugin from 'rollup-plugin-vue'
import postcssPlugin from 'rollup-plugin-postcss'
export default defineNuxtConfig({
compatibilityDate: '2024-04-03',
modules: [
@@ -114,17 +117,43 @@ export default defineNuxtConfig({
path: '~/components',
pathPrefix: false,
},
{
path: '~/server/components',
pathPrefix: true,
global: true,
},
],
nitro: {
alias: {
'public': '//public',
},
publicAssets: [{
baseURL: 'public',
dir: 'public',
}],
preset: 'bun',
experimental: {
tasks: true,
},
rollupConfig: {
external: ['bun'],
plugins: [
vuePlugin({ include: /\.vue$/, target: 'node' })
]
},
},
runtimeConfig: {
session: {
password: '699c46bd-9aaa-4364-ad01-510ee4fe7013'
},
database: 'db.sqlite'
database: 'db.sqlite',
mail: {
host: '',
port: '',
user: '',
passwd: '',
dkim: '',
}
},
security: {
rateLimiter: false,

View File

@@ -7,23 +7,46 @@
"dev": "bunx --bun nuxi dev"
},
"dependencies": {
"@atlaskit/pragmatic-drag-and-drop": "^1.4.0",
"@atlaskit/pragmatic-drag-and-drop-hitbox": "^1.0.3",
"@iconify/vue": "^4.1.2",
"@nuxtjs/color-mode": "^3.5.2",
"@nuxtjs/tailwindcss": "^6.12.2",
"@vueuse/gesture": "^2.0.0",
"@vueuse/math": "^11.2.0",
"@vueuse/nuxt": "^11.1.0",
"codemirror": "^6.0.1",
"drizzle-orm": "^0.35.3",
"hast": "^1.0.0",
"lodash.capitalize": "^4.2.1",
"mdast-util-find-and-replace": "^3.0.1",
"nodemailer": "^6.9.16",
"nuxt": "^3.14.159",
"nuxt-security": "^2.0.0",
"radix-vue": "^1.9.8",
"rehype-raw": "^7.0.0",
"remark-breaks": "^4.0.0",
"remark-frontmatter": "^5.0.0",
"remark-gfm": "^4.0.0",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.1",
"rollup-plugin-postcss": "^4.0.2",
"rollup-plugin-vue": "^6.0.0",
"unified": "^11.0.5",
"unist-util-visit": "^5.0.0",
"vue": "latest",
"vue-router": "latest",
"zod": "^3.23.8"
},
"devDependencies": {
"@types/bun": "^1.1.12",
"@types/lodash.capitalize": "^4.2.9",
"@types/nodemailer": "^6.4.16",
"@types/unist": "^3.0.3",
"better-sqlite3": "^11.5.0",
"bun-types": "^1.1.34",
"drizzle-kit": "^0.26.2"
"drizzle-kit": "^0.26.2",
"mdast-util-to-string": "^4.0.0",
"rehype-stringify": "^10.0.1"
}
}

View File

@@ -1,27 +1,54 @@
<script lang="ts">
const mailSchema = z.object({
to: z.string().email(),
template: z.string(),
data: z.string(),
});
const schemaList: Record<string, z.ZodObject<any> | null> = {
'pull': null,
'push': null,
'mail': mailSchema,
}
</script>
<script setup lang="ts">
import { z } from 'zod';
definePageMeta({
rights: ['admin'],
})
const job = ref<string>('');
const toaster = useToast();
const data = ref(), status = ref<'idle' | 'pending' | 'success' | 'error'>('idle'), success = ref(false), err = ref(false), error = ref();
const payload = reactive<Record<string, any>>({
data: JSON.stringify({ username: "Peaceultime", id: 1, timestamp: Date.now() }),
to: 'clem31470@gmail.com',
});
const data = ref(), status = ref<'idle' | 'pending' | 'success' | 'error'>('idle'), success = ref(false), error = ref<Error | null>();
async function fetch()
{
status.value = 'pending';
data.value = null;
error.value = null;
err.value = false;
success.value = false;
try
{
const schema = schemaList[job.value];
if(schema)
{
console.log(payload);
const parsedPayload = schema.parse(payload);
}
data.value = await $fetch(`/api/admin/jobs/${job.value}`, {
method: 'POST',
body: payload,
});
status.value = 'success';
error.value = null;
err.value = false;
success.value = true;
toaster.add({ duration: 10000, content: data.value ?? 'Job executé avec succès', type: 'success', timer: true, });
@@ -29,26 +56,32 @@ async function fetch()
catch(e)
{
status.value = 'error';
error.value = e;
err.value = true;
error.value = e as Error;
success.value = false;
toaster.add({ duration: 10000, content: error.value, type: 'error', timer: true, });
toaster.add({ duration: 10000, content: error.value.message, type: 'error', timer: true, });
}
}
</script>
<template>
<Head>
<Title>Administration</Title>
<Title>d[any] - Administration</Title>
</Head>
<div class="flex flex-col justify-start">
<div class="flex flex-col justify-start items-center">
<ProseH2>Administration</ProseH2>
<Select label="Job" v-model="job">
<SelectItem label="Synchroniser" value="sync" />
<SelectItem label="Nettoyer la base" value="clear" disabled />
<SelectItem label="Reconstruire" value="rebuild" disabled />
</Select>
<div class="flex flex-row w-full gap-8">
<Select label="Job" v-model="job">
<SelectItem label="Récupérer les données d'Obsidian" value="pull" />
<SelectItem label="Envoyer les données dans Obsidian" value="push" disabled />
<SelectItem label="Envoyer un mail de test" value="mail" />
</Select>
<Select v-if="job === 'mail'" v-model="payload.template" label="Modèle" class="w-full" ><SelectItem label="Inscription" value="registration" /></Select>
</div>
<div v-if="job === 'mail'" class="flex justify-center items-center flex-col">
<TextInput label="Destinataire" class="w-full" v-model="payload.to" />
<textarea v-model="payload.data" class="w-[640px] bg-light-20 dark:bg-dark-20 border border-light-35 dark:border-dark-35 outline-none m-2 px-2"></textarea>
</div>
<Button class="self-center" @click="() => !!job && fetch()" :loading="status === 'pending'">
<span>Executer</span>
</Button>

View File

@@ -1,6 +1,6 @@
<template>
<Head>
<Title>Editeur</Title>
<Title>d[any] - Editeur</Title>
</Head>
<Editor v-model="model" />
</template>

View File

@@ -42,6 +42,14 @@
<script setup lang="ts">
const route = useRouter().currentRoute;
const path = computed(() => Array.isArray(route.value.params.path) ? route.value.params.path[0] : route.value.params.path);
watch(path, () => {
if(path.value === 'index')
{
useRouter().replace({ name: 'explore' });
}
}, { immediate: true });
const { loggedIn, user } = useUserSession();
const { data: page, status, error } = await useFetch(`/api/file/${encodeURIComponent(path.value)}`, { watch: [route, path], });

View File

@@ -1,25 +1,30 @@
<template>
<div v-if="page" class="xl:p-12 lg:p-8 py-4 flex flex-1 flex-col items-start justify-start max-h-full">
<Head>
<Title>Modification de {{ page.title }}</Title>
<Title>d[any] - Modification de {{ page.title }}</Title>
</Head>
<div class="flex flex-col xl:flex-row xl:justify-between justify-center items-center w-full px-4 pb-4 border-b border-light-35 dark:border-dark-35 bg-light-0 dark:bg-dark-0">
<input type="text" v-model="page.title" placeholder="Titre" class="flex-1 mx-4 h-16 caret-light-50 dark:caret-dark-50 text-light-100 dark:text-dark-100 placeholder:text-light-50 dark:placeholder:text-dark-50 appearance-none outline-none px-3 py-1 text-5xl font-thin bg-transparent" />
<div class="flex gap-4 self-end xl:self-auto">
<Tooltip message="Consultable uniquement par le propriétaire" side="bottom"><Switch label="Privé" v-model="page.private" /></Tooltip>
<Tooltip message="Afficher dans le menu de navigation" side="bottom"><Switch label="Navigable" v-model="page.navigable" /></Tooltip>
<Button @click="() => save()" :loading="saveStatus === 'pending'" class="border-light-blue dark:border-dark-blue hover:border-light-blue dark:hover:border-dark-blue focus:shadow-light-blue dark:focus:shadow-dark-blue">Enregistrer</Button>
<input type="text" v-model="page.title" placeholder="Titre" class="flex-1 mx-4 h-16 w-full caret-light-50 dark:caret-dark-50 text-light-100 dark:text-dark-100 placeholder:text-light-50 dark:placeholder:text-dark-50 appearance-none outline-none px-3 py-1 text-5xl font-thin bg-transparent" />
<div class="flex gap-4 self-end xl:self-auto flex-wrap">
<div class="flex gap-4">
<Tooltip message="Consultable uniquement par le propriétaire" side="bottom"><Switch label="Privé" v-model="page.private" /></Tooltip>
<Tooltip message="Afficher dans le menu de navigation" side="bottom"><Switch label="Navigable" v-model="page.navigable" /></Tooltip>
</div>
<div class="flex gap-4">
<Tooltip message="Ctrl+S" side="bottom"><Button @click="() => save(true)" :loading="saveStatus === 'pending'" class="border-light-blue dark:border-dark-blue hover:border-light-blue dark:hover:border-dark-blue focus:shadow-light-blue dark:focus:shadow-dark-blue">Enregistrer</Button></Tooltip>
<Tooltip message="Ctrl+Shift+Z" side="bottom"><NuxtLink :href="{ name: 'explore-path', params: { path: path } }"><Button>Annuler</Button></NuxtLink></Tooltip>
</div>
</div>
</div>
<div class="my-4 flex-1 w-full max-h-full flex">
<template v-if="page.type === 'markdown'">
<SplitterGroup direction="horizontal" class="flex-1 w-full flex">
<SplitterPanel asChild>
<textarea v-model="page.content" class="flex-1 bg-transparent appearance-none outline-none max-h-full resize-none !overflow-y-auto"></textarea>
<SplitterGroup direction="horizontal" class="flex-1 w-full flex" >
<SplitterPanel asChild collapsible :collapsedSize="0" :minSize="20" v-slot="{ isCollapsed }" :defaultSize="50">
<Editor v-model="page.content" class="flex-1 bg-transparent appearance-none outline-none max-h-full resize-none !overflow-y-auto" :class="{ 'hidden': isCollapsed }" />
</SplitterPanel>
<SplitterResizeHandle class="bg-light-35 dark:bg-dark-35 w-px xl!mx-4 mx-2" />
<SplitterPanel asChild>
<div class="flex-1 max-h-full !overflow-y-auto px-8"><Markdown :content="debounced" :proses="{ 'a': FakeA }" /></div>
<SplitterPanel asChild collapsible :collapsedSize="0" :minSize="20" v-slot="{ isCollapsed }">
<div class="flex-1 max-h-full !overflow-y-auto px-8" :class="{ 'hidden': isCollapsed }"><Markdown :content="debounced" :proses="{ 'a': FakeA }" /></div>
</SplitterPanel>
</SplitterGroup>
</template>
@@ -33,7 +38,7 @@
</div>
<div v-else-if="status === 'pending'" class="flex">
<Head>
<Title>Chargement</Title>
<Title>d[any] - Chargement</Title>
</Head>
<Loading />
</div>
@@ -43,41 +48,69 @@
<script setup lang="ts">
import FakeA from '~/components/prose/FakeA.vue';
const route = useRouter().currentRoute;
const nuxt = useNuxtApp();
const router = useRouter();
const route = router.currentRoute;
const path = computed(() => Array.isArray(route.value.params.path) ? route.value.params.path[0] : route.value.params.path);
const { user, loggedIn } = useUserSession();
const toaster = useToast();
const saveStatus = ref<'idle' | 'pending' | 'success' | 'error'>('idle');
const { data: page, status, error } = await useLazyFetch(`/api/file/${encodeURIComponent(path.value)}`, { watch: [ route, path ]});
const sessionContent = useSessionStorage<string | undefined>(path.value, undefined);
const { data: page, status, error } = await useFetch(`/api/file/${encodeURIComponent(path.value)}`, { watch: [ route, path ], transform: (value) => {
if(value && sessionContent.value !== undefined)
{
value.content = sessionContent.value;
}
return value;
}, getCachedData: (key) => {
const value = nuxt.isHydrating ? nuxt.payload.data[key] : nuxt.static.data[key];
if(value && sessionContent.value !== undefined)
{
value.content = sessionContent.value;
}
return value;
} });
const content = computed(() => page.value?.content);
const debounced = useDebounce(content, 250);
if(!loggedIn || (page.value && page.value.owner !== user.value?.id))
{
useRouter().replace({ name: 'explore-path', params: { path: path.value } });
router.replace({ name: 'explore-path', params: { path: path.value } });
}
async function save(): Promise<void>
watch(debounced, (value) => {
sessionContent.value = value;
});
useShortcuts({
meta_s: { usingInput: true, handler: () => save(false) },
meta_shift_z: { usingInput: true, handler: () => router.push({ name: 'explore-path', params: { path: path.value }}) }
})
async function save(redirect: boolean): Promise<void>
{
saveStatus.value = 'pending';
try {
await $fetch(`/api/file`, {
method: 'post',
body: page.value,
headers: {
'Content-Type': 'application/json',
},
});
saveStatus.value = 'success';
sessionContent.value = undefined;
toaster.clear('error');
toaster.add({
type: 'success', content: 'Contenu enregistré', timer: true, duration: 10000
});
useRouter().push({ name: 'explore-path', params: { path: path.value } });
if(redirect)
router.push({ name: 'explore-path', params: { path: path.value } });
} catch(e: any) {
toaster.add({
type: 'error', content: e.message, timer: true, duration: 10000

View File

@@ -0,0 +1,407 @@
<template>
<Head>
<Title>d[any] - Configuration du projet</Title>
</Head>
<div class="flex flex-1 flex-row gap-4 p-6 items-start" v-if="navigation">
<div class="flex flex-1 flex-col w-[450px] max-w-[450px] max-h-full">
<DraggableTree class="list-none select-none border border-light-35 dark:border-dark-35 text-light-100 dark:text-dark-100 p-2 xl:text-base text-sm overflow-auto"
:items="navigation ?? undefined" :get-key="(item: Partial<ProjectExtendedItem>) => item.path !== undefined ? getPath(item as ProjectExtendedItem) : ''" @updateTree="drop">
<template #default="{ handleToggle, handleSelect, isExpanded, isSelected, isDragging, item }">
<div class="flex flex-1 items-center px-2" :class="{ 'opacity-50': isDragging }" :style="{ 'padding-left': `${item.level - 0.5}em` }">
<span class="py-2 px-2" @click="handleToggle" v-if="item.hasChildren" >
<Icon :icon="isExpanded ? 'lucide:folder-open' : 'lucide:folder'"/>
</span>
<Icon v-else-if="iconByType[item.value.type]" :icon="iconByType[item.value.type]" class="group-[:hover]:text-accent-purple mx-2" @click="() => { handleSelect(); selected = isSelected ? undefined : item.value; }" />
<div class="pl-3 py-1 flex-1 truncate" :title="item.value.title" @click="() => { handleSelect(); selected = isSelected ? undefined : item.value; }">
{{ item.value.title }}
</div>
<div class="flex gap-2">
<span @click="item.value.private = !item.value.private">
<Icon v-if="item.value.private" icon="radix-icons:lock-closed" />
<Icon v-else class="text-light-50 dark:text-dark-50" icon="radix-icons:lock-open-2" />
</span>
<span @click="item.value.navigable = !item.value.navigable">
<Icon v-if="item.value.navigable" icon="radix-icons:eye-open" />
<Icon v-else class="text-light-50 dark:text-dark-50" icon="radix-icons:eye-none" />
</span>
</div>
</div>
</template>
<template #hint="{ instruction }">
<div v-if="instruction" class="absolute h-full w-full top-0 right-0 border-light-50 dark:border-dark-50" :style="{
width: `calc(100% - ${instruction.currentLevel - 1}em)`
}" :class="{
'!border-b-4': instruction?.type === 'reorder-below',
'!border-t-4': instruction?.type === 'reorder-above',
'!border-4': instruction?.type === 'make-child',
}"></div>
</template>
</DraggableTree>
</div>
<div class="flex flex-col flex-1">
<div class="flex self-end gap-4 px-4">
<DropdownMenu align="center" side="bottom" :options="[{
type: 'item',
label: 'Markdown',
kbd: 'Ctrl+N',
icon: 'radix-icons:file',
select: () => add('markdown'),
}, {
type: 'item',
label: 'Dossier',
kbd: 'Ctrl+Shift+N',
icon: 'lucide:folder',
select: () => add('folder'),
}, {
type: 'item',
label: 'Canvas',
icon: 'ph:graph-light',
select: () => add('canvas'),
}, {
type: 'item',
label: 'Fichier',
icon: 'radix-icons:file-text',
select: () => add('file'),
}]">
<Button>Nouveau</Button>
</DropdownMenu>
<Button @click="navigation = tree.remove(navigation, getPath(selected))" v-if="selected" class="border-light-red dark:border-dark-red hover:border-light-red dark:hover:border-dark-red focus:shadow-light-red dark:focus:shadow-dark-red">Supprimer</Button>
<Tooltip message="Ctrl+S" side="bottom"><Button @click="() => save(true)" :loading="saveStatus === 'pending'" class="border-light-blue dark:border-dark-blue hover:border-light-blue dark:hover:border-dark-blue focus:shadow-light-blue dark:focus:shadow-dark-blue">Enregistrer</Button></Tooltip>
<Tooltip message="Ctrl+Shift+Z" side="bottom"><NuxtLink :href="{ name: 'explore' }"><Button>Annuler</Button></NuxtLink></Tooltip>
</div>
<div v-if="selected" class="flex-1 flex justify-start items-start">
<div class="flex flex-col flex-1 justify-start items-start">
<input type="text" v-model="selected.title" @change="(e) => {
if(selected && !selected.customPath)
{
selected.name = parsePath(selected.title);
rebuildPath(selected.children, getPath(selected));
}
}" placeholder="Titre" class="flex-1 mx-4 h-16 w-full caret-light-50 dark:caret-dark-50 text-light-100 dark:text-dark-100 placeholder:text-light-50 dark:placeholder:text-dark-50 appearance-none outline-none px-3 py-1 text-5xl font-thin bg-transparent" />
<div class="flex ms-6 flex-col justify-start items-start gap-2">
<div class="flex flex-col justify-start items-start">
<Switch label="Chemin personnalisé" v-model="selected.customPath" />
<span>
<pre v-if="selected.customPath" class="flex items-center">/{{ selected.parent !== '' ? selected.parent + '/' : '' }}<TextInput v-model="selected.name" @input="(e) => {
if(selected && selected.customPath)
{
selected.name = parsePath(selected.name);
rebuildPath(selected.children, getPath(selected));
}
}" class="mx-0"/></pre>
<pre v-else>/{{ getPath(selected) }}</pre>
</span>
</div>
<div class="flex items-center gap-2">
<HoverCard class="!py-2 !px-4"><Icon icon="radix-icons:question-mark-circled" /><template #content><span class="text-sm italic text-light-60 dark:text-dark-60">Un fichier privé n'est consultable que par le propriétaire du projet. Rendre un dossier privé cache automatiquement son contenu sans avoir à chaque fichier un par un.</span></template></HoverCard>
<Switch label="Privé" v-model="selected.private" />
</div>
<div class="flex items-center gap-2">
<HoverCard class="!py-2 !px-4"><Icon icon="radix-icons:question-mark-circled" /><template #content><span class="text-sm italic text-light-60 dark:text-dark-60">Un fichier navigable est disponible dans le menu de navigation à gauche. Les fichiers non navigable peuvent toujours être utilisés dans des liens.</span></template></HoverCard>
<Switch label="Navigable" v-model="selected.navigable" />
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { Icon } from '@iconify/vue/dist/iconify.js';
import type { Instruction } from '@atlaskit/pragmatic-drag-and-drop-hitbox/dist/types/tree-item';
import { parsePath } from '#shared/general.utils';
import type { ProjectItem } from '~/schemas/project';
import type { FileType } from '~/schemas/file';
import { iconByType } from '#shared/general.utils';
interface ProjectExtendedItem extends ProjectItem
{
customPath: boolean
children?: ProjectExtendedItem[]
}
interface ProjectExtended
{
items: ProjectExtendedItem[]
}
definePageMeta({
rights: ['admin', 'editor'],
});
const router = useRouter();
const toaster = useToast();
const saveStatus = ref<'idle' | 'pending' | 'success' | 'error'>('idle');
const { data: project } = await useFetch(`/api/project`, {
transform: (project) =>{
if(project)
(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;
if(proj && value)
proj.items = value;
project.value = proj;
}
});
const selected = ref<ProjectExtendedItem>();
useShortcuts({
meta_s: { usingInput: true, handler: () => save(false) },
meta_n: { usingInput: true, handler: () => add('markdown') },
meta_shift_n: { usingInput: true, handler: () => add('folder') },
meta_shift_z: { usingInput: true, handler: () => router.push({ name: 'explore' }) }
})
const tree = {
remove(data: ProjectExtendedItem[], id: string): ProjectExtendedItem[] {
return data
.filter(item => getPath(item) !== id)
.map((item) => {
if (tree.hasChildren(item)) {
return {
...item,
children: tree.remove(item.children ?? [], id),
};
}
return item;
});
},
insertBefore(data: ProjectExtendedItem[], targetId: string, newItem: ProjectExtendedItem): ProjectExtendedItem[] {
return data.flatMap((item) => {
if (getPath(item) === targetId)
return [newItem, item];
if (tree.hasChildren(item)) {
return {
...item,
children: tree.insertBefore(item.children ?? [], targetId, newItem),
};
}
return item;
});
},
insertAfter(data: ProjectExtendedItem[], targetId: string, newItem: ProjectExtendedItem): ProjectExtendedItem[] {
return data.flatMap((item) => {
if (getPath(item) === targetId)
return [item, newItem];
if (tree.hasChildren(item)) {
return {
...item,
children: tree.insertAfter(item.children ?? [], targetId, newItem),
};
}
return item;
});
},
insertChild(data: ProjectExtendedItem[], targetId: string, newItem: ProjectExtendedItem): ProjectExtendedItem[] {
return data.flatMap((item) => {
if (getPath(item) === targetId) {
// already a parent: add as first child
return {
...item,
// opening item so you can see where item landed
isOpen: true,
children: [newItem, ...item.children ?? []],
};
}
if (!tree.hasChildren(item))
return item;
return {
...item,
children: tree.insertChild(item.children ?? [], targetId, newItem),
};
});
},
find(data: ProjectExtendedItem[], itemId: string): ProjectExtendedItem | undefined {
for (const item of data) {
if (getPath(item) === itemId)
return item;
if (tree.hasChildren(item)) {
const result = tree.find(item.children ?? [], itemId);
if (result)
return result;
}
}
},
search(data: ProjectExtendedItem[], prop: keyof ProjectExtendedItem, value: string): ProjectExtendedItem[] {
const arr = [];
for (const item of data)
{
if (item[prop]?.toString().toLowerCase()?.startsWith(value.toLowerCase()))
arr.push(item);
if (tree.hasChildren(item)) {
arr.push(...tree.search(item.children ?? [], prop, value));
}
}
return arr;
},
getPathToItem({
current,
targetId,
parentIds = [],
}: {
current: ProjectExtendedItem[]
targetId: string
parentIds?: string[]
}): string[] | undefined {
for (const item of current) {
if (getPath(item) === targetId)
return parentIds;
const nested = tree.getPathToItem({
current: (item.children ?? []),
targetId,
parentIds: [...parentIds, getPath(item)],
});
if (nested)
return nested;
}
},
hasChildren(item: ProjectExtendedItem): boolean {
return (item.children ?? []).length > 0;
},
}
function add(type: FileType): void
{
if(!navigation.value)
{
return;
}
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 item: ProjectExtendedItem = { navigable: true, private: false, parent: '', path: '', title: title, name: parsePath(title), type: type, order: 0, children: type === 'folder' ? [] : undefined, customPath: false };
if(!selected.value)
{
navigation.value = [...navigation.value, item];
}
else if(selected.value?.children)
{
item.parent = getPath(selected.value);
navigation.value = tree.insertChild(navigation.value, item.parent, item);
}
else
{
navigation.value = tree.insertAfter(navigation.value, getPath(selected.value), item);
}
}
function updateTree(instruction: Instruction, itemId: string, targetId: string) : ProjectExtendedItem[] | undefined {
if(!navigation.value)
return;
const item = tree.find(navigation.value, itemId);
const target = tree.find(navigation.value, targetId);
if(!item)
return;
if (instruction.type === 'reparent') {
const path = tree.getPathToItem({
current: navigation.value,
targetId: targetId,
});
if (!path) {
console.error(`missing ${path}`);
return;
}
const desiredId = path[instruction.desiredLevel];
let result = tree.remove(navigation.value, itemId);
result = tree.insertAfter(result, desiredId, item);
return result;
}
// the rest of the actions require you to drop on something else
if (itemId === targetId)
return navigation.value;
if (instruction.type === 'reorder-above') {
let result = tree.remove(navigation.value, itemId);
result = tree.insertBefore(result, targetId, item);
return result;
}
if (instruction.type === 'reorder-below') {
let result = tree.remove(navigation.value, itemId);
result = tree.insertAfter(result, targetId, item);
return result;
}
if (instruction.type === 'make-child') {
if(!target || target.type !== 'folder')
return;
let result = tree.remove(navigation.value, itemId);
result = tree.insertChild(result, targetId, item);
rebuildPath([item], targetId);
return result;
}
return navigation.value;
}
function transform(items: ProjectItem[] | undefined): ProjectExtendedItem[] | undefined
{
return items?.map(e => ({...e, customPath: e.name !== parsePath(e.title), children: transform(e.children)}));
}
function drop(instruction: Instruction, itemId: string, targetId: string)
{
navigation.value = updateTree(instruction, itemId, targetId) ?? navigation.value ?? [];
}
function rebuildPath(tree: ProjectExtendedItem[] | null | undefined, parentPath: string)
{
if(!tree)
return;
tree.forEach(e => {
e.parent = parentPath;
rebuildPath(e.children, getPath(e));
});
}
async function save(redirect: boolean): Promise<void>
{
saveStatus.value = 'pending';
try {
await $fetch(`/api/project`, {
method: 'post',
body: project.value,
});
saveStatus.value = 'success';
toaster.clear('error');
toaster.add({
type: 'success', content: 'Contenu enregistré', timer: true, duration: 10000
});
if(redirect) router.push({ name: 'explore' });
} catch(e: any) {
toaster.add({
type: 'error', content: e.message, timer: true, duration: 10000
})
saveStatus.value = 'error';
}
}
function getPath(item: ProjectExtendedItem): string
{
return [item.parent, parsePath(item.customPath ? item.name : item.title)].filter(e => !!e).join('/');
}
</script>

View File

@@ -1,3 +1,42 @@
<template>
Index
</template>
<div v-if="status === 'pending'" class="flex">
<Head>
<Title>d[any] - Chargement</Title>
</Head>
<Loading />
</div>
<div class="flex flex-1 justify-start items-start" v-else-if="page">
<Head>
<Title>d[any] - Accueil</Title>
</Head>
<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 flex-row justify-between items-center">
<ProseH1>{{ page.title }}</ProseH1>
<div class="flex gap-4">
<NuxtLink :href="{ name: 'explore-edit-path', params: { path: 'index' } }"><Button v-if="isOwner">Modifier la page</Button></NuxtLink>
<NuxtLink :href="{ name: 'explore-edit' }"><Button v-if="isOwner">Configurer le projet</Button></NuxtLink>
</div>
</div>
<Markdown :content="page.content" />
</div>
</div>
<div v-else-if="status === 'error'">
<Head>
<Title>d[any] - Erreur</Title>
</Head>
<span>{{ error?.message }}</span>
</div>
<div v-else>
<Head>
<Title>d[any] - Erreur</Title>
</Head>
<div><ProseH2>Impossible d'afficher le contenu demandé</ProseH2></div>
</div>
</template>
<script setup lang="ts">
const { loggedIn, user } = useUserSession();
const { data: page, status, error } = await useFetch(`/api/file/index`);
const isOwner = computed(() => user.value?.id === page.value?.owner);
</script>

View File

@@ -1,14 +1,3 @@
<script setup lang="ts">
const open = ref(false), username = ref(""), price = ref(750), disabled = ref(false), loading = ref(false);
watch(loading, (value) => {
if(value)
{
setTimeout(() => { open.value = true; loading.value = false }, 1500);
}
})
</script>
<template>
<Head>
<Title>d[any] - Accueil</Title>

View File

@@ -1,4 +1,7 @@
<template>
<Head>
<Title>d[any] - Mentions légales</Title>
</Head>
<div class="flex flex-col max-w-[1200px] p-16">
<ProseH3>Mentions Légales</ProseH3>
<ProseH4>Collecte et Traitement des Données Personnelles</ProseH4>

48
pages/roadmap.vue Normal file
View File

@@ -0,0 +1,48 @@
<template>
<Head>
<Title>d[any] - Roadmap</Title>
</Head>
<div class="flex flex-col justify-start p-6">
<ProseH2>Roadmap</ProseH2>
<div class="grid grid-cols-4 gap-x-2 gap-y-4">
<div class="flex flex-col gap-2 justify-start">
<ProseH3>Administration</ProseH3>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Statistiques de consultation</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Statistiques de connexion</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Dashboard de statistiques</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Gestion de droits</span><ProseTag>prioritaire</ProseTag></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Synchro project <-> GIT</span><ProseTag>prioritaire</ProseTag></Label>
</div>
<div class="flex flex-col gap-2 justify-start">
<ProseH3>Editeur</ProseH3>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" checked disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class="text-light-60 dark:text-dark-60 line-through">Edition de page</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" checked disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class="text-light-60 dark:text-dark-60 line-through">Edition riche de page</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Edition live de page</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" checked disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class="text-light-60 dark:text-dark-60 line-through">Raccourcis d'edition</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Affichage alternatif par page</span></Label>
</div>
<div class="flex flex-col gap-2 justify-start">
<ProseH3>Projet</ProseH3>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" checked disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class="text-light-60 dark:text-dark-60 line-through">Edition du projet</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" checked disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class="text-light-60 dark:text-dark-60 line-through">Déplacement des fichiers</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Configuration de droit du projet</span><ProseTag>prioritaire</ProseTag></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Theme par projet</span></Label>
</div>
<div class="flex flex-col gap-2 justify-start">
<ProseH3>Nouvelles features</ProseH3>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Historique des modifs</span><ProseTag>prioritaire</ProseTag></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Commentaire par page</span></Label>
</div>
<div class="flex flex-col gap-2 justify-start">
<ProseH3>Utilisateur</ProseH3>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" checked disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class="text-light-60 dark:text-dark-60 line-through">Validation du compte par mail<ProseTag>prioritaire</ProseTag></span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Modification de profil</span></Label>
<Label class="flex flex-row gap-2 items-center"><CheckboxRoot class="border border-light-35 dark:border-dark-35 w-6 h-6 flex justify-center items-center" disabled><CheckboxIndicator><Icon icon="radix-icons:check" /></CheckboxIndicator></CheckboxRoot><span class=" ">Image de profil</span></Label>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { Icon } from '@iconify/vue/dist/iconify.js';
</script>

View File

@@ -1,6 +1,6 @@
<template>
<Head>
<Title>Connexion</Title>
<Title>d[any] - Connexion</Title>
</Head>
<div class="flex flex-1 flex-col justify-center items-center">
<div class="flex gap-8 items-center">

View File

@@ -0,0 +1,18 @@
<template>
<Head>
<Title>d[any] - Validation de votre adresse mail</Title>
</Head>
<div class="flex flex-col justify-center items-center">
<ProseH2>Votre compte a été validé ! 🎉</ProseH2>
<div class="flex flex-row gap-8">
<Button class="bg-light-25 dark:bg-dark-25"><NuxtLink :to="{ name: 'user-login', replace: true }">Se connecter</NuxtLink></Button>
<Button class="bg-light-25 dark:bg-dark-25"><NuxtLink :to="{ name: 'index', replace: true }">Retourner à l'accueil</NuxtLink></Button>
</div>
</div>
</template>
<script setup lang="ts">
definePageMeta({
layout: 'login'
})
</script>

View File

@@ -1,14 +1,29 @@
<script setup lang="ts">
import { hasPermissions } from "#shared/auth.util";
definePageMeta({
guestsGoesTo: '/user/login',
})
let { user, clear } = useUserSession();
const { user, clear } = useUserSession();
const toaster = useToast();
const loading = ref<boolean>(false);
async function revalidateUser()
{
loading.value = true;
await $fetch(`/api/users/${user.value?.id}/revalidate`, {
method: 'get'
});
loading.value = false;
toaster.add({ closeable: false, duration: 10000, timer: true, content: 'Un mail vous a été envoyé.', type: 'info' });
}
async function deleteUser()
{
loading.value = true;
await $fetch(`/api/users/${user.value?.id}`, {
method: 'delete'
});
loading.value = false;
clear();
}
</script>
@@ -16,7 +31,7 @@ async function deleteUser()
<template>
<Head>
<Title>Mon profil</Title>
<Title>d[any] - Mon profil</Title>
</Head>
<div class="grid lg:grid-cols-4 grid-col-2 w-full items-start py-8 gap-6 content-start" v-if="user">
<div class="flex flex-col gap-4 col-span-4 lg:col-span-3 border border-light-35 dark:border-dark-35 p-4">
@@ -34,14 +49,14 @@ async function deleteUser()
<template v-slot:content><span>Tant que votre adresse mail n'as pas été validée, vous n'avez que
des droits de lecture.</span></template>
</HoverCard>
<Tooltip message="En cours de développement"><Button class="ms-4" disabled>Renvoyez un mail</Button></Tooltip>
<Button class="ms-4" @click="revalidateUser" :loading="loading">Renvoyez un mail</Button>
</div>
</div>
<div class="flex flex-col self-center flex-1 gap-4">
<Button @click="async () => await clear()">Se deconnecter</Button>
<Button @click="clear">Se deconnecter</Button>
<Button disabled><Tooltip message="En cours de développement">Modifier mon profil</Tooltip></Button>
<AlertDialogRoot>
<AlertDialogTrigger asChild><Button
<AlertDialogTrigger asChild><Button :loading="loading"
class="border-light-red dark:border-dark-red hover:border-light-red dark:hover:border-dark-red hover:bg-light-redBack dark:hover:bg-dark-redBack text-light-red dark:text-dark-red focus:shadow-light-red dark:focus:shadow-dark-red">Supprimer
mon compte</Button></AlertDialogTrigger>
<AlertDialogPortal>

View File

@@ -1,6 +1,6 @@
<template>
<Head>
<Title>Inscription</Title>
<Title>d[any] - Inscription</Title>
</Head>
<div class="flex flex-1 flex-col justify-center items-center">
<div class="flex gap-8 items-center">
@@ -11,19 +11,13 @@
<TextInput type="text" label="Nom d'utilisateur" autocomplete="username" v-model="state.username" class="w-full md:w-auto"/>
<TextInput type="email" label="Email" autocomplete="email" v-model="state.email" class="w-full md:w-auto"/>
<TextInput type="password" label="Mot de passe" autocomplete="new-password" v-model="state.password" class="w-full md:w-auto"/>
<div class="flex flex-col font-light border border-light-35 dark:border-dark-35 px-4 py-2 m-4 ms-0 text-sm leading-[18px] lg:text-base order-8 col-span-2 md:col-span-1 md:order-none">
<span class="">Votre mot de passe doit respecter les critères de sécurité suivants
:</span>
<span class="ps-4" :class="{'text-light-red dark:text-dark-red': !checkedLength}">Entre 8 et 128
caractères</span>
<span class="ps-4" :class="{'text-light-red dark:text-dark-red': !checkedLowerUpper}">Au moins
une minuscule et une majuscule</span>
<span class="ps-4" :class="{'text-light-red dark:text-dark-red': !checkedDigit}">Au moins un
chiffre</span>
<span class="ps-4" :class="{'text-light-red dark:text-dark-red': !checkedSymbol}">Au moins un
caractère spécial parmi la liste suivante:
<pre class="text-wrap">! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ ] ^ _ ` { | } ~</pre>
</span>
<div class="grid grid-cols-2 flex-col font-light border border-light-35 dark:border-dark-35 px-4 py-2 m-4 ms-0 text-sm leading-[18px] lg:text-base order-8 col-span-2 md:col-span-1 md:order-none">
<span class="col-span-2">Prérequis de sécurité</span>
<span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedLength}"><Icon v-show="!checkedLength" icon="radix-icons:cross-2" />8 à 128 caractères</span>
<span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedLower}"><Icon v-show="!checkedLower" icon="radix-icons:cross-2" />Une minuscule</span>
<span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedUpper}"><Icon v-show="!checkedUpper" icon="radix-icons:cross-2" />Une majuscule</span>
<span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedDigit}"><Icon v-show="!checkedDigit" icon="radix-icons:cross-2" />Un chiffre</span>
<span class="ps-4 flex items-center gap-2" :class="{'text-light-red dark:text-dark-red': !checkedSymbol}"><Icon v-show="!checkedSymbol" icon="radix-icons:cross-2" />Un caractère special</span>
</div>
<TextInput type="password" label="Confirmation du mot de passe" autocomplete="new-password" v-model="confirmPassword" class="w-full md:w-auto"/>
<Button class="border border-light-35 dark:border-dark-35 max-w-48 w-full order-9 col-span-2 md:col-span-1 m-auto" :loading="status === 'pending'">S'inscrire</Button>
@@ -52,7 +46,8 @@ const { add: addToast, clear: clearToasts } = useToast();
const confirmPassword = ref("");
const checkedLength = computed(() => state.password.length >= 8 && state.password.length <= 128);
const checkedLowerUpper = computed(() => state.password.toLowerCase() !== state.password && state.password.toUpperCase() !== state.password);
const checkedLower = computed(() => state.password.toUpperCase() !== state.password);
const checkedUpper = computed(() => state.password.toLowerCase() !== state.password);
const checkedDigit = computed(() => /[0-9]/.test(state.password));
const checkedSymbol = computed(() => " !\"#$%&'()*+,-./:;<=>?@[]^_`{|}~".split("").some(e => state.password.includes(e)));

BIN
public/logo.light.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

View File

@@ -1,13 +1,16 @@
import { z } from "zod";
export const fileType = z.enum(['folder', 'file', 'markdown', 'canvas']);
export const schema = z.object({
path: z.string(),
owner: z.number(),
owner: z.number().finite(),
title: z.string(),
type: z.enum(['folder', 'file', 'markdown', 'canvas']),
type: fileType,
content: z.string(),
navigable: z.boolean(),
private: z.boolean(),
order: z.number().finite(),
});
export type FileType = z.infer<typeof fileType>;
export type File = z.infer<typeof schema>;

16
schemas/navigation.ts Normal file
View File

@@ -0,0 +1,16 @@
import { z } from "zod";
import { fileType } from "./file";
export const single = z.object({
path: z.string(),
owner: z.number().finite(),
title: z.string(),
type: fileType,
navigable: z.boolean(),
private: z.boolean(),
order: z.number().finite(),
});
export const table = z.array(single);
export type Navigation = z.infer<typeof table>;
export type NavigationItem = z.infer<typeof single>;

24
schemas/project.ts Normal file
View File

@@ -0,0 +1,24 @@
import { z } from "zod";
import { fileType } from "./file";
const baseItem = z.object({
path: z.string(),
parent: z.string(),
name: z.string(),
title: z.string(),
type: fileType,
navigable: z.boolean(),
private: z.boolean(),
order: z.number().finite(),
});
export const item: z.ZodType<ProjectItem> = baseItem.extend({
children: z.lazy(() => item.array().optional()),
});
export const project = z.object({
items: z.array(item),
});
export type Project = z.infer<typeof project>;
export type ProjectItem = z.infer<typeof baseItem> & {
children?: ProjectItem[]
};

View File

@@ -1,3 +1,13 @@
import { hasPermissions } from "#shared/auth.util";
declare module 'nitropack'
{
interface TaskPayload
{
type: string
}
}
export default defineEventHandler(async (e) => {
const session = await getUserSession(e);
@@ -7,19 +17,31 @@ export default defineEventHandler(async (e) => {
return;
}
const id = getRouterParam(e, 'id');
const payload: Record<string, any> = await readBody(e);
if(!id)
{
setResponseStatus(e, 400);
return;
}
payload.type = id;
payload.data = JSON.parse(payload.data);
const result = await runTask(id);
const result = await runTask(id, {
payload: payload
});
if(!result.result)
{
setResponseStatus(e, 500);
throw result.error ?? new Error('Erreur inconnue');
if(result.error && (result.error as Error).message)
throw result.error;
else if(result.error)
throw new Error(result.error);
else
throw new Error('Erreur inconnue');
}
return
return;
});

View File

@@ -73,6 +73,19 @@ export default defineEventHandler(async (e): Promise<Return> => {
logSession(e, await setUserSession(e, { user: { id: id.id, username: body.data.username, email: body.data.email, state: 0, signin: new Date(), permissions: [] } }) as UserSessionRequired);
await runTask('mail', {
payload: {
type: 'mail',
to: [body.data.email],
template: 'registration',
data: {
username: body.data.username,
timestamp: Date.now(),
id: id.id,
}
}
});
setResponseStatus(e, 201);
return { success: true, session };
}

View File

@@ -21,6 +21,7 @@ export default defineEventHandler(async (e) => {
'content': sql<string>`cast(${explorerContentTable.content} as TEXT)`.as('content'),
'navigable': explorerContentTable.navigable,
'private': explorerContentTable.private,
'order': explorerContentTable.order,
}).from(explorerContentTable).where(eq(explorerContentTable.path, sql.placeholder('path'))).prepare().get({ path });
if(content !== undefined)

View File

@@ -1,21 +1,29 @@
import useDatabase from '~/composables/useDatabase';
import { explorerContentTable } from '~/db/schema';
import type { Navigation } from '~/types/api';
import type { NavigationItem } from '~/schemas/navigation';
export type NavigationTreeItem = NavigationItem & { children?: NavigationTreeItem[] };
export default defineEventHandler(async (e) => {
const { user } = await getUserSession(e);
/*if(!user)
{
throw createError({ statusCode: 401, statusText: 'Unauthorized' });
}*/
const db = useDatabase();
const content = db.select({ path: explorerContentTable.path, title: explorerContentTable.title, type: explorerContentTable.type, private: explorerContentTable.private, navigable: explorerContentTable.navigable, owner: explorerContentTable.owner }).from(explorerContentTable).prepare().all() as (Navigation & { owner: number, navigable: boolean })[];
const content = db.select({
path: explorerContentTable.path,
type: explorerContentTable.type,
owner: explorerContentTable.owner,
title: explorerContentTable.title,
navigable: explorerContentTable.navigable,
private: explorerContentTable.private,
order: explorerContentTable.order,
}).from(explorerContentTable).all();
content.sort((a, b) => {
return a.path.split('/').length - b.path.split('/').length;
});
if(content.length > 0)
{
const navigation: Navigation[] = [];
const navigation: NavigationTreeItem[] = [];
for(const idx in content)
{
@@ -43,9 +51,10 @@ export default defineEventHandler(async (e) => {
}
setResponseStatus(e, 404);
return;
});
function addChild(arr: Navigation[], e: Navigation): void
function addChild(arr: NavigationTreeItem[], e: NavigationItem): void
{
const parent = arr.find(f => e.path.startsWith(f.path));
@@ -58,6 +67,11 @@ function addChild(arr: Navigation[], e: Navigation): void
}
else
{
arr.push({ title: e.title, path: e.path, type: e.type, private: e.private });
arr.push({ ...e });
arr.sort((a, b) => {
if(a.order !== b.order)
return a.order - b.order;
return a.title.localeCompare(b.title);
});
}
}

80
server/api/project.get.ts Normal file
View File

@@ -0,0 +1,80 @@
import useDatabase from '~/composables/useDatabase';
import { explorerContentTable } from '~/db/schema';
import type { NavigationItem } from '~/schemas/navigation';
import type { ProjectItem, Project } from '~/schemas/project';
import { hasPermissions } from '~/shared/auth.util';
export default defineEventHandler(async (e) => {
const { user } = await getUserSession(e);
if(!user || !hasPermissions(user.permissions, ['editor', 'admin']))
{
throw createError({
statusCode: 401,
statusMessage: 'Unauthorized',
});
}
const db = useDatabase();
const content = db.select({
path: explorerContentTable.path,
type: explorerContentTable.type,
owner: explorerContentTable.owner,
title: explorerContentTable.title,
navigable: explorerContentTable.navigable,
private: explorerContentTable.private,
order: explorerContentTable.order,
}).from(explorerContentTable).prepare().all();
content.sort((a, b) => {
return a.path.split('/').length - b.path.split('/').length;
});
if(content.length > 0)
{
const project: Project = {
items: [],
}
for(const item of content.filter(e => !!e))
{
addChild(project.items, item);
}
return project;
}
setResponseStatus(e, 404);
return;
});
function addChild(arr: ProjectItem[], e: NavigationItem): 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({
path: e.path,
parent: e.path.substring(0, e.path.lastIndexOf('/')),
name: e.path.substring(e.path.lastIndexOf('/') + 1),
title: e.title,
type: e.type,
navigable: e.navigable,
private: e.private,
order: e.order,
});
arr.sort((a, b) => {
if(a.order !== b.order)
return a.order - b.order;
return a.title.localeCompare(b.title);
});
}
}

View File

@@ -0,0 +1,76 @@
import { hasPermissions } from "#shared/auth.util";
import useDatabase from '~/composables/useDatabase';
import { explorerContentTable } from '~/db/schema';
import { project, type ProjectItem } from '~/schemas/project';
import { parsePath } from "#shared/general.utils";
import { eq, getTableColumns } from "drizzle-orm";
export default defineEventHandler(async (e) => {
const { user } = await getUserSession(e);
if(!user || !hasPermissions(user.permissions, ['admin', 'editor']))
{
throw createError({ statusCode: 401, statusText: 'Unauthorized' });
}
const body = await readValidatedBody(e, project.safeParse);
if(!body.success)
{
throw body.error;
}
const items = buildOrder(body.data.items);
const db = useDatabase();
const { content, ...cols } = getTableColumns(explorerContentTable);
const full = db.select(cols).from(explorerContentTable).all();
for(let i = full.length - 1; i >= 0; i--)
{
if(items.find(e => (e.path === '' ? [e.parent, parsePath(e.name === '' ? e.title : e.name)].filter(e => !!e).join('/') : e.path) === full[i].path))
full.splice(i, 1);
}
db.transaction((tx) => {
for(let i = 0; i < items.length; i++)
{
const item = items[i];
tx.insert(explorerContentTable).values({
path: item.path,
owner: user.id,
title: item.title,
type: item.type,
navigable: item.navigable,
private: item.private,
order: item.order,
content: null,
}).onConflictDoUpdate({
set: {
path: [item.parent, parsePath(item.name === '' ? item.title : item.name)].filter(e => !!e).join('/'),
title: item.title,
type: item.type,
navigable: item.navigable,
private: item.private,
order: item.order,
},
target: explorerContentTable.path,
}).run();
}
for(let i = 0; i < full.length; i++)
{
tx.delete(explorerContentTable).where(eq(explorerContentTable.path, full[i].path)).run();
}
});
});
function buildOrder(items: ProjectItem[]): ProjectItem[]
{
items.forEach((e, i) => {
e.order = i;
if(e.children) e.children = buildOrder(e.children);
});
return items.flatMap(e => [e, ...(e.children ?? [])]);
}

View File

@@ -0,0 +1,64 @@
import { eq } from "drizzle-orm";
import useDatabase from "~/composables/useDatabase";
import { usersTable } from "~/db/schema";
export default defineEventHandler(async (e) => {
const session = await getUserSession(e);
if(!session || !session.user || !session.user.id)
{
return createError({
statusCode: 401,
message: 'Unauthorized',
});
}
const id = getRouterParam(e, 'id');
if(!id)
{
return createError({
statusCode: 403,
message: 'Forbidden',
});
}
if(session.user.id.toString() !== id)
{
return createError({
statusCode: 401,
message: 'Unauthorized',
});
}
const db = useDatabase();
const data = db.select({ state: usersTable.state }).from(usersTable).where(eq(usersTable.id, session.user.id)).get();
if(!data)
{
return createError({
statusCode: 401,
message: 'Unauthorized',
});
}
if(data.state === 1)
{
setResponseStatus(e, 200);
return;
}
await runTask('mail', {
payload: {
type: 'mail',
to: [session.user.email],
template: 'registration', //@TODO
data: {
username: session.user.username,
timestamp: Date.now(),
id: session.user.id,
}
}
});
setResponseStatus(e, 200);
return;
})

View File

@@ -0,0 +1,16 @@
<template>
<div style='margin-left: auto; margin-right: auto; width: 75%; font-family: ui-sans-serif, system-ui, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji"; font-size: 1rem; line-height: 1.5rem; color: #171717;'>
<div style="margin-left: auto; margin-right: auto; text-align: center;">
<a href="https://obsidian.peaceultime.com">
<img src="https://obsidian.peaceultime.com/logo.light.png" alt="Logo" title="d[any] logo" width="64" height="64" style="display: block; height: 4rem; width: 4rem; margin-left: auto; margin-right: auto;" />
<span style="margin-inline-end: 1rem; font-size: 1.5rem; line-height: 2rem; font-weight: 700; font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;">d[any]</span>
</a>
</div>
<div style="padding: 1rem;">
<slot></slot>
</div>
</div>
<div style="background-color: #171717;">
<p style="padding-top: 1rem; padding-bottom: 1rem; text-align: center; font-size: 0.75rem; line-height: 1rem; color: #fff;">Copyright Peaceultime - d[any] - 2024</p>
</div>
</template>

View File

@@ -0,0 +1,26 @@
<template>
<div style="max-width: 800px; margin-left: auto; margin-right: auto;">
<p style="font-variant: small-caps; margin-bottom: 1rem; font-size: 1.25rem; line-height: 1.75rem;">Bienvenue sur d[any], <span>{{ username }}</span>.</p>
<p>Nous vous invitons à valider votre compte afin de profiter de toutes les fonctionnalités de d[any].</p>
<div style="padding-top: 1rem; padding-bottom: 1rem; text-align: center;">
<a :href="`https://obsidian.peaceultime.com/user/mailvalidation?u=${id}&t=${timestamp}&h=${hash}`" target="_blank"><span style="display: inline-block; border-width: 1px; border-color: #525252; background-color: #e5e5e5; padding-left: 0.75rem; padding-right: 0.75rem; padding-top: 0.25rem; padding-bottom: 0.25rem; font-weight: 200; color: #171717; text-decoration: none;">Je valide mon compte</span></a>
<span style="display: block; padding-top: 0.5rem; font-size: 0.75rem; line-height: 1rem;">Ce lien est valable 1 heure.</span>
</div>
<div>
<span>Vous pouvez egalement copier le lien suivant pour valider votre compte: </span>
<pre style="display: inline-block; border-bottom-width: 1px; font-size: 0.75rem; line-height: 1rem; color: #171717; font-weight: 400; text-decoration: none;">{{ `https://obsidian.peaceultime.com/user/mailvalidation?u=${id}&t=${timestamp}&h=${hash}` }}</pre>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import Bun from 'bun';
const { id, username, timestamp } = defineProps<{
id: number
username: string
timestamp: number
}>();
const hash = computed(() => Bun.hash(id.toString(), timestamp));
</script>

View File

@@ -0,0 +1,54 @@
import { eq } from "drizzle-orm";
import { z } from "zod";
import useDatabase from "~/composables/useDatabase";
import { usersTable } from "~/db/schema";
const schema = z.object({
h: z.coerce.string(),
u: z.coerce.number(),
t: z.coerce.number(),
});
export default defineEventHandler(async (e) => {
const query = await getValidatedQuery(e, schema.safeParse);
if(!query.success)
throw query.error;
if(Bun.hash(query.data.u.toString(), query.data.t).toString() !== query.data.h)
{
return createError({
statusCode: 400,
message: 'Lien incorrect',
})
}
if(Date.now() > query.data.t + (60 * 60 * 1000))
{
return createError({
statusCode: 400,
message: 'Le lien a expiré',
})
}
const db = useDatabase();
const result = db.select({ state: usersTable.state }).from(usersTable).where(eq(usersTable.id, query.data.u)).get();
if(result === undefined)
{
return createError({
statusCode: 400,
message: 'Aucune donnée utilisateur trouvée',
})
}
if(result?.state === 1)
{
return createError({
statusCode: 400,
message: 'Votre compte a déjà été validé',
})
}
db.update(usersTable).set({ state: 1 }).where(eq(usersTable.id, query.data.u)).run();
sendRedirect(e, '/user/mailvalidated');
})

110
server/tasks/mail.ts Normal file
View File

@@ -0,0 +1,110 @@
import nodemailer from 'nodemailer';
import { createSSRApp, h } from 'vue';
import { renderToString } from 'vue/server-renderer';
import base from '../components/mail/base.vue';
import registration from '../components/mail/registration.vue';
//import revalidation from '../components/mail/revalidation.vue';
const config = useRuntimeConfig();
const [domain, selector, dkim] = config.mail.dkim.split(":");
export const templates: Record<string, { component: any, subject: string }> = {
"registration": { component: registration, subject: 'Bienvenue sur d[any] 😎' },
// "revalidate-mail": { component: revalidation, subject: 'd[any]: Valider votre email' },
};
import 'nitropack/types';
import type Mail from 'nodemailer/lib/mailer';
declare module 'nitropack/types'
{
interface TaskPayload
{
type: 'mail'
to: string[]
template: string
data: Record<string, any>
}
}
const transport = nodemailer.createTransport({
//@ts-ignore
pool: true,
host: config.mail.host,
port: config.mail.port,
secure: false,
auth: {
user: config.mail.user,
pass: config.mail.passwd,
},
requireTLS: true,
dkim: {
domainName: domain,
keySelector: selector,
privateKey: dkim,
},
});
export default defineTask({
meta: {
name: 'mail',
description: 'Send email',
},
async run(e) {
try {
if(e.payload.type !== 'mail')
{
throw new Error(`Données inconnues`);
}
const payload = e.payload;
const template = templates[payload.template];
if(!template)
{
throw new Error(`Modèle de mail ${payload.template} inconnu`);
}
console.time('Generating HTML');
const mail: Mail.Options = {
from: 'd[any] - Ne pas répondre <no-reply@peaceultime.com>',
to: payload.to,
html: await render(template.component, payload.data),
subject: template.subject,
textEncoding: 'quoted-printable',
};
console.timeEnd('Generating HTML');
if(mail.html === '')
return { result: false, error: new Error("Invalid content") };
console.time('Sending Mail');
const status = await transport.sendMail(mail);
console.timeEnd('Sending Mail');
if(status.rejected.length > 0)
{
return { result: false, error: status.response, details: status.rejectedErrors };
}
return { result: true };
}
catch(e)
{
return { result: false, error: e };
}
},
})
async function render(component: any, data: Record<string, any>): Promise<string>
{
const app = createSSRApp({
render(){
return h(base, null, { default: () => h(component, data, { default: () => null }) });
}
});
const html = await renderToString(app);
return (`<html><body><div>${html}</div></body></html>`);
}

View File

@@ -1,6 +1,6 @@
import useDatabase from "~/composables/useDatabase";
import { extname, basename } from 'node:path';
import type { File, FileType, Tag } from '~/types/api';
import type { FileType } from '~/types/api';
import type { CanvasColor, CanvasContent } from "~/types/canvas";
import { explorerContentTable } from "~/db/schema";
@@ -11,8 +11,8 @@ const typeMapping: Record<string, FileType> = {
export default defineTask({
meta: {
name: 'sync',
description: 'Synchronise the project with Obsidian',
name: 'pull',
description: 'Pull the data from Git',
},
async run(event) {
try {
@@ -25,10 +25,9 @@ export default defineTask({
recursive: true,
per_page: 1000,
}
}) as any;
}) as { tree: any[] } & Record<string, any>;
const files: typeof explorerContentTable.$inferInsert = await Promise.all(tree.tree.filter((e: any) => !e.path.startsWith(".")).map(async (e: any) => {
const files: typeof explorerContentTable.$inferInsert = await Promise.all(tree.tree.filter((e: any) => !e.path.startsWith(".")).map(async (e, i) => {
if(e.type === 'tree')
{
const title = basename(e.path);
@@ -36,13 +35,13 @@ export default defineTask({
const path = (e.path as string).split('/').map(f => { const check = /(\d+)\. ?(.+)/gsmi.exec(f); return check && check[2] ? check[2] : f }).join('/');
return {
path: path.toLowerCase().replaceAll(" ", "-").normalize("NFD").replace(/[\u0300-\u036f]/g, ""),
//order: order && order[1] ? order[1] : 50,
order: i,
title: order && order[2] ? order[2] : title,
type: 'folder',
content: null,
owner: '1',
navigable: true,
private: e.path.startsWith('98.Privé')
private: e.path.startsWith('98.Privé'),
}
}
@@ -54,7 +53,7 @@ export default defineTask({
return {
path: (extension === '.md' ? path.replace(extension, '') : path).toLowerCase().replaceAll(" ", "-").normalize("NFD").replace(/[\u0300-\u036f]/g, ""),
//order: order && order[1] ? order[1] : 50,
order: i,
title: order && order[2] ? order[2] : title,
type: (typeMapping[extension] ?? 'file'),
content: reshapeContent(content as string, typeMapping[extension] ?? 'File'),
@@ -64,77 +63,18 @@ export default defineTask({
}
}));
/*let tags: Tag[] = [];
const tagFile = files.find(e => e.path === "tags");
if(tagFile)
{
const parsed = useMarkdown()(tagFile.content);
const titles = parsed.children.filter(e => e.type === 'element' && e.tagName.match(/h\d/));
for(let i = 0; i < titles.length; i++)
{
const start = titles[i].position?.start.offset ?? 0;
const end = titles.length === i + 1 ? tagFile.content.length : titles[i + 1].position.start.offset - 1;
tags.push({ tag: titles[i].properties.id, description: tagFile.content.substring(titles[i].position?.end.offset + 1, end) });
}
}*/
const db = useDatabase();
db.delete(explorerContentTable).run();
db.insert(explorerContentTable).values(files).run();
/*const oldFiles = db.prepare(`SELECT * FROM explorer_files WHERE project = ?1`).all('1') as File[];
const removeFiles = db.prepare(`DELETE FROM explorer_files WHERE project = ?1 AND path = ?2`);
db.transaction((data: File[]) => data.forEach(e => removeFiles.run('1', e.path)))(oldFiles.filter(e => !files.find(f => f.path = e.path)));
removeFiles.finalize();
const oldTags = db.prepare(`SELECT * FROM explorer_tags WHERE project = ?1`).all('1') as Tag[];
const removeTags = db.prepare(`DELETE FROM explorer_tags WHERE project = ?1 AND tag = ?2`);
db.transaction((data: Tag[]) => data.forEach(e => removeTags.run('1', e.tag)))(oldTags.filter(e => !tags.find(f => f.tag = e.tag)));
removeTags.finalize();
const insertFiles = db.prepare(`INSERT INTO explorer_files("project", "path", "owner", "title", "order", "type", "content") VALUES (1, $path, 1, $title, $order, $type, $content)`);
const updateFiles = db.prepare(`UPDATE explorer_files SET content = $content WHERE project = 1 AND path = $path`);
db.transaction((content) => {
for (const item of content) {
let order = item.order;
if (typeof order === 'string')
order = parseInt(item.order, 10);
if (isNaN(order))
order = 999;
if(oldFiles.find(e => item.path === e.path))
updateFiles.run({ $path: item.path, $content: item.content });
else
insertFiles.run({ $path: item.path, $title: item.title, $type: item.type, $content: item.content, $order: order });
}
})(files);
insertFiles.finalize();
updateFiles.finalize();
const insertTags = db.prepare(`INSERT INTO explorer_tags("project", "tag", "description") VALUES (1, $tag, $description)`);
const updateTags = db.prepare(`UPDATE explorer_tags SET description = $description WHERE project = 1 AND tag = $tag`);
db.transaction((content) => {
for (const item of content) {
if (oldTags.find(e => item.tag === e.tag))
updateTags.run({ $tag: item.tag, $description: item.description });
else
insertTags.run({ $tag: item.tag, $description: item.description });
}
})(tags);
insertTags.finalize();
updateTags.finalize();*/
useStorage('cache').clear();
return { result: true };
}
catch(e)
{
console.error(e);
return { result: false, error: e };
}
},

39
server/tasks/push.ts Normal file
View File

@@ -0,0 +1,39 @@
import useDatabase from "~/composables/useDatabase";
import type { FileType } from '~/types/api';
import { explorerContentTable } from "~/db/schema";
import { eq, ne } from "drizzle-orm";
const typeMapping: Record<string, FileType> = {
".md": "markdown",
".canvas": "canvas"
};
export default defineTask({
meta: {
name: 'push',
description: 'Push the data to Git',
},
async run(event) {
try {
const tree = await $fetch('https://git.peaceultime.com/api/v1/repos/peaceultime/system-aspect/git/trees/master', {
method: 'get',
headers: {
accept: 'application/json',
},
params: {
recursive: true,
per_page: 1000,
}
}) as any;
const db = useDatabase();
const files = db.select().from(explorerContentTable).where(ne(explorerContentTable.type, 'folder')).all();
return { result: true };
}
catch(e)
{
return { result: false, error: e };
}
},
})

View File

@@ -1,7 +1,13 @@
import type { FileType } from "~/schemas/file";
export function unifySlug(slug: string | string[]): string
{
return (Array.isArray(slug) ? slug.join('/') : slug);
}
export function parsePath(path: string): string
{
return path.toLowerCase().replaceAll(" ", "-").normalize("NFD").replaceAll(/[\u0300-\u036f]/g, "").replaceAll('(', '').replaceAll(')', '');
}
export function parseId(id: string | undefined): string |undefined
{
return id?.normalize('NFD')?.replace(/[\u0300-\u036f]/g, '')?.replace(/^\d\. */g, '')?.replace(/\s/g, "-")?.replace(/%/g, "-percent")?.replace(/\?/g, "-q")?.toLowerCase();
@@ -39,4 +45,11 @@ export function clamp(x: number, min: number, max: number): number {
if (x < min)
return min;
return x;
}
export const iconByType: Record<FileType, string> = {
'folder': 'lucide:folder',
'canvas': 'ph:graph-light',
'file': 'radix-icons:file',
'markdown': 'radix-icons:file',
}