Skip to content

📚 The open-source, offline-first Notion, Obsidian & Confluence alternative. Advanced Markdown, multi-tenant teams, OIDC/SSO, and local S3 backups. Deploy in one command.

feat: offline mode & new nodes stores (#557)

Smaug5d7ab18afb85
diff --git a/frontend/.env b/frontend/.env
index ae113dcd..d54d0b00 100644
--- a/frontend/.env
+++ b/frontend/.env
@@ -1,6 +1,8 @@
+NUXT_PUBLIC_BASE_URL=http://localhost:3000
NUXT_PUBLIC_BASE_API=http://localhost:8201
NUXT_PUBLIC_BASE_CDN=http://localhost:9000
+
NUXT_PUBLIC_CONFIG_DISABLE_LANDING_PAGE=false
NUXT_PUBLIC_CONFIG_DISABLE_SIGNUP_PAGE=false
NUXT_PUBLIC_CONFIG_DISABLE_NATIVE_LOGIN=false
\ No newline at end of file
diff --git a/frontend/app/App.vue b/frontend/app/App.vue
index 9f4d164f..62f445b6 100644
--- a/frontend/app/App.vue
+++ b/frontend/app/App.vue
@@ -36,7 +36,7 @@ watch(
watch(
interfaceStyle,
style => {
- document.documentElement.classList.toggle('glassmorphism', style === 'glassmorphism');
+ if (import.meta.client) document.documentElement.classList.toggle('glassmorphism', style === 'glassmorphism');
},
{ immediate: true },
);
@@ -49,12 +49,35 @@ watch(
{ immediate: true },
);
-router.beforeEach((to, from, next) => {
+router.beforeEach((to, from) => {
if (to.path.startsWith('/dashboard') && (from.path === '/login' || from.path === '/')) {
console.log('Setting loading state to true');
isLoading.value = true;
}
- next();
+ return;
+});
+
+useHead({
+ link: [
+ {
+ rel: 'canonical',
+ href: __BASE_URL__,
+ },
+ {
+ rel: 'preconnect',
+ href: __BASE_API__,
+ },
+ {
+ rel: 'preconnect',
+ href: __BASE_CDN__,
+ },
+ ],
+ meta: [
+ {
+ property: 'og:url',
+ content: __BASE_URL__,
+ },
+ ],
});
</script>
diff --git a/frontend/app/components/AppSelect.vue b/frontend/app/components/AppSelect.vue
index dd2c7fe8..b3847711 100644
--- a/frontend/app/components/AppSelect.vue
+++ b/frontend/app/components/AppSelect.vue
@@ -95,9 +95,21 @@ const emit = defineEmits(['update:modelValue']);
const { isMobile } = useDevice();
const { t } = useI18nT();
+const localValue = ref(props.modelValue ?? '');
+
+watch(
+ () => props.modelValue,
+ newVal => {
+ localValue.value = newVal ?? '';
+ },
+);
+
const selectedId = computed({
- get: () => props.modelValue ?? '',
- set: val => emit('update:modelValue', val),
+ get: () => localValue.value,
+ set: val => {
+ localValue.value = val;
+ emit('update:modelValue', val);
+ },
});
const open = ref(false);
const search = ref('');
@@ -123,7 +135,6 @@ const selected = computed(() => {
const clearSelection = () => {
selectedId.value = '';
- emit('update:modelValue', null);
toggleDropdown();
};
@@ -191,7 +202,6 @@ function handleKeyDown(event: KeyboardEvent) {
function handleSelect(node: ANode) {
selectedId.value = node.id;
- emit('update:modelValue', node.id);
closeDropdown();
}
diff --git a/frontend/app/components/Icon.vue b/frontend/app/components/Icon.vue
index e08fa4f1..4a52521b 100644
--- a/frontend/app/components/Icon.vue
+++ b/frontend/app/components/Icon.vue
@@ -1,6 +1,6 @@
<template>
<svg v-if="isSpriteIcon" class="icon" :class="display" :style="{ color: fill || 'currentColor', width: size, height: size }" aria-hidden="true">
- <use :href="`#icon-${name}`" />
+ <use :xlink:href="`#icon-${name}`" />
</svg>
<!-- eslint-disable-next-line vue/no-v-html | OK Because not a user entry-->
diff --git a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue b/frontend/app/components/MarkdownEditor/MarkdownEditor.vue
index ade44cd0..349caf54 100644
--- a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue
+++ b/frontend/app/components/MarkdownEditor/MarkdownEditor.vue
@@ -1,12 +1,12 @@
<!-- eslint-disable vue/no-v-html -->
<template>
<div class="editor-wrapper">
- <Teleport to="#navbar-title"> {{ t('components.editor.title') }}</Teleport>
+ <Teleport v-if="!public" to="#navbar-title"> {{ t('components.editor.title') }}</Teleport>
<div class="editor-container">
<!-- Toolbar Section -->
- <Toolbar v-model="document" @execute-action="handleToolbarAction" />
+ <Toolbar v-model="document" :public="public" @execute-action="handleToolbarAction" />
<!-- Compact Document Metadata -->
<div class="document-meta">
@@ -61,7 +61,7 @@ const resourcesStore = useResourcesStore();
const nodesStore = useNodesStore();
const preferences = usePreferencesStore();
-const props = defineProps<{ doc?: Partial<Node> }>();
+const props = defineProps<{ doc?: Partial<Node>; public?: boolean }>();
const emit = defineEmits(['save', 'exit', 'autoSave']);
const editorContainer = ref<HTMLDivElement>();
diff --git a/frontend/app/components/MarkdownEditor/Toolbar.vue b/frontend/app/components/MarkdownEditor/Toolbar.vue
index 5a8fef56..e9c0a5a4 100644
--- a/frontend/app/components/MarkdownEditor/Toolbar.vue
+++ b/frontend/app/components/MarkdownEditor/Toolbar.vue
@@ -1,7 +1,7 @@
<template>
<div class="toolbar">
<!-- Text Formatting Group -->
- <Teleport to="#navbar-actions">
+ <Teleport to="#navbar-actions" :disabled="public">
<div v-if="displayStats" class="stats-badge no-tablet">
<div class="stat-item">
<span class="stat-value">{{ stats.words }}</span>
@@ -125,6 +125,7 @@ const modals = useModal();
const props = defineProps<{
modelValue: Partial<Node>;
+ public?: boolean;
}>();
const preferences = usePreferencesStore();
diff --git a/frontend/app/components/Node/Action/ContextMenu.vue b/frontend/app/components/Node/Action/ContextMenu.vue
index f2238ba5..6ac04ac9 100644
--- a/frontend/app/components/Node/Action/ContextMenu.vue
+++ b/frontend/app/components/Node/Action/ContextMenu.vue
@@ -22,7 +22,7 @@
</button>
</div>
- <div v-if="nodeStore.hasPermissions(node, 4)" class="menu-group">
+ <div v-if="nodesPermissionsStore.hasPermissions(node, 4)" class="menu-group">
<button class="menu-item" @click="action('manageAccess')"><Icon name="manage_access" />{{ t('nodes.actions.managePermissions') }}</button>
</div>
@@ -45,6 +45,7 @@ const props = defineProps<{ node: Node; contextMenu?: boolean }>();
const emit = defineEmits(['close']);
const nodeStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const userStore = useUserStore();
const preferences = usePreferencesStore();
diff --git a/frontend/app/components/Node/Action/ResourceContextMenu.vue b/frontend/app/components/Node/Action/ResourceContextMenu.vue
index 1acf6e1f..c6e2cac7 100644
--- a/frontend/app/components/Node/Action/ResourceContextMenu.vue
+++ b/frontend/app/components/Node/Action/ResourceContextMenu.vue
@@ -18,7 +18,7 @@
<button class="menu-item" @click="action('copyMd')"><Icon name="link" />{{ t('common.actions.copy') }} {{ t('common.labels.content') }}</button>
</div>
- <div v-if="nodeStore.hasPermissions(node, 4)" class="menu-group">
+ <div v-if="nodesPermissionsStore.hasPermissions(node, 4)" class="menu-group">
<button class="menu-item" @click="action('manageAccess')"><Icon name="manage_access" />{{ t('nodes.actions.managePermissions') }}</button>
</div>
@@ -40,7 +40,7 @@ import type { Node } from '~/stores';
const props = defineProps<{ node: Node }>();
const emit = defineEmits(['close']);
-const nodeStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const userStore = useUserStore();
const preferences = usePreferencesStore();
diff --git a/frontend/app/components/Node/Card/Recent.vue b/frontend/app/components/Node/Card/Recent.vue
index 099705d9..17254d4d 100644
--- a/frontend/app/components/Node/Card/Recent.vue
+++ b/frontend/app/components/Node/Card/Recent.vue
@@ -1,30 +1,25 @@
<template>
<div class="card">
<div class="header">
- <!-- Icone enveloppée pour un contrôle précis des dimensions -->
<div class="icon-wrapper">
<Icon :name="icon" display="xl" :class="['node-icon', getAppAccent(node.color || (category?.color as number), true)]" />
</div>
<span class="time">{{ relativeTime(node.updated_timestamp) }}</span>
</div>
- <!-- Le corps de la carte est enveloppé pour isoler le push du margin-top: auto du footer -->
<div class="card-body">
<h3 class="title" :title="node.name">{{ node.name }}</h3>
<p v-if="node.description" class="desc">{{ node.description }}</p>
</div>
- <!-- Footer de métadonnées propre et scannable -->
<div v-if="category || node.tags" class="meta">
<span v-if="category" class="category" :title="category.name">
{{ category.name }}
</span>
- <!-- Petit séparateur visuel si on a ET une catégorie ET des tags -->
<span v-if="category && node.tags" class="meta-separator">·</span>
<div v-if="node.tags" class="tags">
- <!-- Remplacement du tag custom par un traitement de badge standardisé -->
<span v-for="tag in computedTags" :key="tag" class="tag-badge">
{{ tag }}
</span>
@@ -47,7 +42,6 @@ const { getAppAccent } = useAppColors();
const category = nodesStore.getById(props.node.parent_id || '');
const icon = resolveIcon(props.node);
-// Nettoyage et découpage des tags sécurisé
const computedTags = computed(() => {
if (!props.node.tags) return [];
return props.node.tags
@@ -63,14 +57,13 @@ const computedTags = computed(() => {
display: flex;
flex-direction: column;
height: 100%;
- padding: 1.25rem; /* Augmenté légèrement pour un rendu plus aéré / premium */
+ padding: 1.25rem;
border: 1px solid var(--border);
border-radius: var(--radius-lg);
background: var(--surface-base);
color: var(--text-body);
text-decoration: none;
- // Utilisation des variables de transition de ton projet
transition:
border-color $transition-fast ease,
background-color $transition-fast ease,
@@ -79,7 +72,7 @@ const computedTags = computed(() => {
&:hover {
border-color: var(--primary);
- background: var(--surface-raised); /* Donne un effet de profondeur au survol */
+ background: var(--surface-raised);
box-shadow: var(--shadow-md);
transform: translateY(-2px);
}
@@ -144,9 +137,9 @@ const computedTags = computed(() => {
display: flex;
align-items: center;
gap: 0.5rem;
- margin-top: auto; /* Pousse le footer vers le bas de la carte, peu importe la taille du texte */
+ margin-top: auto;
padding-top: 0.5rem;
- min-width: 0; /* Important pour que le flex-truncate fonctionne dedans */
+ min-width: 0;
}
.category {
@@ -178,12 +171,10 @@ const computedTags = computed(() => {
font-size: 0.72rem;
font-weight: 600;
border-radius: var(--radius-xs);
- // Un fond neutre et discret qui s'adapte au mode sombre
background: var(--surface-raised);
border: 1px solid var(--border);
color: var(--text-secondary);
- // Au survol de la carte globale, on peut accentuer subtilement les badges
.card:hover & {
background: var(--surface-base);
}
diff --git a/frontend/app/components/Node/Card/Workspace.vue b/frontend/app/components/Node/Card/Workspace.vue
index 897e06e8..689e0b8c 100644
--- a/frontend/app/components/Node/Card/Workspace.vue
+++ b/frontend/app/components/Node/Card/Workspace.vue
@@ -1,6 +1,5 @@
<template>
- <div class="workspace-tile" :class="accentColorClass">
- <!-- La lueur utilise désormais une variable CSS `--accent-color` injectée proprement par getAppAccent -->
+ <div class="workspace-tile" :class="getAppAccent(workspace.color, true)">
<div class="glow-ambiance" />
<div class="tile-content">
@@ -44,13 +43,6 @@ const props = defineProps<{ workspace: Node }>();
const nodesStore = useNodesStore();
const { getAppAccent } = useAppColors();
-// Nettoyage de la logique de couleur pour utiliser les mêmes standards de l'app
-const accentColorClass = computed(() => {
- const colors = ['blue', 'red', 'green', 'yellow', 'purple', 'pink', 'teal', 'primary'];
- const colorIndex = props.workspace.color as number;
- return colors[colorIndex] || 'primary';
-});
-
const categories = computed(() => {
const childrenIds = nodesStore.getAll.getChildrenIds(props.workspace.id);
return childrenIds.map(id => nodesStore.getById(id)).filter((n): n is Node => !!n && (n.role === 1 || n.role === 2));
diff --git a/frontend/app/components/Node/ContainerView.vue b/frontend/app/components/Node/ContainerView.vue
index 86787d2d..7d458be5 100644
--- a/frontend/app/components/Node/ContainerView.vue
+++ b/frontend/app/components/Node/ContainerView.vue
@@ -28,14 +28,26 @@
@click="openRemoveShareModal"
/>
<AppBtnIcon
- v-if="parent && nodesStore.hasPermissions(parent, 4)"
+ v-if="parent && nodesPermissionsStore.hasPermissions(parent, 4)"
nav
icon="manage_access"
:tooltip="t('nodes.actions.managePermissions')"
@click="openPermissionsModal"
/>
- <AppBtnIcon v-if="parent && nodesStore.hasPermissions(parent, 2)" nav icon="settings" :tooltip="t('nodes.actions.editMeta')" @click="openEditModal" />
- <AppBtnIcon v-if="parent && nodesStore.hasPermissions(parent, 4)" nav icon="delete" :tooltip="t('common.actions.delete')" @click="openDeleteModal" />
+ <AppBtnIcon
+ v-if="parent && nodesPermissionsStore.hasPermissions(parent, 2)"
+ nav
+ icon="settings"
+ :tooltip="t('nodes.actions.editMeta')"
+ @click="openEditModal"
+ />
+ <AppBtnIcon
+ v-if="parent && nodesPermissionsStore.hasPermissions(parent, 4)"
+ nav
+ icon="delete"
+ :tooltip="t('common.actions.delete')"
+ @click="openDeleteModal"
+ />
</Teleport>
<Teleport to="#navbar-infos">
<header>
@@ -87,6 +99,7 @@ import type { Node } from '~/stores';
const props = defineProps<{ parent?: Node; nodes: Node[]; parentId?: string }>();
const nodesStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const userStore = useUserStore();
const { isMobile } = useDevice();
diff --git a/frontend/app/components/Node/Document/Footer.vue b/frontend/app/components/Node/Document/Footer.vue
index 57fcf664..e12ad6dc 100644
--- a/frontend/app/components/Node/Document/Footer.vue
+++ b/frontend/app/components/Node/Document/Footer.vue
@@ -2,7 +2,7 @@
<footer v-if="document">
<div v-if="showAttachments" class="attachments">
<div v-for="attachment in attachments" :key="attachment.id" class="attachment">
- <NodeResourceInline :node="attachment.data" />
+ <NodeResourceInline :node="attachment" />
</div>
</div>
<div class="footer-top-row">
@@ -34,15 +34,17 @@ import type { Node } from '~/stores';
const props = defineProps<{ document?: Node; next?: Node; previous?: Node }>();
const preferences = usePreferencesStore();
+const nodeStore = useNodesStore();
const { t } = useI18nT();
const { formatRelativeDate } = useDateFormatters();
-const nodesTree = useNodesTree();
const showAttachments = preferences.get('documentShowAttachments');
const attachments = computed(() => {
- const children = nodesTree.getChildren(props.document?.id);
- return children.filter(child => child.data.role === 4);
+ return nodeStore.nodes
+ .getChildrenIds(props.document?.id)
+ .map(id => nodeStore.getById(id))
+ .filter(n => n?.role === 4) as Node[];
});
</script>
diff --git a/frontend/app/components/Node/Document/Header.vue b/frontend/app/components/Node/Document/Header.vue
index 59809fe5..ea538d42 100644
--- a/frontend/app/components/Node/Document/Header.vue
+++ b/frontend/app/components/Node/Document/Header.vue
@@ -5,9 +5,10 @@
<NodeDocumentHeaderSkeleton v-if="!doc" />
<!-- Real content -->
<template v-else>
- <Teleport to="#navbar-actions">
+ <Teleport v-if="!public" to="#navbar-actions">
<NodeDocumentHeaderActionRow :doc="doc" :is-public="public" class="no-print actions" />
</Teleport>
+ <NodeDocumentHeaderActionRow v-else :doc="doc" :is-public="public" class="no-print actions" />
<div class="content">
<div class="infos">
@@ -17,7 +18,7 @@
</p>
<NuxtLink class="category" :to="`/dashboard/categories/${category?.id}`">{{ category?.name || 'Uncategorized' }}</NuxtLink>
<h1 :class="{ public: public }">{{ doc?.name }}</h1>
- <Teleport to="#navbar-title">
+ <Teleport v-if="!public" to="#navbar-title">
<Icon :name="doc.icon || 'files'" display="xl" :class="['parent-icon', getAppAccent(doc.color as number, true)]" />
{{ doc.name }}
</Teleport>
@@ -52,9 +53,22 @@ const user = ref<PublicUser | null>(null);
const category = computed(() => nodesTree.getClosestCategoryAncestor(props.doc?.id)?.data);
const printMode = preferences.get('printMode');
-watchEffect(() => {
- if (props.doc) userStore.fetchPublicUser(props.doc.user_id).then(u => (user.value = u));
-});
+watch(
+ () => props.doc?.user_id,
+ async newUserId => {
+ if (!newUserId || newUserId === 'undefined') {
+ user.value = null;
+ return;
+ }
+ try {
+ const u = await userStore.fetchPublicUser(newUserId);
+ user.value = u;
+ } catch {
+ user.value = null;
+ }
+ },
+ { immediate: true },
+);
</script>
<style lang="scss" scoped>
diff --git a/frontend/app/components/Node/Document/HeaderActionRow.vue b/frontend/app/components/Node/Document/HeaderActionRow.vue
index a521dbf0..8e03b41f 100644
--- a/frontend/app/components/Node/Document/HeaderActionRow.vue
+++ b/frontend/app/components/Node/Document/HeaderActionRow.vue
@@ -2,7 +2,7 @@
<div>
<AppBtnIcon v-if="doc.accessibility == 3 && !isPublic" nav icon="link" :tooltip="t('nodes.actions.publicLink')" :to="`/doc/${doc.id}`" :blank="true" />
<AppBtnIcon
- v-if="nodeStore.hasPermissions(doc, 2)"
+ v-if="nodesPermissionsStore.hasPermissions(doc, 2)"
nav
icon="edit"
:tooltip="t('common.actions.edit')"
@@ -11,15 +11,15 @@
<AppBtnIcon nav icon="markdown" :tooltip="t('nodes.actions.exportAsMarkdown')" @click="exportMarkdown" />
<AppBtnIcon nav icon="print" :tooltip="t('common.actions.print')" @click="print" />
<AppBtnIcon v-if="doc.shared" nav icon="group_off" :tooltip="t('nodes.actions.removeFromShared')" @click="openRemoveShareModal" />
- <AppBtnIcon v-if="nodeStore.hasPermissions(doc, 2)" nav icon="settings" :tooltip="t('nodes.actions.editMeta')" @click="openEditModal" />
+ <AppBtnIcon v-if="nodesPermissionsStore.hasPermissions(doc, 2)" nav icon="settings" :tooltip="t('nodes.actions.editMeta')" @click="openEditModal" />
<AppBtnIcon
- v-if="nodeStore.hasPermissions(doc, 4)"
+ v-if="nodesPermissionsStore.hasPermissions(doc, 4)"
nav
icon="manage_access"
:tooltip="t('nodes.actions.managePermissions')"
@click="openPermissionsModal"
/>
- <AppBtnIcon v-if="nodeStore.hasPermissions(doc, 3)" nav icon="delete" :tooltip="t('common.actions.delete')" @click="openDeleteModal" />
+ <AppBtnIcon v-if="nodesPermissionsStore.hasPermissions(doc, 3)" nav icon="delete" :tooltip="t('common.actions.delete')" @click="openDeleteModal" />
</div>
</template>
@@ -33,7 +33,7 @@ import type { Node } from '~/stores';
const props = defineProps<{ doc: Node; isPublic?: boolean }>();
-const nodeStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const { t } = useI18nT();
const modals = useModal();
diff --git a/frontend/app/components/Node/Modals/Delete.vue b/frontend/app/components/Node/Modals/Delete.vue
index cdd16d13..3955f081 100644
--- a/frontend/app/components/Node/Modals/Delete.vue
+++ b/frontend/app/components/Node/Modals/Delete.vue
@@ -56,7 +56,7 @@ const handleDelete = async () => {
if (props.nodes && props.nodes.length > 0) {
await store.bulkDelete(props.nodes);
} else if (props.node) {
- await store.delete(props.node.id);
+ await store.remove(props.node.id);
}
emit('close');
if (props.redirectTo) {
diff --git a/frontend/app/components/Node/Modals/Permissions.vue b/frontend/app/components/Node/Modals/Permissions.vue
index b4b279cd..b2a7e728 100644
--- a/frontend/app/components/Node/Modals/Permissions.vue
+++ b/frontend/app/components/Node/Modals/Permissions.vue
@@ -107,12 +107,13 @@ const { t } = useI18nT();
const usersStore = useUserStore();
const nodesStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const { avatarURL } = useApi();
const { shortDate } = useDateFormatters();
const notifications = useNotifications();
-const node = ref<Node>(props.node);
+const node = ref<Node | undefined>(props.node);
const query = ref('');
const users = ref<PublicUser[]>([]);
const selectedPermission = ref(1);
@@ -125,28 +126,21 @@ const isCreatingInvitation = ref(false);
const link = computed(() => `${window.location.origin}/doc/${node.value?.id}`);
const invitationLink = (code: string) => `${window.location.origin}/dashboard/join-workspace?code=${encodeURIComponent(code)}`;
-const refreshInvitations = async () => {
- if (!node.value?.id) return;
- invitations.value = await nodesStore.fetchInvitations(node.value.id);
-};
-
-watchEffect(() => {
- if (node.value.partial) nodesStore.fetch({ id: node.value.id }).then(fetched => (node.value = fetched));
- for (const perm of node.value.permissions) {
- usersStore.fetchPublicUser(perm.user_id);
+watchEffect(async () => {
+ try {
+ const cached = nodesStore.getById(props.node.id);
+ if (cached && cached.partial) {
+ await nodesStore.fetch({ id: props.node.id });
+ }
+ node.value = nodesStore.getById(props.node.id);
+ for (const perm of node.value?.permissions ?? []) {
+ usersStore.fetchPublicUser(perm.user_id);
+ }
+ } catch {
+ node.value = undefined;
}
});
-watch(
- () => node.value.id,
- () => {
- refreshInvitations().catch(() => {
- invitations.value = [];
- });
- },
- { immediate: true },
-);
-
watch(query, async newQuery => {
users.value = [];
searchError.value = null;
@@ -170,29 +164,56 @@ const searchUsers = debounce((query: unknown) => {
}, 750);
watch(
- () => node.value.accessibility + node.value.access,
- debounce(() => nodesStore.update(node.value), 500),
+ () => (node.value?.accessibility ?? 0) + (node.value?.access ?? 0),
+ debounce(() => nodesStore.update(node.value!), 500),
{ deep: true },
);
// Actions
+
const addPermission = async (user: PublicUser) => {
if (!user) return;
- await nodesStore.addPermission({
+ await nodesPermissionsStore.addPermission({
node_id: props.node.id,
user_id: user.id,
permission: selectedPermission.value,
});
+
users.value = [];
query.value = '';
selectedPermission.value = 1;
};
+const updatePermission = async (perm: Permission) => {
+ await nodesPermissionsStore.updatePermission(perm);
+};
+
+const removePermission = async (perm: Permission) => {
+ if (!node.value) return;
+ await nodesPermissionsStore.removePermission(perm);
+ node.value.permissions = node.value.permissions.filter(p => p.id !== perm.id);
+};
+
+const refreshInvitations = async () => {
+ if (!node.value?.id) return;
+ invitations.value = await nodesPermissionsStore.fetchInvitations(node.value.id);
+};
+
+watch(
+ () => node.value?.id,
+ () => {
+ refreshInvitations().catch(() => {
+ invitations.value = [];
+ });
+ },
+ { immediate: true },
+);
+
const createInvitation = async () => {
if (!node.value?.id) return;
isCreatingInvitation.value = true;
try {
- const invitation = await nodesStore.addInvitation(node.value.id, selectedInvitationPermission.value);
+ const invitation = await nodesPermissionsStore.addInvitation(node.value.id, selectedInvitationPermission.value);
invitations.value = [invitation, ...invitations.value];
selectedInvitationPermission.value = 1;
notifications.add({ type: 'success', title: 'Invitation created' });
@@ -203,7 +224,7 @@ const createInvitation = async () => {
const deleteInvitation = async (invitationId: string) => {
if (!node.value?.id) return;
- await nodesStore.removeInvitation(node.value.id, invitationId);
+ await nodesPermissionsStore.removeInvitation(node.value.id, invitationId);
invitations.value = invitations.value.filter(invitation => invitation.id !== invitationId);
notifications.add({ type: 'success', title: 'Invitation revoked' });
};
@@ -212,16 +233,6 @@ const copyInvitationLink = async (code: string) => {
await navigator.clipboard.writeText(invitationLink(code));
notifications.add({ type: 'success', title: 'Invitation link copied to clipboard' });
};
-
-const updatePermission = async (perm: Permission) => {
- await nodesStore.updatePermission(perm);
-};
-
-const removePermission = async (perm: Permission) => {
- if (!node.value) return;
- await nodesStore.removePermission(perm);
- node.value.permissions = node.value.permissions.filter(p => p.id !== perm.id);
-};
</script>
<style scoped lang="scss">
diff --git a/frontend/app/components/Node/Modals/RemoveShared.vue b/frontend/app/components/Node/Modals/RemoveShared.vue
index 152f3990..fa10dede 100644
--- a/frontend/app/components/Node/Modals/RemoveShared.vue
+++ b/frontend/app/components/Node/Modals/RemoveShared.vue
@@ -16,6 +16,7 @@ const props = defineProps<{ nodeId: string }>();
const emit = defineEmits(['close']);
const nodesStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const userStore = useUserStore();
const { t } = useI18nT();
@@ -28,7 +29,7 @@ const removeDoc = () => {
const node = nodesStore.getById(props.nodeId);
const perm = node?.permissions.find(p => p.user_id === userStore.user?.id);
if (!perm) return notifications.add({ type: 'error', title: t('common.errors.generic') });
- nodesStore
+ nodesPermissionsStore
.removePermission(perm)
.then(() => {
notifications.add({ type: 'success', title: t('nodes.modals.removeShared.success') });
diff --git a/frontend/app/components/Node/Resource/CDN.vue b/frontend/app/components/Node/Resource/CDN.vue
index 859fcbf1..518cd8f1 100644
--- a/frontend/app/components/Node/Resource/CDN.vue
+++ b/frontend/app/components/Node/Resource/CDN.vue
@@ -11,7 +11,7 @@
<div class="storage-indicator">
<div class="storage-info">
<span class="storage-label">{{ t('cdn.storageUsed') }}</span>
- <span class="storage-values">{{ readableFileSize(totalUsedSpace) }} / {{ readableFileSize(MAX_STORAGE) }}</span>
+ <span class="storage-values">{{ readableFileSize(nodesStore.getTotalUsedStorage) }} / {{ readableFileSize(MAX_STORAGE) }}</span>
</div>
<div class="progress-bar">
<div
@@ -127,8 +127,7 @@ const nodes = computed(() => {
});
const filteredResources = ref(nodes.value);
-const totalUsedSpace = computed(() => nodesStore.getTotalUsedStorage);
-const storagePercentage = computed(() => Math.min((totalUsedSpace.value / MAX_STORAGE) * 100, 100));
+const storagePercentage = computed(() => Math.min((nodesStore.getTotalUsedStorage / MAX_STORAGE) * 100, 100));
const linksText = computed(() => fileLinks.value.join('\n'));
// DataTable setup
diff --git a/frontend/app/components/Node/Resource/Inline.vue b/frontend/app/components/Node/Resource/Inline.vue
index d7ace483..23f61397 100644
--- a/frontend/app/components/Node/Resource/Inline.vue
+++ b/frontend/app/components/Node/Resource/Inline.vue
@@ -7,8 +7,8 @@
<span class="file-size">{{ readableFileSize(node.size ?? 0) }}</span>
</div>
- <AppBtnIcon v-if="editable" nav icon="edit" :tooltip="t('common.actions.edit')" @click.prevent="openDrawioEditor" />
- <AppBtnIcon nav icon="delete" :tooltip="t('common.actions.delete')" @click.prevent="openDeleteModal" />
+ <span @click.prevent="openDrawioEditor"><AppBtnIcon v-if="editable" nav icon="edit" :tooltip="t('common.actions.edit')" /></span>
+ <span @click.prevent="openDeleteModal"> <AppBtnIcon nav icon="delete" :tooltip="t('common.actions.delete')" /></span>
</NuxtLink>
</template>
diff --git a/frontend/app/components/Node/TOC/TOC.vue b/frontend/app/components/Node/TOC/TOC.vue
index 1599aae9..ccb70f6b 100644
--- a/frontend/app/components/Node/TOC/TOC.vue
+++ b/frontend/app/components/Node/TOC/TOC.vue
@@ -14,20 +14,28 @@
</ul>
<h4 v-if="childs.length">{{ t('nodes.document.childs') }}</h4>
<NuxtLink v-for="child in childs" :key="child.id" :to="`/dashboard/docs/${child.id}`" class="child-link">
- <Icon name="file_shortcut" fill="var(--primary)" />{{ child.data.name as string }}
+ <Icon name="file_shortcut" fill="var(--primary)" />{{ child.name as string }}
</NuxtLink>
</aside>
</template>
<script lang="ts" setup>
import type { Node } from '~/stores';
-import type { TreeItem as NodeTreeItem } from '~/helpers/TreeBuilder';
+
+const props = defineProps<{ element?: HTMLElement; doc?: Node }>();
+
+const nodesStore = useNodesStore();
const { t } = useI18nT();
-const nodesTree = useNodesTree();
-const childs = computed(() => nodesTree.getChildren(props.doc?.id).filter(c => c.data.role === 3)) as Ref<NodeTreeItem<Node>[]>;
-const props = defineProps<{ element?: HTMLElement; doc?: Node }>();
+const childs = computed(
+ () =>
+ nodesStore.nodes
+ .getChildrenIds(props.doc?.id)
+ .map(id => nodesStore.getById(id))
+ .filter(n => n?.role === 3) as Node[],
+);
+
const list = ref<HTMLElement>();
interface GroupedHeaders {
diff --git a/frontend/app/components/Node/Team/Navbar.vue b/frontend/app/components/Node/Team/Navbar.vue
index 7c87672d..0ff2364e 100644
--- a/frontend/app/components/Node/Team/Navbar.vue
+++ b/frontend/app/components/Node/Team/Navbar.vue
@@ -45,16 +45,17 @@ const props = defineProps<{
}>();
const store = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const team = computed(() => store.getById(props.teamId));
const isAdmin = computed(() => {
if (!team.value) return false;
- return store.hasPermissions(team.value, 3);
+ return nodesPermissionsStore.hasPermissions(team.value, 3);
});
const isEditor = computed(() => {
if (!team.value) return false;
- return store.hasPermissions(team.value, 2);
+ return nodesPermissionsStore.hasPermissions(team.value, 2);
});
</script>
diff --git a/frontend/app/components/Sidebar/SidebarItem.vue b/frontend/app/components/Sidebar/SidebarItem.vue
index 54567a9f..5e76119d 100644
--- a/frontend/app/components/Sidebar/SidebarItem.vue
+++ b/frontend/app/components/Sidebar/SidebarItem.vue
@@ -21,13 +21,14 @@
<!-- Right icons / actions -->
<Icon v-if="item.data.shared && level === 0" name="shared" fill="var(--text-secondary)" />
- <NuxtLink v-if="item.data.role === 2 && canEdit" :to="`/dashboard/categories/${item.id}/edit`" class="nav close">
+ <NuxtLink v-if="item.data.role <= 2 && canEdit" :to="`/dashboard/categories/${item.id}/edit`" class="nav close">
<Icon name="settings" />
</NuxtLink>
<NuxtLink v-if="item.data.role === 2" :to="`/dashboard/docs/new?parent_id=${item.id}`" class="nav close">
<Icon name="plus" />
</NuxtLink>
<Icon v-if="item.data.order === -1" name="pin" fill="var(--text-secondary)" />
+ <Icon v-if="'synced' in item.data && !item.data.synced" name="no_synced" fill="var(--text-secondary)" />
<!-- Show collapse icon for parents -->
<slot />
@@ -42,6 +43,7 @@ import NodeContextMenu from '~/components/Node/Action/ContextMenu.vue';
import { type SidebarItem, getItemChildren } from './helpers';
const nodesStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const resourcesStore = useResourcesStore();
const preferencesStore = usePreferencesStore();
@@ -68,7 +70,7 @@ const icon = computed(() => {
return props.item.icon || '';
});
-const canEdit = computed(() => nodesStore.hasPermissions(props.item.data as Node, 2));
+const canEdit = computed(() => nodesPermissionsStore.hasPermissions(props.item.data as Node, 2));
const onClick = (m: MouseEvent) => {
// if element does not have the "close" class, don't close the sidebar
diff --git a/frontend/app/composables/useAppColors.ts b/frontend/app/composables/useAppColors.ts
index edc16feb..3044aa92 100644
--- a/frontend/app/composables/useAppColors.ts
+++ b/frontend/app/composables/useAppColors.ts
@@ -12,6 +12,7 @@ function setAppColor(color: string | number) {
if (typeof color === 'number') {
color = getAppAccent(color);
}
+ if (!import.meta.client) return;
setThemeColor(`--${color}`);
if (color === 'primary') color = 'accent';
document.documentElement.style.setProperty('--primary', `var(--${color})`);
diff --git a/frontend/app/composables/useCollapseStore.ts b/frontend/app/composables/useCollapseStore.ts
index d45dd019..02b97a00 100644
--- a/frontend/app/composables/useCollapseStore.ts
+++ b/frontend/app/composables/useCollapseStore.ts
@@ -11,8 +11,6 @@ const untilReady = new Promise<void>(resolve => {
resolveReady = resolve;
});
-// Instance réactive partagée unique pour Nuxt
-// (on utilise une fonction d'initialisation tardive pour éviter les soucis de SSR)
let states: Ref<Record<string, boolean>> | null = null;
function getStatesRef() {
diff --git a/frontend/app/composables/useNodesTree.ts b/frontend/app/composables/useNodesTree.ts
index 12c45eba..a9f52d02 100644
--- a/frontend/app/composables/useNodesTree.ts
+++ b/frontend/app/composables/useNodesTree.ts
@@ -2,41 +2,48 @@
* Nodes Tree Composable
* Single source of truth for the hierarchical node structure
*/
-import { TreeBuilder, flattenTree, type TreeItem } from '~/helpers/TreeBuilder';
+import { TreeBuilder, flattenTree, filterTree, type TreeItem } from '~/helpers/TreeBuilder';
import { resolveIcon, resolveNodeLink } from '~/helpers/node';
import type { Node } from '~/stores';
-let globalBuilder: ComputedRef<TreeBuilder<Node>> | null = null;
+let globalBuilder: TreeBuilder<Node> | null = null;
let globalTree: ComputedRef<TreeItem<Node>[]> | null = null;
+let globalTreeMap: ComputedRef<Map<string, TreeItem<Node>>> | null = null;
function initGlobalTree() {
const nodesStore = useNodesStore();
if (!globalBuilder) {
- console.log('[useNodesTree] 🏗️ Building global TreeBuilder');
- globalBuilder = computed(() => {
- const _ = nodesStore.getAll.size; // Trigger reactivity on nodesStore.getAll
- const rawCollection = toRaw(nodesStore.nodes);
- return new TreeBuilder<Node>(rawCollection, transformNode);
- });
+ globalBuilder = new TreeBuilder<Node>(toRaw(nodesStore.nodes), transformNode);
}
if (!globalTree) {
- console.log('[useNodesTree] 🌳 Building global tree');
globalTree = computed(() => {
- return globalBuilder!.value.buildTree({
+ console.debug('[useNodesTree] 🌳 Rebuilding global tree from store trigger');
+
+ globalBuilder!.clearCache();
+
+ return globalBuilder!.buildTree({
rootFilter: node => {
- if (node?.role === 0) return false;
- if (node?.role === 1 && !nodesStore.getById(node.parent_id ?? '')) return true;
+ if (node?.role <= 1) return true; // Include teams and categories as root nodes
if (!nodesStore.getById(node.parent_id ?? '')) return true;
return false;
},
});
});
+
+ globalTreeMap = computed(() => {
+ console.debug('[useNodesTree] 🗺️ Building global tree map from computed tree');
+ const map = new Map<string, TreeItem<Node>>();
+ const flat = flattenTree(globalTree!.value);
+ for (const item of flat) {
+ map.set(item.id, item);
+ }
+ return map;
+ });
}
}
-/** Transform Node to TreeItem */
function transformNode(node: Node): Omit<TreeItem<Node>, 'children'> {
return {
id: node.id,
@@ -47,71 +54,74 @@ function transformNode(node: Node): Omit<TreeItem<Node>, 'children'> {
data: node,
};
}
+
export function useNodesTree() {
- const nodesStore = useNodesStore();
const collapseStore = useCollapseStore();
initGlobalTree();
- const builder = globalBuilder!;
const tree = globalTree!;
+ const treeMap = globalTreeMap!;
const getTreeUpToRole = (maxRole: number) =>
computed(() => {
- return builder.value.buildTree({
- nodeFilter: node => node.role <= maxRole,
- rootFilter: node => {
- if (node.role === 0) return true;
- if (node.role === 1 && !nodesStore.getById(node.parent_id ?? '')) return true;
- if (!nodesStore.getById(node.parent_id ?? '')) return true;
- return false;
- },
- });
+ return filterTree(tree.value, item => (item.data?.role ?? 0) <= maxRole);
});
- // Workspace-specific tree retrieval
+ /**
+ * Get the tree structure for a specific workspace, optionally including the full subtree
+ */
const getWorkspaceTree = (workspaceId?: string, fullTree: boolean = false): TreeItem<Node>[] => {
if (!workspaceId) return tree.value;
+
if (workspaceId === 'shared') {
return tree.value.filter(item => item.data?.shared);
}
- const subtree = builder.value.buildSubtree(workspaceId);
- if (fullTree) return subtree ? [subtree] : [];
- return (subtree?.children as TreeItem<Node>[]) ?? [];
+ const cachedItem = treeMap.value.get(workspaceId);
+ if (!cachedItem) return [];
+
+ if (fullTree) return [cachedItem];
+ return cachedItem.children ?? [];
};
- // Subtree retrieval as flat array
+ /**
+ * Get the subtree of a node as a flat array, optionally starting from a specific node ID
+ * @param id Optional node ID to start the subtree from; if not provided, returns the entire tree as a flat array
+ * @returns TreeItem<Node>[]
+ */
const getSubtreeAsArray = (id?: string): TreeItem<Node>[] => {
if (!id) return flattenTree(tree.value);
- const subtree = builder.value.buildSubtree(id);
- return subtree?.children ? flattenTree(subtree.children as TreeItem<Node>[]) : [];
+ const cachedItem = treeMap.value.get(id);
+ return cachedItem?.children ? flattenTree(cachedItem.children) : [];
};
- // Get ancestors of a node as TreeItems[]
+ /** Get the ancestors of a node, starting from the specified node ID and moving up to the root
+ * @param fromNodeId Optional node ID to start the ancestor search from; if not provided, returns an empty array
+ * @returns TreeItem<Node>[]
+ */
const getAncestors = (fromNodeId?: string): TreeItem<Node>[] => {
- const node = builder.value.getTransformedItem(fromNodeId ?? '');
- if (!node) return [];
-
- const result = [node];
- let current = node;
- while (current.parentId) {
- const parentNode = nodesStore.nodes.get(current.parentId);
- if (!parentNode) break;
- const transformed = builder.value.getTransformedItem(parentNode.id)!;
- result.push(transformed);
- current = transformed;
+ if (!fromNodeId) return [];
+ const result: TreeItem<Node>[] = [];
+ let current = treeMap.value.get(fromNodeId);
+
+ while (current) {
+ result.push(current);
+ current = current.parentId ? treeMap.value.get(current.parentId) : undefined;
}
return result;
};
- // Get the first ancestor that is a category (role 1 or 2)
+ /**
+ * Get the closest ancestor of a node that is a category (role 1 or 2)
+ * @param nodeId Optional node ID to start the search from; if not provided, returns null
+ * @returns TreeItem<Node> | null
+ */
const getClosestCategoryAncestor = (nodeId?: string | null): TreeItem<Node> | null => {
if (!nodeId) return null;
-
- let current = builder.value.getTransformedItem(nodeId);
+ let current = treeMap.value.get(nodeId);
while (current?.parentId) {
- const parent = builder.value.getTransformedItem(current.parentId);
+ const parent = treeMap.value.get(current.parentId);
if (parent && (parent.data?.role === 1 || parent.data?.role === 2)) {
return parent;
}
@@ -120,30 +130,25 @@ export function useNodesTree() {
return null;
};
- const nextDocument = (id?: string) => (id ? builder.value.getSibling(id, 'next', n => n?.role === 3)?.data : undefined);
- const prevDocument = (id?: string) => (id ? builder.value.getSibling(id, 'prev', n => n?.role === 3)?.data : undefined);
-
- // Get children of a node (descendants) as TreeItems[]
- const getChildren = (parentId?: string | null): TreeItem<Node>[] => {
- return builder.value.getChildren(parentId ?? null);
- };
+ /**
+ * Getters for the next and previous documents in the tree, based on the current node ID
+ */
+ const nextDocument = (id?: string) => (id ? globalBuilder!.getSibling(id, 1, n => n?.role === 3)?.data : undefined);
+ const prevDocument = (id?: string) => (id ? globalBuilder!.getSibling(id, -1, n => n?.role === 3)?.data : undefined);
return {
- // Tree data
tree,
getTreeUpToRole,
getWorkspaceTree,
getSubtreeAsArray,
getAncestors,
getClosestCategoryAncestor,
- getChildren,
- builder,
+ builder: globalBuilder!,
- // Navigation
+ // Navigation & Collapse state
nextDocument,
prevDocument,
- // Collapse state
isExpanded: collapseStore.isExpanded,
setExpanded: collapseStore.setExpanded,
toggleExpand: collapseStore.toggle,
diff --git a/frontend/app/composables/useSidebar.ts b/frontend/app/composables/useSidebar.ts
index d40ef615..a321f2d4 100644
--- a/frontend/app/composables/useSidebar.ts
+++ b/frontend/app/composables/useSidebar.ts
@@ -25,7 +25,7 @@ export function useSidebar() {
return items.filter(item => item.data.role !== 4);
}
- return items;
+ return items.filter(item => item.data.role !== 0); // Exclude teams (role 0) from the sidebar
});
const toggle = () => (isOpen.value = !isOpen.value);
diff --git a/frontend/app/helpers/IndexedCollection.ts b/frontend/app/helpers/IndexedCollection.ts
index c8344a88..ff874bcf 100644
--- a/frontend/app/helpers/IndexedCollection.ts
+++ b/frontend/app/helpers/IndexedCollection.ts
@@ -10,24 +10,49 @@ export class IndexedCollection {
private sortedArray: Node[] = [];
// Flag to indicate bulk loading mode (to avoid unnecessary sorting during batch operations)
- private isBulkLoading = false;
+ private isBulkLoading = 0;
+
+ // Internal for reactivity, not exposed to the outside
+ private _dependents = shallowRef(null);
+
+ private notify() {
+ if (!this.isBulkLoading) {
+ triggerRef(this._dependents);
+ }
+ }
+
+ private track() {
+ // eslint-disable-next-line @typescript-eslint/no-unused-expressions
+ this._dependents.value;
+ }
get size(): number {
+ this.track();
return this.store.size;
}
get(id: string): Node | undefined {
+ this.track();
return this.store.get(id);
}
has(id: string): boolean {
+ this.track();
return this.store.has(id);
}
+ /**
+ * Iterate over all nodes in the collection
+ */
+ forEach(callback: (node: Node, id: string) => void): void {
+ this.store.forEach(callback);
+ }
+
/**
* Access O(1) to children of a parent
*/
getChildrenIds(parentId: string | null | undefined): string[] {
+ this.track();
return this.byParent.get(parentId ?? '') ?? [];
}
@@ -35,6 +60,7 @@ export class IndexedCollection {
* Access O(1) to nodes by role
*/
getIdsByRole(role: number): string[] {
+ this.track();
return this.byRole.get(role) ?? [];
}
@@ -42,6 +68,7 @@ export class IndexedCollection {
* Access O(1) to nodes up to a certain role (inclusive)
*/
getIdsUpToRole(maxRole: number): string[] {
+ this.track();
const ids: string[] = [];
for (let role = 0; role <= maxRole; role++) {
ids.push(...this.getIdsByRole(role));
@@ -53,18 +80,26 @@ export class IndexedCollection {
* Return pre-sorted array of nodes for iteration
*/
toSortedArray(): readonly Node[] {
+ this.track();
return this.sortedArray;
}
- set(id: string, node: Node): void {
+ /**
+ * Set a node in the collection. Must be called even if the node has been updated by reference, to ensure the indexes are updated and trigger reactivity.
+ * @param id The ID of the node
+ * @param node The node object
+ * @param forceNotify If true, will trigger reactivity even if the node structure hasn't changed
+ */
+ set(id: string, node: Node, forceNotify = false): void {
const oldNode = this.store.get(id);
// If the node structure hasn't changed, we can skip the re-indexing
- if (oldNode && oldNode.parent_id === node.parent_id && oldNode.role === node.role && oldNode.name === node.name && oldNode.order === node.order) {
+ if (!hasNodeSignatureChanged(oldNode, node)) {
this.store.set(id, node);
// Update the sorted array in place if the node's order or name has changed
const idx = this.sortedArray.findIndex(n => n.id === id);
if (idx !== -1) this.sortedArray[idx] = node;
+ if (forceNotify) this.notify();
return;
}
@@ -87,6 +122,7 @@ export class IndexedCollection {
if (!this.isBulkLoading) {
this.rebuildSortedArray();
}
+ if (forceNotify) this.notify();
}
delete(id: string): boolean {
@@ -97,27 +133,47 @@ export class IndexedCollection {
this.store.delete(id);
if (!this.isBulkLoading) this.rebuildSortedArray();
+ this.notify();
return true;
}
+ // Used to rebuild the indexes when the hierarchy changes
+ rebuildIndexes(): void {
+ this.byParent.clear();
+ this.byRole.clear();
+
+ for (const [id, node] of this.store.entries()) {
+ const pId = node.parent_id ?? '';
+ if (!this.byParent.has(pId)) this.byParent.set(pId, []);
+ this.byParent.get(pId)!.push(id);
+
+ if (!this.byRole.has(node.role)) this.byRole.set(node.role, []);
+ this.byRole.get(node.role)!.push(id);
+ }
+
+ if (!this.isBulkLoading) {
+ this.rebuildSortedArray();
+ }
+ this.notify();
+ }
+
+ // Clear the entire collection and its indexes
clear(): void {
this.store.clear();
this.byParent.clear();
this.byRole.clear();
this.sortedArray = [];
- }
-
- forEach(callback: (node: Node, id: string) => void): void {
- this.store.forEach(callback);
+ this.notify();
}
// Bulk operations to optimize performance when adding/removing multiple nodes
startBulk() {
- this.isBulkLoading = true;
+ this.isBulkLoading++;
}
endBulk() {
- this.isBulkLoading = false;
+ this.isBulkLoading--;
this.rebuildSortedArray();
+ this.notify();
}
// Internal helper to remove a node from the indexes
@@ -140,6 +196,34 @@ export class IndexedCollection {
Builds the sorted array of nodes based on their order and name.
*/
private rebuildSortedArray() {
- this.sortedArray = Array.from(this.store.values()).sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || a.name.localeCompare(b.name));
+ this.sortedArray = Array.from(this.store.values()).sort((a, b) => {
+ // 1. Sort by role
+ if (a.role !== b.role) {
+ return b.role - a.role;
+ }
+
+ // 2. Sort by order (if roles are identical)
+ const orderA = a.order ?? 0;
+ const orderB = b.order ?? 0;
+ if (orderA !== orderB) {
+ return orderA - orderB;
+ }
+
+ // 3. Sort by name (if roles and orders are identical)
+ return a.name.localeCompare(b.name);
+ });
}
}
+
+function hasNodeSignatureChanged(oldNode: Node | undefined, newNode: Node): boolean {
+ if (!oldNode) return true;
+ return (
+ oldNode.parent_id !== newNode.parent_id ||
+ oldNode.role !== newNode.role ||
+ oldNode.name !== newNode.name ||
+ oldNode.order !== newNode.order ||
+ oldNode.icon !== newNode.icon ||
+ oldNode.color !== newNode.color ||
+ oldNode.accessibility !== newNode.accessibility
+ );
+}
diff --git a/frontend/app/helpers/TreeBuilder.ts b/frontend/app/helpers/TreeBuilder.ts
index 0de49230..0a3c0d2d 100644
--- a/frontend/app/helpers/TreeBuilder.ts
+++ b/frontend/app/helpers/TreeBuilder.ts
@@ -41,19 +41,6 @@ export class TreeBuilder<T extends { id: string; parent_id?: string | null; role
return item;
}
- /**
- * Build the direct children of a given parentId
- */
- getChildren(parentId: string | null): TreeItem<T>[] {
- const childrenIds = this.collection.getChildrenIds(parentId);
- const result: TreeItem<T>[] = [];
- for (const childId of childrenIds) {
- const item = this.getTransformedItem(childId);
- if (item) result.push(item);
- }
- return result;
- }
-
/**
* Build the entire descending tree recursively, starting from the roots
* @param options Optional filters for nodes and roots
@@ -75,14 +62,20 @@ export class TreeBuilder<T extends { id: string; parent_id?: string | null; role
const childrenIds = this.collection.getChildrenIds(id);
if (childrenIds.length > 0) {
- item.children = childrenIds.map(childId => buildSubtree(childId)).filter((c): c is TreeItem<T> => !!c); // On élimine les enfants filtrés
+ const mappedChildren = childrenIds.map(childId => buildSubtree(childId)).filter((c): c is TreeItem<T> => !!c);
+
+ if (mappedChildren.length > 1) {
+ mappedChildren.sort(sortNodes);
+ }
+
+ item.children = mappedChildren.length > 0 ? mappedChildren : undefined;
} else {
item.children = undefined;
}
return item;
};
- return rootIds
+ const rootItems = rootIds
.filter(id => {
const node = this.collection.get(id) as T;
if (!node) return false;
@@ -91,56 +84,40 @@ export class TreeBuilder<T extends { id: string; parent_id?: string | null; role
})
.map(id => buildSubtree(id))
.filter((item): item is TreeItem<T> => !!item);
- }
- /**
- * Build a subtree starting from a specific parentId, recursively
- */
- buildSubtree(parentId: string): TreeItem<T> | undefined {
- const buildSubtreeRecursive = (id: string): TreeItem<T> | undefined => {
- const cachedItem = this.getTransformedItem(id);
- if (!cachedItem) return undefined;
-
- const childrenIds = this.collection.getChildrenIds(id);
- if (childrenIds.length === 0) {
- return { ...cachedItem, children: undefined };
- }
-
- const validChildren: TreeItem<T>[] = [];
- for (let i = 0; i < childrenIds.length; i++) {
- const child = buildSubtreeRecursive(childrenIds[i]!);
- if (child) validChildren.push(child);
- }
-
- if (validChildren.length > 1) {
- validChildren.sort((a, b) => (a.data.order ?? 0) - (b.data.order ?? 0));
- }
-
- return {
- ...cachedItem,
- children: validChildren.length > 0 ? validChildren : undefined,
- };
- };
+ if (rootItems.length > 1) {
+ rootItems.sort(sortNodes);
+ }
- return buildSubtreeRecursive(parentId);
+ return rootItems;
}
/**
* Get the next or previous sibling of a node, optionally filtered by a predicate
*/
- getSibling(id: string, direction: 'next' | 'prev', filter?: (item?: T) => boolean): TreeItem<T> | undefined {
+ getSibling(id: string, direction: number, filter?: (item?: T) => boolean): TreeItem<T> | undefined {
const currentItem = this.getTransformedItem(id);
if (!currentItem) return undefined;
- // On récupère instantanément les frères via le parent commun
- let siblings = this.getChildren(currentItem.parentId ?? null);
+ let siblings = this.collection
+ .getChildrenIds(currentItem.parentId ?? null)
+ .map(id => this.getTransformedItem(id))
+ .filter((s): s is TreeItem<T> => !!s);
+
if (filter) siblings = siblings.filter(s => filter(s.data));
const index = siblings.findIndex(s => s.id === id);
if (index === -1) return undefined;
- const targetIndex = direction === 'next' ? index + 1 : index - 1;
- return siblings[targetIndex];
+ return siblings[index + direction] ?? undefined;
+ }
+
+ /**
+ * Clear the transformation cache, useful when the underlying collection changes
+ * to ensure that the tree is rebuilt with the latest data.
+ */
+ public clearCache() {
+ this.transformCache.clear();
}
}
/** Filter tree recursively, keeping branches with matches */
@@ -177,3 +154,15 @@ export function flattenTree<T>(items: TreeItem<T>[]): TreeItem<T>[] {
}
return result;
}
+
+function sortNodes<T extends { id: string; parent_id?: string | null; role?: number; order?: number }>(a: TreeItem<T>, b: TreeItem<T>) {
+ if (a.data.role !== b.data.role) {
+ return (b.data.role ?? 0) - (a.data.role ?? 0);
+ }
+ const orderA = a.data.order ?? 0;
+ const orderB = b.data.order ?? 0;
+ if (orderA !== orderB) {
+ return orderA - orderB;
+ }
+ return a.label.localeCompare(b.label);
+}
diff --git a/frontend/app/helpers/node.ts b/frontend/app/helpers/node.ts
index 615eda14..fd22e83e 100644
--- a/frontend/app/helpers/node.ts
+++ b/frontend/app/helpers/node.ts
@@ -98,15 +98,12 @@ export function parseTags(tags: string): string[] {
}
export function mergeNode(node: Node, full_node: Node): Node {
- const result: Node = { ...full_node };
+ const result: Node = { ...node };
- for (const key in node) {
- const localValue = node[key as keyof Node];
- if (localValue !== undefined && localValue !== null && localValue !== '') {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (result as any)[key] = localValue; // keep local value if it's defined
- }
- }
+ if (!node.content) result.content = full_node.content;
+ if (!node.content_compiled) result.content_compiled = full_node.content_compiled;
+
+ if (!result.parent_id) delete result.parent_id;
result.partial = false;
return result;
diff --git a/frontend/app/pages/(public)/_components/OpenSourceStats.vue b/frontend/app/pages/(public)/_components/OpenSourceStats.vue
index 8dc6da0b..c847b942 100644
--- a/frontend/app/pages/(public)/_components/OpenSourceStats.vue
+++ b/frontend/app/pages/(public)/_components/OpenSourceStats.vue
@@ -1,11 +1,6 @@
<template>
<section class="oss-stats">
<div class="stats-visual">
- <div class="visual-bg">
- <div class="code-lines">
- <span v-for="i in 8" :key="i" class="code-line" :style="{ '--delay': `${i * 0.1}s`, '--width': `${40 + Math.random() * 50}%` }"></span>
- </div>
- </div>
<div class="github-card">
<div class="card-header">
<svg width="32" height="32" viewBox="0 0 24 24" fill="currentColor">
@@ -145,31 +140,6 @@ onMounted(() => {
position: relative;
}
-.visual-bg {
- position: absolute;
- border-radius: var(--radius-xxl);
- background: linear-gradient(135deg, var(--surface-raised), var(--surface-base));
- inset: 0;
- overflow: hidden;
-}
-
-.code-lines {
- position: absolute;
- display: flex;
- padding: 2rem;
- flex-direction: column;
- gap: 12px;
- inset: 0;
-}
-
-.code-line {
- width: var(--width);
- height: 12px;
- border-radius: var(--radius-sm);
- background: var(--border);
- opacity: 0.4;
-}
-
.github-card {
position: relative;
margin: 2rem;
diff --git a/frontend/app/pages/(public)/doc/[id]/edit.vue b/frontend/app/pages/(public)/doc/[id]/edit.vue
index 00c3a1fb..1aef135b 100644
--- a/frontend/app/pages/(public)/doc/[id]/edit.vue
+++ b/frontend/app/pages/(public)/doc/[id]/edit.vue
@@ -1,38 +1,37 @@
<template>
- <LazyMarkdownEditor v-if="document && !error" :doc="document" @save="data => save(data)" @auto-save="data => autoSave(data)" @exit="exit" />
+ <ClientOnly>
+ <LazyMarkdownEditor v-if="document && !error" :doc="document" public @save="data => save(data)" @auto-save="data => autoSave(data)" @exit="exit" />
+ </ClientOnly>
</template>
<script lang="ts" setup>
-import type { Node } from '~/stores';
+import type { Node, PublicNodeResponse } from '~/stores';
-definePageMeta({ breadcrumb: {i18n: 'common.actions.edit'} });
+definePageMeta({ breadcrumb: { i18n: 'common.actions.edit' } });
const store = useNodesStore();
const route = useRoute();
+const router = useRouter();
const notifications = useNotifications();
const nodeId = route.params.id as string;
-const document = ref<Node | undefined>(undefined);
-const error: Ref<string> = ref('');
-
-watchEffect(async () => {
- const storedNode = store.getById(nodeId);
- if (!storedNode) {
- try {
- const result = await store.fetchPublic(nodeId);
- document.value = result?.node;
- } catch {
- error.value = 'Document not found';
- }
- } else if (storedNode?.partial) {
- try {
- document.value = await store.fetch({ id: nodeId });
- } catch {
- error.value = 'Document not found';
- }
- } else document.value = storedNode;
+const { data: document, error } = await useAsyncData(`public-doc-e-${route.params.id}`, async (): Promise<Node | undefined> => {
+ const documentId = route.params.id;
+ if (!documentId || typeof documentId !== 'string') return undefined;
+
+ const request = await makeRequest(`nodes/public/${documentId}`, 'GET', {});
+ if (request.status === 'success') {
+ const response = request.result as PublicNodeResponse;
+
+ return {
+ ...response.node,
+ partial: false,
+ shared: false,
+ permissions: [],
+ };
+ }
+ return undefined;
});
-
function save(doc: Node) {
store
.update(doc)
@@ -44,5 +43,5 @@ function autoSave(doc: Node) {
store.update(doc);
}
-const exit = () => useRouter().push(`/doc/${nodeId}`);
+const exit = () => router.push(`/doc/${nodeId}`);
</script>
diff --git a/frontend/app/pages/(public)/doc/[id]/index.vue b/frontend/app/pages/(public)/doc/[id]/index.vue
index 6bb6b557..449948cc 100644
--- a/frontend/app/pages/(public)/doc/[id]/index.vue
+++ b/frontend/app/pages/(public)/doc/[id]/index.vue
@@ -1,32 +1,26 @@
-<!-- eslint-disable vue/no-v-html -->
<template>
<div style="width: 100%; padding: 1rem 0">
<div
v-if="!error && article"
class="reader"
:style="{
- marginRight: !isTablet && hideTOC && isOpened && hasContent ? '200px' : '0px',
+ marginRight: !isTablet && isOpened && hasContent ? '200px' : '0px',
transition: 'margin $transition-medium',
}"
>
<div class="doc-container">
- <!-- Header for all node types -->
- <NodeDocumentHeader :doc="article" :public="true" style="margin: 20px 0" />
+ <NodeDocumentHeader :doc="article" public style="margin: 20px 0" />
- <!-- Document content if available -->
<NodeDocumentContentCompiled v-if="hasContent" ref="elementComponent" :node="article" />
- <!-- Hierarchical children tree -->
<NodeTree v-if="children.length > 0" :nodes="children" :parent-id="article.id" />
</div>
- <!-- Table of contents only for documents with content -->
- <div v-if="!isTablet && !hideTOC && hasContent" class="toc">
+ <div v-if="!isTablet && hasContent" class="toc">
<NodeTOC :doc="article" :element="element" />
</div>
</div>
- <!-- Loading state -->
<div v-else-if="!error" class="reader">
<div class="doc-container">
<NodeDocumentSkeleton />
@@ -36,20 +30,16 @@
<Error v-else :error="error?.message" />
</div>
</template>
+
<script setup lang="ts">
import NodeDocumentContentCompiled from '~/components/Node/Document/ContentCompiled.vue';
-import type { Node } from '~/stores';
-
-const documentsStore = useNodesStore();
-const preferencesStore = usePreferencesStore();
+import type { Node, PublicNodeResponse } from '~/stores';
const route = useRoute();
-const runtimeConfig = useRuntimeConfig();
+const requestUrl = useRequestURL();
const { isOpened } = useSidebar();
const { isTablet } = useDevice();
-const hideTOC = preferencesStore.get('hideTOC');
-
const children = ref<Node[]>([]);
const elementComponent = ref<InstanceType<typeof NodeDocumentContentCompiled>>();
const element = computed(() => elementComponent.value?.rootElement as HTMLElement | undefined);
@@ -57,41 +47,47 @@ const element = computed(() => elementComponent.value?.rootElement as HTMLElemen
const { data: article, error } = await useAsyncData(`public-doc-${route.params.id}`, async (): Promise<Node | undefined> => {
const documentId = route.params.id;
if (!documentId || typeof documentId !== 'string') return undefined;
- const result = await documentsStore.fetchPublic(documentId);
- if (result) {
- children.value = result.children || [];
- return result.node;
+
+ const request = await makeRequest(`nodes/public/${documentId}`, 'GET', {});
+ if (request.status === 'success') {
+ const response = request.result as PublicNodeResponse;
+
+ children.value = (response.children || []).map(c => ({ ...c, partial: true, shared: false, permissions: [] }));
+
+ return {
+ ...response.node,
+ partial: false,
+ shared: false,
+ permissions: [],
+ };
}
return undefined;
});
/** Check if node has displayable content */
-const hasContent = computed(() => article.value?.content_compiled && article.value.content_compiled.trim().length > 0);
-const title = computed(() => article.value?.name || 'Unknown document');
-const description = computed(() => article.value?.description || 'Public document published on Alexandrie, a modern Markdown-based note-taking platform.');
-const baseUrl = runtimeConfig.public.baseUrl || 'https://alexandrie-hub.fr';
-const canonicalUrl = computed(() => `${baseUrl}/doc/${route.params.id}`);
-const ogImage = computed(() => (article.value?.thumbnail ? `${baseUrl}${article.value.thumbnail}` : `${baseUrl}/og/default-article.png`));
+const hasContent = computed(() => !!article.value?.content_compiled?.trim());
+const baseUrl = requestUrl.origin || __BASE_URL__;
+
+// Configuration SEO robuste pour le SSR
useSeoMeta({
- title,
- description,
+ title: () => article.value?.name || 'Unknown document',
+ description: () => article.value?.description || 'Public document published on Alexandrie, a modern Markdown-based note-taking platform.',
keywords: () => article.value?.tags,
- ogTitle: title,
- ogDescription: description,
+ ogTitle: () => article.value?.name || 'Unknown document',
+ ogDescription: () => article.value?.description || 'Public document published on Alexandrie, a modern Markdown-based note-taking platform.',
ogType: 'article',
- ogUrl: canonicalUrl,
- ogImage,
-
- articlePublishedTime: () => (article.value ? new Date(article.value.created_timestamp).toISOString() : undefined),
+ ogUrl: () => `${baseUrl}/doc/${route.params.id}`,
+ ogImage: () => (article.value?.thumbnail ? `${baseUrl}${article.value.thumbnail}` : `${baseUrl}/og/default-article.png`),
- articleModifiedTime: () => (article.value ? new Date(article.value.updated_timestamp).toISOString() : undefined),
+ articlePublishedTime: () => (article.value?.created_timestamp ? new Date(article.value.created_timestamp).toISOString() : undefined),
+ articleModifiedTime: () => (article.value?.updated_timestamp ? new Date(article.value.updated_timestamp).toISOString() : undefined),
twitterCard: 'summary_large_image',
- twitterTitle: title,
- twitterDescription: description,
- twitterImage: ogImage,
+ twitterTitle: () => article.value?.name || 'Unknown document',
+ twitterDescription: () => article.value?.description || 'Public document published on Alexandrie, a modern Markdown-based note-taking platform.',
+ twitterImage: () => (article.value?.thumbnail ? `${baseUrl}${article.value.thumbnail}` : `${baseUrl}/og/default-article.png`),
});
</script>
diff --git a/frontend/app/pages/(public)/login/index.vue b/frontend/app/pages/(public)/login/index.vue
index 1076a64b..4a0fbf0c 100644
--- a/frontend/app/pages/(public)/login/index.vue
+++ b/frontend/app/pages/(public)/login/index.vue
@@ -31,7 +31,7 @@
<p v-if="errors.password" class="invalid-feedback">{{ errors.password }}</p>
</div>
<NuxtLink to="/signup" class="signup-link">Need an account? Sign up</NuxtLink>
- <button class="btn" :disabled="loginDisabled" @click="login">Login</button>
+ <button class="btn" :disabled="loginDisabled">Login</button>
<p v-if="loginDisabled" class="disabled">Native login is currently disabled. Please use one of the available authentication providers below.</p>
<OIDCProviders />
diff --git a/frontend/app/pages/dashboard/categories/[id]/index.vue b/frontend/app/pages/dashboard/categories/[id]/index.vue
index 6b39a2d9..c94102b9 100644
--- a/frontend/app/pages/dashboard/categories/[id]/index.vue
+++ b/frontend/app/pages/dashboard/categories/[id]/index.vue
@@ -14,6 +14,7 @@ definePageMeta({
});
const nodesStore = useNodesStore();
+const nodesPermissionsStore = useNodesPermissionsStore();
const nodesTree = useNodesTree();
const modals = useModal();
@@ -34,7 +35,7 @@ const nodes = computed(() => {
});
const openDeleteModal = () => {
- if (!parent.value || !nodesStore.hasPermissions(parent.value, 4)) return;
+ if (!parent.value || !nodesPermissionsStore.hasPermissions(parent.value, 4)) return;
modals.add(new Modal(shallowRef(NodeDeleteModal), { size: 'small', props: { node: parent.value, redirect: '/dashboard' } }));
};
diff --git a/frontend/app/pages/dashboard/docs/[id].vue b/frontend/app/pages/dashboard/docs/[id].vue
index 9b3ece15..99c8a278 100644
--- a/frontend/app/pages/dashboard/docs/[id].vue
+++ b/frontend/app/pages/dashboard/docs/[id].vue
@@ -17,13 +17,13 @@
</div>
</template>
<script setup lang="ts">
-import type { RouteLocationNormalizedLoaded } from 'vue-router';
-import type { Node } from '~/stores';
-
import NodeContextMenu from '~/components/Node/Action/ContextMenu.vue';
import NodeDocumentContentCompiled from '~/components/Node/Document/ContentCompiled.vue';
import DeleteNodeModal from '~/components/Node/Modals/Delete.vue';
+import type { RouteLocationNormalizedLoaded } from 'vue-router';
+import type { Node } from '~/stores';
+
definePageMeta({
breadcrumb: (route: RouteLocationNormalizedLoaded) => {
return useBreadcrumbs().generateBreadcrumbsById(route.params.id as string);
@@ -49,24 +49,7 @@ const element = computed(() => elementComponent.value?.rootElement as HTMLElemen
const node = ref<Node | undefined>();
const error = ref<false | string>(false);
-watchEffect(async () => {
- const document_id = route.params.id as string;
- const docFromStore = documentsStore.getById(document_id);
- if (!docFromStore) {
- if (documentsStore.isFetching) return;
- return (error.value = 'Document not found');
- }
- node.value = undefined;
- if (docFromStore.partial) {
- try {
- error.value = false;
- node.value = await documentsStore.fetch({ id: document_id });
- } catch (err: unknown) {
- error.value = (err as Error).message || 'Failed to fetch document';
- }
- } else node.value = docFromStore;
- useHead({ title: node.value?.name || '' });
-});
+const documentId = computed(() => route.params.id as string);
const next = computed(() => nodesTree.nextDocument(node.value?.id));
const previous = computed(() => nodesTree.prevDocument(node.value?.id));
@@ -76,6 +59,45 @@ const width = computed(() => {
return '700px';
});
+async function loadDocument(id: string) {
+ error.value = false;
+
+ if (documentsStore.isFetching) {
+ node.value = undefined;
+ return;
+ }
+
+ const docFromStore = documentsStore.getById(id);
+
+ if (!docFromStore) {
+ node.value = undefined;
+ error.value = 'Document not found';
+ return;
+ }
+
+ if (docFromStore.partial) {
+ try {
+ node.value = await documentsStore.fetch({ id });
+ } catch (err: unknown) {
+ error.value = (err as Error).message || 'Failed to fetch document';
+ }
+ } else {
+ node.value = docFromStore;
+ }
+
+ if (node.value) useHead({ title: node.value.name });
+}
+
+watch(
+ [documentId, () => documentsStore.isFetching],
+ ([newId, _]) => {
+ if (newId) {
+ loadDocument(newId);
+ }
+ },
+ { immediate: true },
+);
+
// Actions
const openContextMenu = (event: MouseEvent) => {
if (!node.value) return;
diff --git a/frontend/app/pages/dashboard/docs/new.vue b/frontend/app/pages/dashboard/docs/new.vue
index cea06728..5671b720 100644
--- a/frontend/app/pages/dashboard/docs/new.vue
+++ b/frontend/app/pages/dashboard/docs/new.vue
@@ -1,7 +1,8 @@
<template>
- <LazyMarkdownEditor :doc="document" @save="data => save(data)" @exit="exit" />
+ <LazyMarkdownEditor :doc="document" @save="data => save(data)" @exit="exit" @auto-save="savePending" />
</template>
<script lang="ts" setup>
+import localForage from 'localforage';
import type { Node } from '~/stores';
definePageMeta({ breadcrumb: { i18n: 'common.actions.new' } });
@@ -14,24 +15,38 @@ const store = useNodesStore();
const notifications = useNotifications();
const route = useRoute();
+const router = useRouter();
const sidebar = useSidebar();
+const pendingNode = await localForage.getItem<Node>('pendingNode');
+
+let saved = false;
+
const routeQuery = computed<NewDocumentQuery>(() => route.query);
const defaultParent = computed(() => routeQuery.value.parent_id || sidebar.workspaceId.value || undefined);
const document = computed<Partial<Node>>(() => ({
accessibility: 1,
parent_id: ['root', 'shared'].includes(defaultParent.value || '') ? undefined : defaultParent.value,
role: 3,
+ ...pendingNode,
}));
function save(doc: Node) {
store
.post(doc)
- .then(d => {
+ .then(async d => {
notifications.add({ title: 'Document successfully posted', type: 'success' });
- useRouter().push(`/dashboard/docs/edit/${d.id}`);
+ await localForage.removeItem('pendingNode');
+ saved = true;
+ router.push(`/dashboard/docs/edit/${d.id}`);
})
.catch(e => notifications.add({ message: e, title: 'Error', type: 'error' }));
}
-const exit = () => useRouter().push('/dashboard');
+
+function savePending(node: Node) {
+ if (saved) return;
+ localForage.setItem('pendingNode', toRaw(node));
+}
+
+const exit = () => router.push('/dashboard');
</script>
diff --git a/frontend/app/pages/dashboard/import/advanced.vue b/frontend/app/pages/dashboard/import/advanced.vue
index 1d0f70b8..7a63a4f7 100644
--- a/frontend/app/pages/dashboard/import/advanced.vue
+++ b/frontend/app/pages/dashboard/import/advanced.vue
@@ -109,7 +109,7 @@ import type { DB_Node } from '~/stores';
definePageMeta({ breadcrumb: { i18n: 'import.meta.breadcrumb' } });
-const nodesStore = useNodesStore();
+const nodesImporterStore = useNodesImporterStore();
const nodesTree = useNodesTree();
const { t } = useI18nT();
@@ -194,7 +194,7 @@ const importAll = () => importNodes(nodes.value, resourcesToUpload.value);
async function importNodes(nodesToImport: DB_Node[], resourcesImport: ResourceImportTask[]) {
importJob.value.toCreate = nodesToImport;
importJob.value.toUpdate = [];
- await nodesStore.importAllNodesAndResources({ toCreate: nodesToImport, toUpdate: [], resources: resourcesImport }, importJob);
+ await nodesImporterStore.importAllNodesAndResources({ toCreate: nodesToImport, toUpdate: [], resources: resourcesImport }, importJob);
nodes.value = [];
resourcesToUpload.value = [];
}
diff --git a/frontend/app/pages/dashboard/import/backup.vue b/frontend/app/pages/dashboard/import/backup.vue
index 05f3cfea..35357133 100644
--- a/frontend/app/pages/dashboard/import/backup.vue
+++ b/frontend/app/pages/dashboard/import/backup.vue
@@ -52,7 +52,7 @@ import type { DB_Node } from '~/stores/db_structures';
definePageMeta({ breadcrumb: { i18n: 'import.meta.breadcrumb' } });
-const nodesStore = useNodesStore();
+const nodesImporterStore = useNodesImporterStore();
const { t } = useI18nT();
const notifications = useNotifications();
@@ -109,7 +109,7 @@ async function analyzeFile() {
if (result.documents?.length) {
backupDocuments.value = result.documents;
- const { toCreate: create, toUpdate: update } = nodesStore.prepareImport(result.documents);
+ const { toCreate: create, toUpdate: update } = nodesImporterStore.prepareImport(result.documents);
importJob.value.toCreate = create;
importJob.value.toUpdate = update;
} else {
@@ -152,10 +152,10 @@ async function importNodes(type: 'create' | 'update', ids: string[]) {
type === 'create' ? importJob.value.toCreate.filter(d => ids.includes(d.id)) : importJob.value.toUpdate.filter(d => ids.includes(d.id));
if (type === 'create') {
- await nodesStore.importAllNodesAndResources({ toCreate: nodes, toUpdate: [], resources: [] }, importJob);
+ await nodesImporterStore.importAllNodesAndResources({ toCreate: nodes, toUpdate: [], resources: [] }, importJob);
importJob.value.toCreate = importJob.value.toCreate.filter(d => !importJob.value.created.includes(d.id));
} else if (type == 'update') {
- await nodesStore.importAllNodesAndResources({ toCreate: [], toUpdate: nodes, resources: [] }, importJob);
+ await nodesImporterStore.importAllNodesAndResources({ toCreate: [], toUpdate: nodes, resources: [] }, importJob);
importJob.value.toUpdate = importJob.value.toUpdate.filter(d => !importJob.value.updated.includes(d.id));
}
@@ -190,7 +190,7 @@ async function importAll() {
const createDocs = importJob.value.toCreate;
const updateDocs = importOptions.skipExisting ? [] : importJob.value.toUpdate;
- await nodesStore.importAllNodesAndResources({ toCreate: createDocs, toUpdate: updateDocs, resources: [] }, importJob);
+ await nodesImporterStore.importAllNodesAndResources({ toCreate: createDocs, toUpdate: updateDocs, resources: [] }, importJob);
importJob.value.toCreate = importJob.value.toCreate.filter(d => !importJob.value.created.includes(d.id));
importJob.value.toUpdate = importJob.value.toUpdate.filter(d => !importJob.value.updated.includes(d.id));
diff --git a/frontend/app/pages/dashboard/import/files.vue b/frontend/app/pages/dashboard/import/files.vue
index f5bf0a29..42559ba6 100644
--- a/frontend/app/pages/dashboard/import/files.vue
+++ b/frontend/app/pages/dashboard/import/files.vue
@@ -43,7 +43,7 @@ import type { DB_Node } from '~/stores';
definePageMeta({ breadcrumb: { i18n: 'import.meta.breadcrumb' } });
-const nodesStore = useNodesStore();
+const nodesImporterStore = useNodesImporterStore();
const { t } = useI18nT();
@@ -94,7 +94,7 @@ const importAll = () => importNodes(nodes.value);
async function importNodes(importNodes: DB_Node[]) {
importJob.value.toCreate = importNodes;
- await nodesStore.importAllNodesAndResources({ toCreate: importNodes, toUpdate: [], resources: [] }, importJob);
+ await nodesImporterStore.importAllNodesAndResources({ toCreate: importNodes, toUpdate: [], resources: [] }, importJob);
nodes.value = nodes.value.filter(n => !importJob.value.created.includes(n.id));
}
</script>
diff --git a/frontend/app/pages/dashboard/teams/[id]/index.vue b/frontend/app/pages/dashboard/teams/[id]/index.vue
index 0bb38d77..5cb87397 100644
--- a/frontend/app/pages/dashboard/teams/[id]/index.vue
+++ b/frontend/app/pages/dashboard/teams/[id]/index.vue
@@ -52,7 +52,6 @@ definePageMeta({ breadcrumb: { i18n: 'teams.overview.title' } });
const nodesStore = useNodesStore();
-const nodesTree = useNodesTree();
const route = useRoute();
const modals = useModal();
const router = useRouter();
@@ -66,13 +65,23 @@ const team = ref<Node | undefined>();
watchEffect(() => {
team.value = nodesStore.getById(teamId);
if (team.value && team.value.partial) {
- nodesStore.fetch({ id: teamId }).then(fetched => (team.value = fetched));
+ nodesStore
+ .fetch({ id: teamId })
+ .then(fetched => (team.value = fetched))
+ .catch(() => {});
}
});
-const allItems = computed(() => (team.value ? nodesTree.getChildren(team.value.id).filter(item => item.id !== team.value?.id) : []));
+const allItems = computed(() =>
+ team.value
+ ? nodesStore.nodes
+ .getChildrenIds(team.value.id)
+ .map(id => nodesStore.getById(id)!)
+ .filter(item => item.id !== team.value?.id)
+ : [],
+);
const editLink = computed(() => (team.value ? `/dashboard/docs/edit/${team.value.id}?redirect=/dashboard/teams/${team.value.id}` : ''));
-const directChildren = computed(() => (team.value ? nodesTree.getChildren(team.value.id) : []));
+const directChildren = computed(() => (team.value ? nodesStore.nodes.getChildrenIds(team.value.id).map(id => nodesStore.getById(id)) : []));
const openCreateWorkspace = () => modals.add(new Modal(shallowRef(CreateCategoryModal), { props: { role: 1, parentId: teamId } }));
const openCreateCategory = () => modals.add(new Modal(shallowRef(CreateCategoryModal), { props: { role: 2, parentId: teamId } }));
diff --git a/frontend/app/pages/dashboard/teams/[id]/manage-members.vue b/frontend/app/pages/dashboard/teams/[id]/manage-members.vue
index ce48d9e5..9f069ee8 100644
--- a/frontend/app/pages/dashboard/teams/[id]/manage-members.vue
+++ b/frontend/app/pages/dashboard/teams/[id]/manage-members.vue
@@ -91,6 +91,7 @@ definePageMeta({ breadcrumb: { i18n: 'teams.members.title' } });
const usersStore = useUserStore();
const nodesStore = useNodesStore();
+const permissionsStore = useNodesPermissionsStore();
const { t } = useI18nT();
const { avatarURL } = useApi();
@@ -115,17 +116,21 @@ const permissions = ref<Permission[]>([]);
const invitationLink = (code: string) => `${window.location.origin}/dashboard/join-workspace?code=${encodeURIComponent(code)}`;
const contextOptions = computed(() => tree.getWorkspaceTree(node.value?.id as string, true));
-nodesStore.fetchPermissions(teamId, true).then(perms => (permissions.value = perms));
-nodesStore.fetchInvitations(teamId).then(invites => (invitations.value = invites));
+permissionsStore.fetchPermissions(teamId, true).then(perms => (permissions.value = perms));
+permissionsStore.fetchInvitations(teamId).then(invites => (invitations.value = invites));
watchEffect(async () => {
- const cached = nodesStore.getById(teamId);
- if (cached && cached.partial) {
- await nodesStore.fetch({ id: teamId });
- }
- node.value = nodesStore.getById(teamId);
- for (const perm of permissions.value) {
- usersStore.fetchPublicUser(perm.user_id);
+ try {
+ const cached = nodesStore.getById(teamId);
+ if (cached && cached.partial) {
+ await nodesStore.fetch({ id: teamId });
+ }
+ node.value = nodesStore.getById(teamId);
+ for (const perm of permissions.value) {
+ usersStore.fetchPublicUser(perm.user_id);
+ }
+ } catch {
+ node.value = undefined;
}
});
@@ -189,7 +194,7 @@ watch(
// Actions
const addPermission = async (user: PublicUser) => {
if (!user) return;
- const newPermission = await nodesStore.addPermission({
+ const newPermission = await permissionsStore.addPermission({
...permToAdd.value,
user_id: user.id,
});
@@ -200,20 +205,20 @@ const addPermission = async (user: PublicUser) => {
};
const updatePermission = async (perm: Permission) => {
- await nodesStore.updatePermission(perm);
+ await permissionsStore.updatePermission(perm);
permissions.value = permissions.value.map(p => (p.id === perm.id ? perm : p));
};
const removePermission = async (perm: Permission) => {
if (!node.value) return;
- await nodesStore.removePermission(perm);
+ await permissionsStore.removePermission(perm);
permissions.value = permissions.value.filter(p => p.id !== perm.id);
};
const createInvitation = async () => {
if (!node.value?.id) return;
try {
- const invitation = await nodesStore.addInvitation(node.value.id, selectedInvitationPermission.value);
+ const invitation = await permissionsStore.addInvitation(node.value.id, selectedInvitationPermission.value);
invitations.value = [invitation, ...invitations.value];
selectedInvitationPermission.value = 1;
notifications.add({ type: 'success', title: 'Invitation created' });
@@ -224,7 +229,7 @@ const createInvitation = async () => {
const deleteInvitation = async (invitationId: string) => {
if (!node.value?.id) return;
- await nodesStore.removeInvitation(node.value.id, invitationId);
+ await permissionsStore.removeInvitation(node.value.id, invitationId);
invitations.value = invitations.value.filter(invitation => invitation.id !== invitationId);
notifications.add({ type: 'success', title: 'Invitation revoked' });
};
diff --git a/frontend/app/services/localDB.ts b/frontend/app/services/localDB.ts
new file mode 100644
index 00000000..8944efce
--- /dev/null
+++ b/frontend/app/services/localDB.ts
@@ -0,0 +1,100 @@
+import localforage from 'localforage';
+import type { Node } from '~/stores/db_structures';
+
+export interface OfflineDelta {
+ id: string;
+ action: 'POST' | 'PUT' | 'DELETE';
+ timestamp: number;
+ node?: Partial<Node>;
+ order: number;
+}
+
+let counter = 0;
+
+const deltaStorage = localforage.createInstance({
+ name: 'alexandrie-offline',
+ storeName: 'deltas',
+});
+
+export const LocalDbService = {
+ /**
+ * Save a creation delta (POST) for a node
+ */
+ async saveCreateDelta(node: Partial<Node>): Promise<Node> {
+ const id = node.id || self.crypto.randomUUID();
+ const localNode = {
+ ...JSON.parse(JSON.stringify(node)),
+ id: id,
+ created_timestamp: node.created_timestamp || Date.now(),
+ updated_timestamp: node.updated_timestamp || Date.now(),
+ partial: false,
+ synced: false,
+ shared: false,
+ permissions: [],
+ };
+ const delta: OfflineDelta = {
+ id: id, // ID can be provided for the "pending" node (node that has not been created yet but has content from the editor)
+ action: 'POST',
+ timestamp: node.created_timestamp || Date.now(),
+ node: JSON.parse(JSON.stringify(localNode)),
+ order: counter++,
+ };
+ await deltaStorage.setItem(id, delta);
+ return localNode as Node;
+ },
+
+ /**
+ * Save an update delta (PUT) for a node
+ */
+ async saveUpdateDelta(node: Node): Promise<void> {
+ const currentDelta = await deltaStorage.getItem<OfflineDelta>(node.id);
+ if (currentDelta) {
+ currentDelta.node = JSON.parse(JSON.stringify(node));
+ node.updated_timestamp = Date.now();
+ await deltaStorage.setItem(node.id, currentDelta);
+ return;
+ }
+ const delta: OfflineDelta = {
+ id: node.id,
+ action: 'PUT',
+ timestamp: node.updated_timestamp || Date.now(),
+ node: JSON.parse(JSON.stringify(node)),
+ order: counter++,
+ };
+ await deltaStorage.setItem(node.id, delta);
+ },
+
+ /**
+ * Save a deletion delta (DELETE) for a node
+ */
+ async saveDeleteDelta(id: string): Promise<void> {
+ const delta: OfflineDelta = {
+ id,
+ action: 'DELETE',
+ timestamp: Date.now(),
+ order: counter++,
+ };
+ await deltaStorage.setItem(id, delta);
+ },
+
+ /**
+ * Get all deltas stored in the local database, sorted by order of action (oldest first).
+ */
+
+ async getDeltas(): Promise<OfflineDelta[]> {
+ const deltas: OfflineDelta[] = [];
+ await deltaStorage.iterate((value: OfflineDelta) => {
+ deltas.push(value);
+ });
+ return deltas.sort((a, b) => a.order - b.order);
+ },
+
+ async removeDelta(id: string): Promise<void> {
+ await deltaStorage.removeItem(id);
+ },
+
+ async clearDeltas(): Promise<void> {
+ await deltaStorage.clear();
+ counter = 0;
+ },
+};
diff --git a/frontend/app/stores/_utils.ts b/frontend/app/stores/_utils.ts
index 65fbde4f..24aa6824 100644
--- a/frontend/app/stores/_utils.ts
+++ b/frontend/app/stores/_utils.ts
@@ -8,6 +8,7 @@ export interface APIResult<Data> {
status: 'success' | 'error';
message: string;
result?: Data;
+ _statusCode: number;
}
export interface FetchOptions {
@@ -162,6 +163,7 @@ export async function makeRequest<T>(route: string, method: HttpMethod, body: ob
return {
status: 'error',
message: response.message || 'Authentication failed.',
+ _statusCode: response._statusCode,
};
}
}
@@ -173,6 +175,32 @@ export async function makeRequest<T>(route: string, method: HttpMethod, body: ob
return {
status: 'error',
message: err instanceof Error ? err.message : String(err),
+ _statusCode: 0,
};
}
}
+
+/**
+ * Detects if a response is likely due to network issues (offline, timeout, etc.)
+ * @param response - The API response to analyze
+ * @returns true if the response is likely a network error, false otherwise
+ */
+export function isNetworkError(response: APIResult<unknown>): boolean {
+ if (!response) return false;
+
+ if (typeof navigator !== 'undefined' && !navigator.onLine) {
+ return true;
+ }
+
+ if (response._statusCode !== undefined) {
+ return (
+ response._statusCode === 0 || // Connection failed (Offline / Crash TCP / CORS Blocked)
+ response._statusCode === 408 || // Request Timeout
+ response._statusCode === 502 || // Bad Gateway (Reverse proxy active but Backend Go down)
+ response._statusCode === 503 || // Service Unavailable
+ response._statusCode === 504 // Gateway Timeout
+ );
+ }
+
+ return false;
+}
diff --git a/frontend/app/stores/collection.ts b/frontend/app/stores/collection.ts
deleted file mode 100644
index 3cab24f8..00000000
--- a/frontend/app/stores/collection.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-type CollectionFunction<K, V> = (value: V, key: K, collection: Collection<K, V>) => boolean;
-
-export class Collection<K, V> extends Map<K, V> {
- public static readonly default: typeof Collection = Collection;
-
- public hasAllKeys(keys: K[]): boolean {
- return keys.every(k => this.has(k));
- }
- public hasAnyKey(keys: K[]): boolean {
- return keys.some(k => this.has(k));
- }
-
- public isUnique(key: K): boolean {
- const valOne = this.get(key);
- if (!valOne) throw new TypeError('Cannot find value for key: ' + key);
- // for (const val of this.filter()) {
- // if (val === valOne) return false;
- // }
-
- if (this.filter((v: V) => v === valOne).size <= 1) return true;
- return false;
- }
- public nextKey(key: K): K | undefined {
- const keys = [...this.keys()];
- const index = keys.indexOf(key);
- if (index === -1 || index === keys.length - 1) return undefined;
- return keys[index + 1];
- }
- public next(key: K): V | undefined {
- const nextKey = this.nextKey(key);
- if (!nextKey) return undefined;
- return this.get(nextKey);
- }
- public previousKey(key: K): K | undefined {
- const keys = [...this.keys()];
- const index = keys.indexOf(key);
- if (index <= 0) return undefined;
- return keys[index - 1];
- }
- public previous(key: K): V | undefined {
- const previousKey = this.previousKey(key);
- if (!previousKey) return undefined;
- return this.get(previousKey);
- }
- public firstKey(): K | null {
- const firstKey = this.keys().next().value;
- if (firstKey) return firstKey;
- return null;
- }
-
- public first(): V | undefined {
- if (this.values().next().value) return this.values().next().value;
- return undefined;
- }
-
- public lastKey(): K | undefined {
- const arr = [...this.keys()];
- if (arr[arr.length - 1]) return arr[arr.length - 1];
- return undefined;
- }
- public last(): V | undefined {
- const arr = [...this.values()];
- if (arr[arr.length - 1]) return arr[arr.length - 1];
- return undefined;
- }
-
- public find(fn: (value: V, key: K, collection: this) => boolean, thisArg?: unknown): V | undefined {
- if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
- for (const [key, val] of this) {
- if (fn(val, key, this)) return val;
- }
- return undefined;
- }
-
- public map<S = unknown>(fn: (value: V, key: K, collection: this) => S, thisArg?: unknown): Array<S> {
- const newArray = [];
- if (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);
- for (const [key, val] of this) {
- newArray.push(fn(val, key, this));
- }
- return newArray;
- }
-
- filter(f: CollectionFunction<K, V>): Collection<K, V> {
- const newCollection = new Collection<K, V>();
- for (const [k, v] of this) {
- if (f(v, k, this)) newCollection.set(k, v);
- }
- return newCollection;
- }
-
- public keysList(): K[] | null {
- const list: K[] = [];
- for (const k of this.keys()) {
- list.push(k);
- }
- if (list) return list;
- return null;
- }
-
- public valuesList(): V[] | null {
- const list: V[] = [];
- for (const v of this.values()) {
- list.push(v);
- }
- if (list) return list;
- return null;
- }
-
- public merge(...maps: Array<Collection<K, V> | Map<K, V>>): Collection<K, V> {
- for (const map of maps) {
- for (const [k, v] of map) {
- this.set(k, v);
- }
- }
- return this;
- }
-
- public toArray(): Array<V> {
- // eslint-disable-next-line @typescript-eslint/no-this-alias
- const that: this = this;
- const newArray = [];
- for (const [_, v] of that) {
- newArray.push(v);
- }
- return newArray;
- }
- public toJSON() {
- const obj = Object.fromEntries(this);
- return obj;
- }
-
- public each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {
- this.forEach(fn as (value: V, key: K, map: Map<K, V>) => void, thisArg);
- return this;
- }
-}
-
-export default Collection;
diff --git a/frontend/app/stores/db_structures.d.ts b/frontend/app/stores/db_structures.d.ts
index e3c80caa..c1d89ba4 100644
--- a/frontend/app/stores/db_structures.d.ts
+++ b/frontend/app/stores/db_structures.d.ts
@@ -52,6 +52,7 @@ export interface InvitationJoinResponse {
export interface Node extends DB_Node {
partial?: boolean;
+ synced?: boolean;
shared: boolean;
permissions: Permission[];
diff --git a/frontend/app/stores/nodes.importer.store.ts b/frontend/app/stores/nodes.importer.store.ts
new file mode 100644
index 00000000..2b1d8e59
--- /dev/null
+++ b/frontend/app/stores/nodes.importer.store.ts
@@ -0,0 +1,114 @@
+import type { DB_Node, Node } from './db_structures';
+import type { ImportJob, ResourceImportTask } from '~/helpers/backups/Importer';
+
+export const useNodesImporterStore = defineStore('nodesImporter', () => {
+ const nodesStore = useNodesStore();
+
+ // Prepare nodes for import by checking which nodes need to be created or updated
+ function prepareImport(nodesToImport: DB_Node[]): { toCreate: DB_Node[]; toUpdate: DB_Node[] } {
+ const toCreate: DB_Node[] = [];
+ const toUpdate: DB_Node[] = [];
+ for (const backupNode of nodesToImport) {
+ const existingNode = nodesStore.getById(backupNode.id);
+ if (!existingNode) {
+ toCreate.push(backupNode);
+ } else {
+ if (backupNode.updated_timestamp !== existingNode.updated_timestamp) {
+ toUpdate.push(backupNode);
+ }
+ }
+ }
+ return { toCreate, toUpdate };
+ }
+ async function importAllNodesAndResources(nodes: { toCreate: DB_Node[]; toUpdate: DB_Node[]; resources: ResourceImportTask[] }, job: Ref<ImportJob>) {
+ job.value.status = 'in_progress';
+ job.value.failures = 0;
+ nodesStore.nodes.startBulk();
+ try {
+ const corresponding: Record<string, string> = {};
+ await importAllNodes(nodes.toCreate, job, corresponding);
+ await updateAllNodes(nodes.toUpdate, job);
+ await importAllResources(nodes.resources, job, corresponding);
+ job.value.status = 'completed';
+ } catch (error) {
+ job.value.status = 'failed';
+ job.value.error_message = (error as Error).message;
+ }
+ nodesStore.nodes.endBulk();
+ }
+ async function importAllNodes(nodes: DB_Node[], job: Ref<ImportJob>, corresponding: Record<string, string>) {
+ const nodesById = new Map(nodes.map(n => [n.id, n]));
+
+ for (const node of nodes) {
+ await importNode(node, nodesById, corresponding, job);
+ }
+ }
+ async function importNode(node: DB_Node, nodesById: Map<string, DB_Node>, corresponding: Record<string, string>, job: Ref<ImportJob>): Promise<void> {
+ if (corresponding[node.id]) return; // Already imported
+
+ if (node.parent_id && !nodesStore.getById(node.parent_id)) {
+ const newParentId = corresponding[node.parent_id];
+
+ if (!newParentId) {
+ const parent = nodesById.get(node.parent_id); // Parent from the backup (future import)
+
+ if (parent) {
+ await importNode(parent, nodesById, corresponding, job); // Import the parent first
+ } else {
+ delete node.parent_id; // Parent not found → detach
+ }
+ }
+
+ if (corresponding[node.parent_id!]) node.parent_id = corresponding[node.parent_id!]; // Update parent_id after import
+ }
+
+ // Import of the node
+ const res = await nodesStore.post({ ...node, user_id: undefined });
+ job.value.created.push(node.id);
+ //await new Promise(resolve => setTimeout(resolve, 75));
+ corresponding[node.id] = res.id;
+ }
+ async function updateAllNodes(nodes: DB_Node[], job?: Ref<ImportJob>) {
+ for (const node of nodes) {
+ if (!nodesStore.getById(node.id)) continue;
+ await nodesStore.update({ ...(node as Node), partial: false, shared: false, permissions: [] });
+ if (job) job.value.updated.push(node.id);
+ await new Promise(resolve => setTimeout(resolve, 75));
+ }
+ }
+ async function importAllResources(resources: ResourceImportTask[], job: Ref<ImportJob>, corresponding: Record<string, string>) {
+ const preferences = usePreferencesStore();
+ const defaultUploadFolder = preferences.get('defaultUploadFolder').value;
+ const resourcesStore = useResourcesStore();
+ for (const task of resources) {
+ try {
+ let finalParentId = undefined;
+ if (task.parent_id) finalParentId = corresponding[task.parent_id] || task.parent_id;
+ else {
+ if (job.value.options?.defaultValues?.defaultParent) finalParentId = job.value.options.defaultValues.defaultParent;
+ else if (defaultUploadFolder) finalParentId = defaultUploadFolder;
+ }
+
+ const formData = new FormData();
+ formData.append('file', task.file);
+ if (finalParentId) formData.append('parent_id', finalParentId);
+
+ const uploadedResourceNode = await resourcesStore.post(formData);
+
+ job.value.created.push(uploadedResourceNode.id);
+
+ await new Promise(resolve => setTimeout(resolve, 50));
+ } catch (error) {
+ console.error(`[Import] Failed to upload resource ${task.file.name}:`, error);
+ }
+ }
+ }
+
+ return {
+ prepareImport,
+ importAllNodesAndResources,
+ importAllNodes,
+ updateAllNodes,
+ importAllResources,
+ };
+});
diff --git a/frontend/app/stores/nodes.permissions.store.ts b/frontend/app/stores/nodes.permissions.store.ts
new file mode 100644
index 00000000..48e9b833
--- /dev/null
+++ b/frontend/app/stores/nodes.permissions.store.ts
@@ -0,0 +1,154 @@
+import type { InvitationJoinResponse, Node, NodeInvitation, Permission } from './db_structures';
+
+export const useNodesPermissionsStore = defineStore('nodesPermissions', () => {
+ const nodesStore = useNodesStore();
+ const nodes = nodesStore.getAll;
+ const isFetching = ref(false);
+
+ async function fetchPermissions(nodeId: string, recursive = false): Promise<Permission[]> {
+ const params = new URLSearchParams({
+ recursive: recursive.toString(),
+ });
+ const request = await makeRequest(`nodes/${nodeId}/permissions?${params.toString()}`, 'GET', {});
+ if (request.status === 'success') {
+ const permissions = request.result as Permission[];
+ if (!permissions || permissions.length === 0) return [];
+ nodes.startBulk();
+ for (const perm of permissions) {
+ const node = nodes.get(perm.node_id);
+ if (!node) continue;
+ const existingPermIndex = node.permissions.findIndex(p => p.id === perm.id);
+ if (existingPermIndex !== -1) node.permissions[existingPermIndex] = perm;
+ else node.permissions.push(perm);
+ nodes.set(node.id, node);
+ }
+ nodes.endBulk();
+ return permissions;
+ }
+ console.error('[store/nodes] Fetching permissions failed:', request.message);
+ return [];
+ }
+
+ function hasPermissions(node: Node, level: number) {
+ // Case 1: User is the owner => All permissions
+ // Case 2: User has a permission entry for this node
+ // Case 3: A parent node has a permission entry for this node (inherited permissions)
+ const userStore = useUserStore();
+ if (node.user_id === userStore.user?.id) return true;
+ if (node.accessibility === 3 && level <= node.access) return true;
+ let permission = node.permissions.find(p => p.user_id === userStore.user?.id)?.permission || 0;
+ let currentNode = node;
+ while (permission < level && currentNode.parent_id) {
+ const parentNode = nodes.get(currentNode.parent_id);
+ if (!parentNode) break;
+ if (parentNode.user_id === userStore.user?.id) return true; // owner of parent node
+ const parentPerm = parentNode.permissions.find(p => p.user_id === userStore.user?.id);
+ if (parentPerm && parentPerm.permission > permission) permission = parentPerm.permission;
+ currentNode = parentNode;
+ }
+ return permission >= level;
+ }
+
+ async function addPermission(perm: Omit<Permission, 'id' | 'created_timestamp'>): Promise<Permission> {
+ console.log(`[store/nodes/permissions] Adding permission for user ${perm.user_id} on node ${perm.node_id}`);
+ const node = nodes.get(perm.node_id);
+ if (!node) throw 'Node not found in store, cannot add permission';
+ const request = await makeRequest(`nodes/${perm.node_id}/permissions`, 'POST', perm);
+ if (request.status === 'success') {
+ const newPermission = request.result as Permission;
+ nodes.set(
+ node.id,
+ {
+ ...node,
+ permissions: [...node.permissions, newPermission],
+ },
+ true,
+ );
+ return newPermission;
+ } else throw request.message;
+ }
+
+ async function updatePermission(perm: Permission) {
+ console.log(`[store/nodes/permissions] Updating permission for user ${perm.user_id} on node ${perm.node_id}`);
+ const node = nodes.get(perm.node_id);
+ if (!node) throw 'Node not found in store, cannot update permission';
+ const request = await makeRequest(`nodes/${perm.node_id}/permissions/${perm.id}`, 'PATCH', { permission: perm.permission });
+ if (request.status === 'success') {
+ const index = node.permissions.findIndex(p => p.id === perm.id);
+ const newPermissions = [...node.permissions];
+ if (index !== -1 && newPermissions[index]) {
+ newPermissions[index] = { ...newPermissions[index], permission: perm.permission };
+ nodes.set(node.id, {
+ ...node,
+ permissions: newPermissions,
+ });
+ }
+ } else throw request.message;
+ }
+
+ async function removePermission(perm: Permission) {
+ console.log(`[store/nodes/permissions] Removing permission for user ${perm.user_id} on node ${perm.node_id}`);
+ const node = nodes.get(perm.node_id);
+ if (!node) throw 'Node not found in store, cannot remove permission';
+ const request = await makeRequest(`nodes/${perm.node_id}/permissions/${perm.id}`, 'DELETE', {});
+ if (request.status === 'success') {
+ const newPermissions = node.permissions.filter(p => p.id !== perm.id);
+ nodes.set(node.id, {
+ ...node,
+ permissions: newPermissions,
+ });
+ } else throw request.message;
+ }
+
+ async function fetchInvitations(nodeId: string): Promise<NodeInvitation[]> {
+ const request = await makeRequest<NodeInvitation[]>(`nodes/${nodeId}/invitations`, 'GET', {});
+ if (request.status === 'success') {
+ return request.result || [];
+ }
+ throw request.message;
+ }
+
+ async function addInvitation(nodeId: string, permission_level: number): Promise<NodeInvitation> {
+ const request = await makeRequest<NodeInvitation>(`nodes/${nodeId}/invitations`, 'POST', { permission_level });
+ if (request.status === 'success') return request.result as NodeInvitation;
+ throw request.message;
+ }
+
+ async function removeInvitation(nodeId: string, invitationId: string) {
+ const request = await makeRequest(`nodes/${nodeId}/invitations/${invitationId}`, 'DELETE', {});
+ if (request.status !== 'success') throw request.message;
+ }
+ async function joinInvitation(codeOrLink: string): Promise<InvitationJoinResponse> {
+ const request = await makeRequest<InvitationJoinResponse>('nodes/invitations/join', 'POST', { code: codeOrLink });
+ if (request.status === 'success' && request.result) {
+ const { node, permission } = request.result;
+ const existing = nodes.get(node.id);
+ nodes.set(node.id, {
+ ...(existing || {}),
+ ...node,
+ partial: false,
+ shared: true,
+ permissions: [permission],
+ } as Node);
+ return request.result;
+ }
+ throw request.message;
+ }
+
+ function clear() {
+ isFetching.value = false;
+ }
+
+ return {
+ fetchPermissions,
+ hasPermissions,
+ addPermission,
+ updatePermission,
+ removePermission,
+ fetchInvitations,
+ addInvitation,
+ removeInvitation,
+ joinInvitation,
+ clear,
+ };
+});
diff --git a/frontend/app/stores/nodes.store.ts b/frontend/app/stores/nodes.store.ts
index 5a59fe41..56805945 100644
--- a/frontend/app/stores/nodes.store.ts
+++ b/frontend/app/stores/nodes.store.ts
@@ -1,8 +1,8 @@
-import { Collection } from './collection';
import { IndexedCollection } from '~/helpers/IndexedCollection';
import { parseTags, mergeNode } from '~/helpers/node';
-import type { DB_Node, InvitationJoinResponse, Node, NodeInvitation, NodeSearchResult, Permission, PublicNodeResponse } from './db_structures';
-import type { ImportJob, ResourceImportTask } from '~/helpers/backups/Importer';
+import { LocalDbService } from '~/services/localDB';
+import { skipHydrate } from 'pinia';
+import type { DB_Node, Node, NodeSearchResult, Permission } from './db_structures';
export type TeamRole = 0;
export type CategoryRole = 1 | 2;
@@ -23,594 +23,399 @@ export interface SearchOptions {
role?: NodeRole;
}
-export const useNodesStore = defineStore('nodes', {
- state: () => ({
- nodes: new IndexedCollection(),
- public_nodes: new Collection<string, Node>(),
- allTags: [] as string[],
- isFetching: false,
- }),
- getters: {
- getAll: state => state.nodes,
- getAllTags: state => state.allTags,
- getById: state => (id: string) => state.nodes.get(id),
- getTotalUsedStorage: state => state.nodes.toSortedArray().reduce((total, node) => total + (node.size || 0), 0),
-
- /* Getters for nodes by role */
- teams: state => state.nodes.getIdsByRole(0).map(id => state.nodes.get(id)!),
- categories: state => [...state.nodes.getIdsByRole(1), ...state.nodes.getIdsByRole(2)].map(id => state.nodes.get(id)!),
- workspaces: state => state.nodes.getIdsByRole(1).map(id => state.nodes.get(id)!),
- documents: state => state.nodes.getIdsByRole(3).map(id => state.nodes.get(id)!),
- resources: state => state.nodes.getIdsByRole(4).map(id => state.nodes.get(id)!),
-
- /**
- * Recursive getters
- */
-
- // Check if a node (descendantId) is a descendant of another node
- isDescendant:
- state =>
- (parent: Node, descendantId: string): boolean => {
- let current = state.nodes.get(descendantId);
- while (current?.parent_id) {
- if (current.parent_id === parent.id) return true;
- current = state.nodes.get(current.parent_id);
- }
- return false;
- },
- // Get all descendant IDs of a node
- getDescendantIds:
- state =>
- (id: string): string[] => {
- const result: string[] = [];
- const queue: string[] = [id];
-
- while (queue.length > 0) {
- const currentId = queue.shift()!;
- const childrenIds = state.nodes.getChildrenIds(currentId);
- for (const childId of childrenIds) {
- result.push(childId);
- queue.push(childId);
- }
- }
- return result;
- },
-
- search:
- state =>
- (options: SearchOptions, nodes = state.nodes.toSortedArray()) => {
- const {
- query,
- fromDate,
- toDate,
- dateType = 'modified',
- tags,
- category,
- sortBy = 'modified',
- sortType = 'descending',
- matchMode = 'includes',
- } = options;
-
- const queryLower = query?.toLowerCase().trim();
- const hasQuery = Boolean(queryLower);
- const hasTags = tags && tags.length > 0;
-
- const filtered = nodes.filter(node => {
- // --- Filter by role ---
- if (options.role && node.role !== options.role) return false;
- // --- Filter by text search ---
- if (hasQuery) {
- const content = `${node.name ?? ''} ${node.description ?? ''} ${node.tags ?? ''}`.toLowerCase();
- switch (matchMode) {
- case 'starts':
- if (!content.startsWith(queryLower!)) return false;
- break;
- case 'exact':
- if (node.name.toLowerCase() !== queryLower) return false;
- break;
- default: // includes
- if (!content.includes(queryLower!)) return false;
- }
- }
-
- // --- Filter by dates ---
- if (fromDate || toDate) {
- const timestamp = dateType === 'created' ? node.created_timestamp : node.updated_timestamp;
- const nodeDate = new Date(timestamp);
- if (fromDate && nodeDate < fromDate) return false;
- if (toDate && nodeDate > toDate) return false;
- }
-
- // --- Filter by tags ---
- if (hasTags) {
- if (!node.tags) return false;
- const nodeTags = parseTags(node.tags);
- // All tags must match
- if (!tags!.some(tag => nodeTags.includes(tag))) return false;
- }
-
- // --- Filter by category ---
- if (category && node.parent_id !== category) return false;
-
- return true;
- });
-
- // --- Sort results ---
- filtered.sort((a, b) => {
- let valA: string | number = '';
- let valB: string | number = '';
-
- switch (sortBy) {
- case 'created':
- valA = new Date(a.created_timestamp).getTime();
- valB = new Date(b.created_timestamp).getTime();
- break;
- case 'modified':
- valA = new Date(a.updated_timestamp).getTime();
- valB = new Date(b.updated_timestamp).getTime();
- break;
- case 'name':
- valA = a.name.toLowerCase();
- valB = b.name.toLowerCase();
- break;
- }
-
- if (valA < valB) return sortType === 'ascending' ? -1 : 1;
- if (valA > valB) return sortType === 'ascending' ? 1 : -1;
- return 0;
- });
-
- return filtered;
- },
- hasPermissions: state => (node: Node, level: number) => {
- // Case 1: User is the owner => All permissions
- // Case 2: User has a permission entry for this node
- // Case 3: A parent node has a permission entry for this node (inherited permissions)
- const userStore = useUserStore();
- if (node.user_id === userStore.user?.id) return true;
- if (node.accessibility === 3 && level <= node.access) return true;
- let permission = node.permissions.find(p => p.user_id === userStore.user?.id)?.permission || 0;
- let currentNode = node;
- while (permission < level && currentNode.parent_id) {
- const parentNode = state.nodes.get(currentNode.parent_id);
- if (!parentNode) break;
- if (parentNode.user_id === userStore.user?.id) return true; // owner of parent node
- const parentPerm = parentNode.permissions.find(p => p.user_id === userStore.user?.id);
- if (parentPerm && parentPerm.permission > permission) permission = parentPerm.permission;
- currentNode = parentNode;
- }
- return permission >= level;
- },
- },
- actions: {
- async init() {
- console.log('[store/nodes] Initializing store');
- this.clear();
- await Promise.all([this.fetch(), this.fetchShared()]);
- },
-
- recomputeTags() {
- const tags = new Set<string>();
-
- this.nodes.startBulk();
-
- this.nodes.forEach(node => {
- if (node.tags) {
- parseTags(node.tags).forEach(tag => tags.add(tag));
- }
- if (node.parent_id && !this.nodes.get(node.parent_id)) {
- this.nodes.set(node.id, { ...node, parent_id: '' });
- }
+export const useNodesStore = defineStore('nodes', () => {
+ const userStore = useUserStore();
+
+ const nodes = shallowRef(new IndexedCollection());
+ const allTags = ref<string[]>([]);
+ const isFetching = ref(false);
+
+ const getAll = computed(() => nodes.value);
+ const getAllTags = computed(() => allTags.value);
+ const getById = computed(() => (id: string) => nodes.value.get(id));
+ const getTotalUsedStorage = computed(() => nodes.value.toSortedArray().reduce((total, node) => total + (node.size || 0), 0));
+
+ /* Getters for nodes by role */
+ const teams = computed(() => nodes.value.getIdsByRole(0).map(id => nodes.value.get(id)!));
+ const categories = computed(() => [...nodes.value.getIdsByRole(1), ...nodes.value.getIdsByRole(2)].map(id => nodes.value.get(id)!));
+ const workspaces = computed(() => nodes.value.getIdsByRole(1).map(id => nodes.value.get(id)!));
+ const documents = computed(() => nodes.value.getIdsByRole(3).map(id => nodes.value.get(id)!));
+ const resources = computed(() => nodes.value.getIdsByRole(4).map(id => nodes.value.get(id)!));
+
+ async function init() {
+ console.log('[store/nodes] Initializing store');
+ clear();
+
+ isFetching.value = true;
+ nodes.value.startBulk();
+ await Promise.all([syncLocalDeltas(), fetch(), fetchShared()]);
+ nodes.value.endBulk();
+ isFetching.value = false;
+ if (import.meta.client) {
+ window.addEventListener('online', () => {
+ console.log('[store/nodes] Online, syncing local deltas');
+ syncLocalDeltas();
});
-
- this.nodes.endBulk();
- this.allTags = Array.from(tags).sort();
- },
-
- async fetch<T extends FetchOptions>(opts?: T): Promise<'id' extends keyof T ? Node : IndexedCollection> {
- if (opts?.id && !this.nodes.get(opts.id)?.partial) return this.nodes.get(opts.id) as 'id' extends keyof T ? Node : IndexedCollection;
- console.log(`[store/nodes] Fetching nodes with options: ${JSON.stringify(opts)}`);
- if (!this.nodes.size) this.isFetching = true;
- const request = await makeRequest(`nodes/${opts?.id ? opts.id : 'user/@me'}`, 'GET', {});
- this.isFetching = false;
- if (request.status == 'success') {
- if (opts?.id) {
- const result = request.result as { node: DB_Node; permissions: Permission[] };
- const n = this.nodes.get(opts.id);
- let shared = false;
- if (n) shared = n.shared;
- // Check for orphaned parent_id and detach if necessary
- let finalParentId = result.node.parent_id;
- if (finalParentId && !this.nodes.has(finalParentId)) {
- finalParentId = '';
- }
-
- const updatedNode: Node = { ...(result.node as DB_Node), parent_id: finalParentId, partial: false, shared: shared, permissions: result.permissions };
- if (!n) this.nodes.set(opts.id, updatedNode);
- else this.nodes.set(opts.id, updatedNode);
- return updatedNode as 'id' extends keyof T ? Node : IndexedCollection;
- } else {
- if (!request.result) return this.nodes as 'id' extends keyof T ? Node : IndexedCollection;
- this.nodes.startBulk();
- for (const node of request.result as DB_Node[]) {
- const n = this.nodes.get(node.id);
- if (!n) this.nodes.set(node.id, { ...node, partial: true, shared: false, permissions: [] });
- else this.nodes.set(node.id, { ...node, partial: true, shared: false, permissions: [] });
- }
- this.nodes.endBulk();
- this.recomputeTags();
- return this.nodes as 'id' extends keyof T ? Node : IndexedCollection;
- }
- } else throw request;
- },
-
- async fetchPublic(id: string): Promise<{ node: Node; children: Node[] } | undefined> {
- console.log(`[store/nodes] Fetching public node with id: ${id}`);
- const existingDoc = this.public_nodes.get(id);
- if (existingDoc && existingDoc._children !== undefined) {
- return { node: existingDoc, children: existingDoc._children };
- }
- const request = await makeRequest(`nodes/public/${id}`, 'GET', {});
- if (request.status === 'success') {
- const response = request.result as PublicNodeResponse;
- const children: Node[] = (response.children || []).map(c => ({ ...c, partial: true, shared: false, permissions: [] }));
- const fetchedDoc: Node & { _children?: Node[] } = {
- ...response.node,
- partial: false,
- shared: false,
- permissions: [],
- _children: children,
- };
- this.public_nodes.set(fetchedDoc.id, fetchedDoc);
- return { node: fetchedDoc, children };
- } else return undefined;
- },
-
- async fetchShared(): Promise<IndexedCollection> {
- console.log(`[store/nodes] Fetching shared nodes`);
- const request = await makeRequest(`nodes/shared/@me`, 'GET', {});
- if (request.status === 'success') {
- if (!request.result) return this.nodes as IndexedCollection;
- this.nodes.startBulk();
- for (const node of request.result as DB_Node[]) {
- let finalParentId = node.parent_id;
- if (finalParentId && !this.nodes.has(finalParentId)) {
- finalParentId = '';
- }
- if (!this.nodes.has(node.id))
- this.nodes.set(node.id, { ...node, parent_id: finalParentId, partial: true, shared: true, permissions: node.permissions || [] });
- else {
- const state = this.nodes.get(node.id);
- this.nodes.set(node.id, { ...node, parent_id: finalParentId, partial: true, shared: state?.shared ?? true, permissions: node.permissions || [] });
- }
- }
- this.nodes.endBulk();
- return this.nodes as IndexedCollection;
- } else throw request;
- },
- /**
- * Performs a fulltext search on the server using MySQL FULLTEXT index
- * This is optimized for searching in document content (body)
- * @param query - Search query (min 2 characters)
- * @param includeContent - Whether to search in document body content
- * @param limit - Max results to return
- */
- async searchFulltext(query: string, includeContent = true, limit = 20): Promise<NodeSearchResult[]> {
- if (query.length < 2) return [];
- const params = new URLSearchParams({
- q: query,
- content: includeContent.toString(),
- limit: limit.toString(),
- });
- const request = await makeRequest(`nodes/search?${params.toString()}`, 'GET', {});
- if (request.status === 'success') {
- return request.result as NodeSearchResult[];
- }
- console.error('[store/nodes] Fulltext search failed:', request.message);
- return [];
- },
-
- async post(node: Partial<Node>): Promise<DB_Node> {
- const request = await makeRequest('nodes', 'POST', { ...node, id: undefined });
- if (request.status == 'success') {
- this.nodes.set((request.result as DB_Node).id, { ...(request.result as DB_Node), partial: false, shared: false, permissions: [] });
- return request.result as DB_Node;
- } else throw request.message;
- },
-
- async update(node: Node) {
- if (node.partial) {
- console.log('[store/nodes] Node looks partial, cannot update it directly.');
- const full_node = await this.fetch({ id: node.id });
- if (!full_node) throw 'Node not found';
- node = mergeNode(node, full_node);
- }
- const request = await makeRequest(`nodes/${node.id}`, 'PUT', node);
- if (request.status == 'success') {
- node.updated_timestamp = Date.now(); // approximate update time for better UX & backups import
- if (node.parent_id && !this.nodes.has(node.parent_id)) node.parent_id = ''; // Check for orphaned parent_id and detach if necessary
- this.nodes.set(node.id, node);
- return this.nodes;
- } else throw request.message;
- },
-
- async duplicate(node: Node): Promise<DB_Node> {
- if (!node) throw 'Node not found in store, cannot duplicate';
- if (node.partial) {
- console.log('[store/nodes] Node looks partial, cannot duplcate it directly.');
- const full_node = await this.fetch({ id: node.id });
- if (!full_node) throw 'Node not found';
- node = mergeNode(node, full_node);
- }
- // use the post method to duplicate the node
- const newNodeData: Partial<Node> = {
- name: node.name,
- description: node.description,
- role: node.role,
- parent_id: node.parent_id,
- tags: node.tags,
- accessibility: node.accessibility,
- access: node.access,
- content: node.content,
- content_compiled: node.content_compiled,
- };
- const newNode = await this.post(newNodeData);
- return newNode;
- },
- async delete(id: string) {
- const request = await makeRequest(`nodes/${id}`, 'DELETE', {});
- if (request.status == 'success') {
- const allChildrens = this.getDescendantIds(id);
- this.nodes.delete(id);
- allChildrens.forEach(childId => this.nodes.delete(childId));
- } else throw request.message;
- },
-
- async bulkDelete(nodes: Node[]) {
- const deletedIds: string[] = [];
- const failedIds: { id: string; message: string }[] = [];
- for (const node of nodes) {
- try {
- const request = await makeRequest(`nodes/${node.id}`, 'DELETE', {});
- if (request.status === 'success') {
- deletedIds.push(node.id);
- } else {
- failedIds.push({ id: node.id, message: request.message || 'Unknown error' });
- }
- } catch (error) {
- failedIds.push({ id: node.id, message: (error as Error).message });
+ }
+ }
+
+ async function syncLocalDeltas() {
+ const deltas = await LocalDbService.getDeltas();
+ await LocalDbService.clearDeltas(); // Clear deltas before syncing to avoid duplicates in case of failure & reset counter
+ const corresponding: Record<string, string> = {};
+ for (const delta of deltas) {
+ if (nodes.value.get(delta.id)) nodes.value.delete(delta.id); // Remove the node from the store to ensure a clean state before syncing
+ try {
+ if (delta.action === 'POST') {
+ if (delta.node?.parent_id && corresponding[delta.node.parent_id]) delta.node.parent_id = corresponding[delta.node.parent_id];
+ const res = await post(delta.node!);
+ corresponding[delta.id] = res.id;
+ } else if (delta.action === 'PUT' && delta.node) {
+ await update(delta.node! as Node);
+ } else if (delta.action === 'DELETE') {
+ await remove(delta.id);
}
+ } catch (error) {
+ console.error(`[store/nodes] Failed to sync delta ${delta.action} for node ${delta.id}:`, error);
}
- // Update store
- this.nodes.startBulk();
- deletedIds.forEach(id => {
- const allChildrens = this.getDescendantIds(id);
- this.nodes.delete(id);
- allChildrens.forEach(childId => this.nodes.delete(childId));
- });
- this.nodes.endBulk();
- return { deletedIds, failedIds };
- },
- // ********************************** Permissions management **********************************
-
- async fetchPermissions(nodeId: string, recursive = false): Promise<Permission[]> {
- const params = new URLSearchParams({
- recursive: recursive.toString(),
- });
- const request = await makeRequest(`nodes/${nodeId}/permissions?${params.toString()}`, 'GET', {});
- if (request.status === 'success') {
- const permissions = request.result as Permission[];
- if (!permissions || permissions.length === 0) return [];
- this.nodes.startBulk();
- for (const perm of permissions) {
- const node = this.nodes.get(perm.node_id);
- if (!node) continue;
- const existingPermIndex = node.permissions.findIndex(p => p.id === perm.id);
- if (existingPermIndex !== -1) node.permissions[existingPermIndex] = perm;
- else node.permissions.push(perm);
- this.nodes.set(node.id, node);
- }
- this.nodes.endBulk();
- return permissions;
+ }
+ }
+
+ function recomputeTags() {
+ const tags = new Set<string>();
+
+ nodes.value.startBulk();
+
+ nodes.value.forEach(node => {
+ if (node.tags) {
+ parseTags(node.tags).forEach(tag => tags.add(tag));
}
- console.error('[store/nodes] Fetching permissions failed:', request.message);
- return [];
- },
-
- async addPermission(perm: Omit<Permission, 'id' | 'created_timestamp'>): Promise<Permission> {
- console.log(`[store/nodes/permissions] Adding permission for user ${perm.user_id} on node ${perm.node_id}`);
- const node = this.nodes.get(perm.node_id);
- if (!node) throw 'Node not found in store, cannot add permission';
- const request = await makeRequest(`nodes/${perm.node_id}/permissions`, 'POST', perm);
- if (request.status === 'success') {
- const newPermission = request.result as Permission;
- this.nodes.set(node.id, {
- ...node,
- permissions: [...node.permissions, newPermission],
- });
- return newPermission;
- } else throw request.message;
- },
-
- async updatePermission(perm: Permission) {
- console.log(`[store/nodes/permissions] Updating permission for user ${perm.user_id} on node ${perm.node_id}`);
- const node = this.nodes.get(perm.node_id);
- if (!node) throw 'Node not found in store, cannot update permission';
- const request = await makeRequest(`nodes/${perm.node_id}/permissions/${perm.id}`, 'PATCH', { permission: perm.permission });
- if (request.status === 'success') {
- const index = node.permissions.findIndex(p => p.id === perm.id);
- const newPermissions = [...node.permissions];
- if (index !== -1 && newPermissions[index]) {
- newPermissions[index] = { ...newPermissions[index], permission: perm.permission };
- this.nodes.set(node.id, {
- ...node,
- permissions: newPermissions,
- });
- }
- } else throw request.message;
- },
-
- async removePermission(perm: Permission) {
- console.log(`[store/nodes/permissions] Removing permission for user ${perm.user_id} on node ${perm.node_id}`);
- const node = this.nodes.get(perm.node_id);
- if (!node) throw 'Node not found in store, cannot remove permission';
- const request = await makeRequest(`nodes/${perm.node_id}/permissions/${perm.id}`, 'DELETE', {});
- if (request.status === 'success') {
- const newPermissions = node.permissions.filter(p => p.id !== perm.id);
- this.nodes.set(node.id, {
- ...node,
- permissions: newPermissions,
- });
- } else throw request.message;
- },
-
- // ********************************** Invitations management **********************************
-
- async fetchInvitations(nodeId: string): Promise<NodeInvitation[]> {
- const request = await makeRequest<NodeInvitation[]>(`nodes/${nodeId}/invitations`, 'GET', {});
- if (request.status === 'success') {
- return request.result || [];
+ if (node.parent_id && !nodes.value.get(node.parent_id)) {
+ nodes.value.set(node.id, { ...node, parent_id: '' });
}
- throw request.message;
- },
-
- async addInvitation(nodeId: string, permission_level: number): Promise<NodeInvitation> {
- const request = await makeRequest<NodeInvitation>(`nodes/${nodeId}/invitations`, 'POST', { permission_level });
- if (request.status === 'success') return request.result as NodeInvitation;
- throw request.message;
- },
-
- async removeInvitation(nodeId: string, invitationId: string) {
- const request = await makeRequest(`nodes/${nodeId}/invitations/${invitationId}`, 'DELETE', {});
- if (request.status !== 'success') throw request.message;
- },
- async joinInvitation(codeOrLink: string): Promise<InvitationJoinResponse> {
- const request = await makeRequest<InvitationJoinResponse>('nodes/invitations/join', 'POST', { code: codeOrLink });
- if (request.status === 'success' && request.result) {
- const { node, permission } = request.result;
- const existing = this.nodes.get(node.id);
- this.nodes.set(node.id, {
- ...(existing || {}),
- ...node,
- partial: false,
- shared: true,
- permissions: [permission],
- } as Node);
- return request.result;
+ });
+
+ nodes.value.endBulk();
+ allTags.value = Array.from(tags).sort();
+ }
+
+ // Check if a node (descendantId) is a descendant of another node
+ const isDescendant = (parent: Node, descendantId: string): boolean => {
+ let current = nodes.value.get(descendantId);
+ while (current?.parent_id) {
+ if (current.parent_id === parent.id) return true;
+ current = nodes.value.get(current.parent_id);
+ }
+ return false;
+ };
+ // Get all descendant IDs of a node
+ const getDescendantIds = (id: string): string[] => {
+ const result: string[] = [];
+ const queue: string[] = [id];
+
+ while (queue.length > 0) {
+ const currentId = queue.shift()!;
+ const childrenIds = nodes.value.getChildrenIds(currentId);
+ for (const childId of childrenIds) {
+ result.push(childId);
+ queue.push(childId);
}
- throw request.message;
- },
-
- // ********************************** Import management **********************************
-
- // Prepare nodes for import by checking which nodes need to be created or updated
- prepareImport(nodes: DB_Node[]): { toCreate: DB_Node[]; toUpdate: DB_Node[] } {
- const toCreate: DB_Node[] = [];
- const toUpdate: DB_Node[] = [];
- for (const backupNode of nodes) {
- const existingNode = this.nodes.get(backupNode.id);
- if (!existingNode) {
- toCreate.push(backupNode);
- } else {
- if (backupNode.updated_timestamp !== existingNode.updated_timestamp) {
- toUpdate.push(backupNode);
- }
+ }
+ return result;
+ };
+
+ const search = (options: SearchOptions, nodesToSearch: Node[] | readonly Node[] = nodes.value.toSortedArray()) => {
+ const { query, fromDate, toDate, dateType = 'modified', tags, category, sortBy = 'modified', sortType = 'descending', matchMode = 'includes' } = options;
+
+ const queryLower = query?.toLowerCase().trim();
+ const hasQuery = Boolean(queryLower);
+ const hasTags = tags && tags.length > 0;
+
+ const filtered = nodesToSearch.filter(node => {
+ // --- Filter by role ---
+ if (options.role && node.role !== options.role) return false;
+ // --- Filter by text search ---
+ if (hasQuery) {
+ const content = `${node.name ?? ''} ${node.description ?? ''} ${node.tags ?? ''}`.toLowerCase();
+ switch (matchMode) {
+ case 'starts':
+ if (!content.startsWith(queryLower!)) return false;
+ break;
+ case 'exact':
+ if (node.name.toLowerCase() !== queryLower) return false;
+ break;
+ default: // includes
+ if (!content.includes(queryLower!)) return false;
}
}
- return { toCreate, toUpdate };
- },
- async importAllNodesAndResources(nodes: { toCreate: DB_Node[]; toUpdate: DB_Node[]; resources: ResourceImportTask[] }, job: Ref<ImportJob>) {
- job.value.status = 'in_progress';
- job.value.failures = 0;
- try {
- const corresponding: Record<string, string> = {};
- await this.importAllNodes(nodes.toCreate, job, corresponding);
- await this.updateAllNodes(nodes.toUpdate, job);
- await this.importAllResources(nodes.resources, job, corresponding);
- job.value.status = 'completed';
- } catch (error) {
- job.value.status = 'failed';
- job.value.error_message = (error as Error).message;
- }
- },
-
- async importAllNodes(nodes: DB_Node[], job: Ref<ImportJob>, corresponding: Record<string, string>) {
- const nodesById = new Map(nodes.map(n => [n.id, n]));
- for (const node of nodes) {
- await this.importNode(node, nodesById, corresponding, job);
+ // --- Filter by dates ---
+ if (fromDate || toDate) {
+ const timestamp = dateType === 'created' ? node.created_timestamp : node.updated_timestamp;
+ const nodeDate = new Date(timestamp);
+ if (fromDate && nodeDate < fromDate) return false;
+ if (toDate && nodeDate > toDate) return false;
}
- },
- async importNode(node: DB_Node, nodesById: Map<string, DB_Node>, corresponding: Record<string, string>, job: Ref<ImportJob>): Promise<void> {
- if (corresponding[node.id]) return; // Already imported
- if (node.parent_id && !this.getById(node.parent_id)) {
- const newParentId = corresponding[node.parent_id];
+ // --- Filter by tags ---
+ if (hasTags) {
+ if (!node.tags) return false;
+ const nodeTags = parseTags(node.tags);
+ // All tags must match
+ if (!tags!.some(tag => nodeTags.includes(tag))) return false;
+ }
- if (!newParentId) {
- const parent = nodesById.get(node.parent_id); // Parent from the backup (future import)
+ // --- Filter by category ---
+ if (category && node.parent_id !== category) return false;
+
+ return true;
+ });
+
+ // --- Sort results ---
+ filtered.sort((a, b) => {
+ let valA: string | number = '';
+ let valB: string | number = '';
+
+ switch (sortBy) {
+ case 'created':
+ valA = a.created_timestamp;
+ valB = b.created_timestamp;
+ break;
+ case 'modified':
+ valA = a.updated_timestamp;
+ valB = b.updated_timestamp;
+ break;
+ case 'name':
+ valA = a.name.toLowerCase();
+ valB = b.name.toLowerCase();
+ break;
+ }
- if (parent) {
- await this.importNode(parent, nodesById, corresponding, job); // Import the parent first
- } else {
- delete node.parent_id; // Parent not found → detach
- }
+ if (valA < valB) return sortType === 'ascending' ? -1 : 1;
+ if (valA > valB) return sortType === 'ascending' ? 1 : -1;
+ return 0;
+ });
+
+ return filtered;
+ };
+
+ async function fetch<T extends FetchOptions>(opts?: T): Promise<'id' extends keyof T ? Node : IndexedCollection> {
+ if (opts?.id && !nodes.value.get(opts.id)?.partial) return nodes.value.get(opts.id) as 'id' extends keyof T ? Node : IndexedCollection;
+ console.log(`[store/nodes] Fetching nodes with options: ${JSON.stringify(opts)}`);
+ const request = await makeRequest(`nodes/${opts?.id ? opts.id : 'user/@me'}`, 'GET', {});
+ if (request.status == 'success') {
+ if (opts?.id) {
+ const result = request.result as { node: DB_Node; permissions: Permission[] };
+ const shared = nodes.value.get(opts.id)?.shared ?? false;
+ // Check for orphaned parent_id and detach if necessary
+ let finalParentId = result.node.parent_id;
+ if (finalParentId && !nodes.value.has(finalParentId)) {
+ finalParentId = '';
}
- if (corresponding[node.parent_id!]) node.parent_id = corresponding[node.parent_id!]; // Update parent_id after import
- }
-
- // Import of the node
- const res = await this.post({ ...node, user_id: undefined });
- job.value.created.push(node.id);
- await new Promise(resolve => setTimeout(resolve, 75));
- corresponding[node.id] = res.id;
- },
-
- async updateAllNodes(nodes: DB_Node[], job?: Ref<ImportJob>) {
- for (const node of nodes) {
- if (!this.getById(node.id)) continue;
- await this.update({ ...(node as Node), partial: false, shared: false, permissions: [] });
- if (job) job.value.updated.push(node.id);
- await new Promise(resolve => setTimeout(resolve, 75));
+ const updatedNode: Node = {
+ ...(result.node as DB_Node),
+ parent_id: finalParentId,
+ partial: false,
+ synced: true,
+ shared: shared,
+ permissions: result.permissions,
+ };
+ nodes.value.set(opts.id, updatedNode);
+ return updatedNode as 'id' extends keyof T ? Node : IndexedCollection;
+ } else {
+ if (!request.result) return nodes.value as 'id' extends keyof T ? Node : IndexedCollection;
+ nodes.value.startBulk();
+ for (const node of request.result as DB_Node[]) {
+ nodes.value.set(node.id, { ...node, partial: true, synced: true, shared: false, permissions: [] });
+ }
+ nodes.value.endBulk();
+ recomputeTags();
+ return nodes.value as 'id' extends keyof T ? Node : IndexedCollection;
}
- },
-
- async importAllResources(resources: ResourceImportTask[], job: Ref<ImportJob>, corresponding: Record<string, string>) {
- const preferences = usePreferencesStore();
- const defaultUploadFolder = preferences.get('defaultUploadFolder').value;
- const resourcesStore = useResourcesStore();
- for (const task of resources) {
- try {
- let finalParentId = undefined;
- if (task.parent_id) finalParentId = corresponding[task.parent_id] || task.parent_id;
- else {
- if (job.value.options?.defaultValues?.defaultParent) finalParentId = job.value.options.defaultValues.defaultParent;
- else if (defaultUploadFolder) finalParentId = defaultUploadFolder;
- }
-
- const formData = new FormData();
- formData.append('file', task.file);
- if (finalParentId) formData.append('parent_id', finalParentId);
-
- const uploadedResourceNode = await resourcesStore.post(formData);
-
- job.value.created.push(uploadedResourceNode.id);
-
- await new Promise(resolve => setTimeout(resolve, 50));
- } catch (error) {
- console.error(`[Import] Failed to upload resource ${task.file.name}:`, error);
+ } else throw request.message;
+ }
+
+ async function fetchShared(): Promise<IndexedCollection> {
+ console.log(`[store/nodes] Fetching shared nodes`);
+ const request = await makeRequest(`nodes/shared/@me`, 'GET', {});
+ if (request.status === 'success') {
+ if (!request.result) return nodes.value as IndexedCollection;
+ nodes.value.startBulk();
+ for (const node of request.result as DB_Node[]) {
+ let finalParentId = node.parent_id;
+ if (finalParentId && !nodes.value.has(finalParentId)) {
+ finalParentId = '';
+ }
+ if (!nodes.value.has(node.id))
+ nodes.value.set(node.id, { ...node, parent_id: finalParentId, partial: true, synced: true, shared: true, permissions: node.permissions || [] });
+ else {
+ const state = nodes.value.get(node.id);
+ nodes.value.set(node.id, {
+ ...node,
+ parent_id: finalParentId,
+ partial: true,
+ synced: true,
+ shared: state?.shared ?? true,
+ permissions: node.permissions || [],
+ });
}
}
- },
-
- clear() {
- this.nodes.clear();
- this.public_nodes.clear();
- this.allTags = [];
- this.isFetching = false;
- },
- },
+ nodes.value.endBulk();
+ return nodes.value as IndexedCollection;
+ } else throw request;
+ }
+ /**
+ * Performs a fulltext search on the server using MySQL FULLTEXT index
+ * This is optimized for searching in document content (body)
+ * @param query - Search query (min 2 characters)
+ * @param includeContent - Whether to search in document body content
+ * @param limit - Max results to return
+ */
+ async function searchFulltext(query: string, includeContent = true, limit = 20): Promise<NodeSearchResult[]> {
+ if (query.length < 2) return [];
+ const params = new URLSearchParams({
+ q: query,
+ content: includeContent.toString(),
+ limit: limit.toString(),
+ });
+ const request = await makeRequest(`nodes/search?${params.toString()}`, 'GET', {});
+ if (request.status === 'success') {
+ return request.result as NodeSearchResult[];
+ }
+ console.error('[store/nodes] Fulltext search failed:', request.message);
+ return [];
+ }
+
+ async function post(node: Partial<Node>): Promise<DB_Node> {
+ const oldId = node.id;
+ delete node.id;
+ const response = await makeRequest<DB_Node>('nodes', 'POST', { ...node, id: undefined });
+ if (response.status == 'success') {
+ nodes.value.set((response.result as DB_Node).id, { ...(response.result as DB_Node), partial: false, synced: true, shared: false, permissions: [] }, true);
+ return response.result as DB_Node;
+ } else if (isNetworkError(response)) {
+ node.user_id = userStore.user?.id;
+ const localNode = await LocalDbService.saveCreateDelta({ ...node, id: oldId });
+ nodes.value.set(localNode.id, localNode, true);
+ return localNode;
+ }
+ throw response.message || 'Failed to create node';
+ }
+
+ async function update(node: Node): Promise<void> {
+ if (node.partial) {
+ console.log('[store/nodes] Node looks partial, cannot update it directly.');
+ const full_node = await fetch({ id: node.id });
+ if (!full_node) throw 'Node not found';
+ node = mergeNode(node, full_node);
+ }
+ const response = await makeRequest(`nodes/${node.id}`, 'PUT', node);
+ if (response.status == 'success') {
+ node.updated_timestamp = Date.now(); // approximate update time for better UX & backups import
+ node.synced = true;
+ if (node.parent_id && !nodes.value.has(node.parent_id)) node.parent_id = ''; // Check for orphaned parent_id and detach if necessary
+ nodes.value.set(node.id, node, true);
+ } else if (isNetworkError(response)) {
+ await LocalDbService.saveUpdateDelta(node);
+ node.synced = false;
+ nodes.value.set(node.id, node, true);
+ }
+ nodes.value.rebuildIndexes();
+ }
+
+ async function duplicate(node: Node): Promise<DB_Node> {
+ if (!node) throw 'Node not found in store, cannot duplicate';
+ if (node.partial) {
+ console.log('[store/nodes] Node looks partial, cannot duplcate it directly.');
+ const full_node = await fetch({ id: node.id });
+ if (!full_node) throw 'Node not found';
+ node = mergeNode(node, full_node);
+ }
+ const newNodeData: Partial<Node> = {
+ name: node.name,
+ description: node.description,
+ role: node.role,
+ parent_id: node.parent_id,
+ tags: node.tags,
+ accessibility: node.accessibility,
+ access: node.access,
+ content: node.content,
+ content_compiled: node.content_compiled,
+ };
+ const newNode = await post(newNodeData);
+ return newNode;
+ }
+
+ async function remove(id: string) {
+ const response = await makeRequest(`nodes/${id}`, 'DELETE', {});
+ if (response.status == 'success') {
+ //
+ } else if (isNetworkError(response)) {
+ await LocalDbService.saveDeleteDelta(id);
+ }
+ const allChildrens = getDescendantIds(id);
+ nodes.value.delete(id);
+ allChildrens.forEach(childId => nodes.value.delete(childId));
+ }
+
+ async function bulkDelete(toDelete: Node[]) {
+ const deletedIds: string[] = [];
+ const failedIds: { id: string; message: string }[] = [];
+ for (const node of toDelete) {
+ const response = await makeRequest(`nodes/${node.id}`, 'DELETE', {});
+ if (response.status === 'success') {
+ deletedIds.push(node.id);
+ } else if (isNetworkError(response)) {
+ await LocalDbService.saveDeleteDelta(node.id);
+ deletedIds.push(node.id);
+ } else {
+ failedIds.push({ id: node.id, message: response.message || 'Unknown error' });
+ }
+ }
+ // Update store
+ nodes.value.startBulk();
+ deletedIds.forEach(id => {
+ const allChildrens = getDescendantIds(id);
+ nodes.value.delete(id);
+ allChildrens.forEach(childId => nodes.value.delete(childId));
+ });
+ nodes.value.endBulk();
+ return { deletedIds, failedIds };
+ }
+
+ function clear() {
+ nodes.value.clear();
+ allTags.value = [];
+ isFetching.value = false;
+ }
+
+ return {
+ nodes: skipHydrate(nodes),
+ allTags,
+ isFetching,
+ getAll,
+ getAllTags,
+ getById,
+ getTotalUsedStorage,
+ teams,
+ categories,
+ workspaces,
+ documents,
+ resources,
+ isDescendant,
+ getDescendantIds,
+ search,
+ init,
+ recomputeTags,
+ fetch,
+ fetchShared,
+ searchFulltext,
+ post,
+ update,
+ duplicate,
+ remove,
+ bulkDelete,
+ clear,
+ };
});
-
-// Helper functions
diff --git a/frontend/app/stores/resources.store.ts b/frontend/app/stores/resources.store.ts
index afa8a162..33f1a41f 100644
--- a/frontend/app/stores/resources.store.ts
+++ b/frontend/app/stores/resources.store.ts
@@ -10,7 +10,7 @@ export const useResourcesStore = defineStore('resources', {
}
const request = await makeRequest(`resources`, 'POST', resource);
if (request.status == 'success') {
- nodesStore.nodes.set((request.result as Node).id, request.result as Node);
+ nodesStore.nodes.set((request.result as Node).id, request.result as Node, true);
return request.result as Node;
} else throw request.message;
},
diff --git a/frontend/app/stores/tabs.stores.ts b/frontend/app/stores/tabs.stores.ts
index fd74b31c..a8c006df 100644
--- a/frontend/app/stores/tabs.stores.ts
+++ b/frontend/app/stores/tabs.stores.ts
@@ -1,3 +1,5 @@
+import localForage from 'localforage';
+
export interface Tab {
path: string;
name: string;
@@ -9,30 +11,25 @@ const STORAGE_KEY = 'app-tabs';
export const useTabsStore = defineStore('tabs', () => {
const tabs = ref<Tab[]>([]);
- // Chargement initial depuis le localStorage (côté client uniquement)
if (import.meta.client) {
- const saved = localStorage.getItem(STORAGE_KEY);
- if (saved) {
- try {
- tabs.value = JSON.parse(saved);
- } catch {
- tabs.value = [];
- }
- }
+ localForage
+ .getItem<Tab[]>(STORAGE_KEY)
+ .then(saved => {
+ if (saved) {
+ tabs.value = saved;
+ }
+ })
+ .catch(_ => (tabs.value = []));
}
- // Sauvegarde automatique à chaque modification de la liste
watch(
tabs,
- newTabs => {
- if (import.meta.client) {
- localStorage.setItem(STORAGE_KEY, JSON.stringify(newTabs));
- }
+ async newTabs => {
+ if (import.meta.client) await localForage.setItem(STORAGE_KEY, toRaw(newTabs));
},
{ deep: true },
);
- // Ajouter ou activer un onglet
function syncTab(tab: Tab) {
const exists = tabs.value.some(t => t.path === tab.path);
if (!exists) {
@@ -40,21 +37,18 @@ export const useTabsStore = defineStore('tabs', () => {
}
}
- // Fermer un onglet et retourner le prochain chemin à ouvrir si nécessaire
function closeTab(path: string, currentPath: string): string | null {
const index = tabs.value.findIndex(t => t.path === path);
if (index === -1) return null;
tabs.value.splice(index, 1);
- // Si on ferme l'onglet sur lequel on se trouve actuellement
if (currentPath === path) {
if (tabs.value.length > 0) {
- // On redirige vers l'onglet précédent, ou le premier disponible
const nextTab = tabs.value[index - 1] || tabs.value[0];
return nextTab!.path;
}
- return '/dashboard/home'; // Route de secours par défaut
+ return '/dashboard/home';
}
return null;
diff --git a/frontend/app/stores/user.store.ts b/frontend/app/stores/user.store.ts
index 3e7025ce..3b347db9 100644
--- a/frontend/app/stores/user.store.ts
+++ b/frontend/app/stores/user.store.ts
@@ -18,8 +18,7 @@ export const useUserStore = defineStore('user', {
actions: {
async login(username: string, password: string) {
try {
- // makeRequest doit être capable de vous retourner la réponse brute ou le body complet
- const response = await makeRequest<{ auth: boolean; pre_auth_token?: string; message?: string }>('auth', 'POST', { username, password });
+ const response = await makeRequest<{ auth: boolean; pre_auth_token?: string; message?: string; user?: User }>('auth', 'POST', { username, password });
if (response.status === 'success') {
if (response.result?.message === '2FA_REQUIRED') return { success: true, require2FA: true, preAuthToken: response.result?.pre_auth_token };
@@ -36,7 +35,7 @@ export const useUserStore = defineStore('user', {
async request2FA() {
const response = await makeRequest<{ secret: string; qr_code_url: string }>('auth/2fa/request', 'POST', {});
if (response.status === 'success') {
- return response.result; // contient { secret, qr_code_url }
+ return response.result;
}
throw response.message;
},
@@ -52,9 +51,9 @@ export const useUserStore = defineStore('user', {
async verify2FA(preAuthToken: string, code: string) {
try {
- const response = await makeRequest<{ success: boolean }>('auth/2fa/verify', 'POST', { pre_auth_token: preAuthToken, code });
+ const response = await makeRequest<{ user: User }>('auth/2fa/verify', 'POST', { pre_auth_token: preAuthToken, code });
if (response.status === 'success') {
- if (import.meta.client) localForage.setItem('isLoggedIn', 'true');
+ if (import.meta.client) localForage.setItem('isLoggedIn', true);
return { success: true };
}
throw response.message;
diff --git a/frontend/app/sw.ts b/frontend/app/sw.ts
index 9e8760e6..450d10d6 100644
--- a/frontend/app/sw.ts
+++ b/frontend/app/sw.ts
@@ -27,8 +27,7 @@ registerRoute(
statuses: [0, 200],
}),
new ExpirationPlugin({
- maxEntries: 5000,
- maxAgeSeconds: 30 * 24 * 60 * 60, // 30 days
+ maxEntries: 1000,
}),
],
}),
@@ -37,7 +36,32 @@ registerRoute(
);
// ─── API cache ───────────────────────────────────────────────────────────────
-registerRoute(({ url }) => url.pathname.startsWith('/api/') && !url.pathname.startsWith('/api/backup/'), new NetworkFirst({ cacheName: 'api-cache' }));
+registerRoute(
+ ({ url }) => url.origin === __BASE_API__ && !url.pathname.startsWith('/api/backup/'),
+ new NetworkFirst({
+ cacheName: 'api-cache',
+ networkTimeoutSeconds: 3,
+ plugins: [
+ new ExpirationPlugin({
+ maxEntries: 1000,
+ }),
+ ],
+ }),
+);
+
+// ─── CDN cache ────────────────────────────────────────────────────────────────
+registerRoute(
+ ({ url }) => url.origin === __BASE_CDN__,
+ new NetworkFirst({
+ cacheName: 'cdn-cache',
+ networkTimeoutSeconds: 3,
+ plugins: [
+ new ExpirationPlugin({
+ purgeOnQuotaError: true,
+ }),
+ ],
+ }),
+);
// ─── Share Target API handler ────────────────────────────────────────────────
// When the PWA receives a share via the Share Target API (POST with form data),
diff --git a/frontend/i18n/locales/de/settings.ts b/frontend/i18n/locales/de/settings.ts
index c329dfaa..cfad1fe7 100644
--- a/frontend/i18n/locales/de/settings.ts
+++ b/frontend/i18n/locales/de/settings.ts
@@ -30,6 +30,8 @@ export default {
chooseAccentColor: 'Akzentfarbe wählen',
displayUncategorizedResources: 'Nicht kategorisierte Ressourcen anzeigen',
displayUncategorizedResourcesDesc: 'Nicht kategorisierte Ressourcen (CDN-Uploads) oben in der Seitenleiste anzeigen.',
+ displayTabs: 'Registerkarten anzeigen',
+ displayTabsDesc: 'Aktiviere oder deaktiviere die Registerkartenleiste am oberen Rand des Dashboards.',
enableCompactMode: 'Kompaktmodus aktivieren',
enableCompactModeDesc: 'Reduziere die Größe der Seitenleistenelemente, um mehr Inhalt anzuzeigen.',
enableDarkMode: 'Dunkelmodus aktivieren',
diff --git a/frontend/i18n/locales/fr/settings.ts b/frontend/i18n/locales/fr/settings.ts
index 77736960..42f3627d 100644
--- a/frontend/i18n/locales/fr/settings.ts
+++ b/frontend/i18n/locales/fr/settings.ts
@@ -30,6 +30,8 @@ export default {
chooseAccentColor: "Choisir la couleur d'accent",
displayUncategorizedResources: 'Afficher les ressources non catégorisées',
displayUncategorizedResourcesDesc: 'Afficher les ressources (téléchargements du CDN) non catégorisées en haut de la barre latérale.',
+ displayTabs: 'Afficher les onglets',
+ displayTabsDesc: "Activer ou désactiver la barre d'onglets en haut du tableau de bord.",
enableCompactMode: 'Activer le mode compact',
enableCompactModeDesc: 'Réduire la taille des éléments de la barre latérale pour afficher plus de contenu.',
enableDarkMode: 'Activer le mode sombre',
diff --git a/frontend/i18n/locales/uk/settings.ts b/frontend/i18n/locales/uk/settings.ts
index ba8d4ec2..6d214158 100644
--- a/frontend/i18n/locales/uk/settings.ts
+++ b/frontend/i18n/locales/uk/settings.ts
@@ -29,6 +29,8 @@ export default {
chooseAccentColor: 'Вибрати акцентний колір',
displayUncategorizedResources: 'Показувати ресурси без категорії',
displayUncategorizedResourcesDesc: 'Показувати ресурси без категорії (завантаження CDN) у верхній частині бічної панелі.',
+ displayTabs: 'Показувати вкладки',
+ displayTabsDesc: 'Увімкнути або вимкнути панель вкладок у верхній частині панелі керування.',
enableCompactMode: 'Увімкнути компактний режим',
enableCompactModeDesc: 'Зменшити розмір елементів бічної панелі, щоб показати більше вмісту.',
enableDarkMode: 'Увімкнути темний режим',
diff --git a/frontend/nuxt.config.ts b/frontend/nuxt.config.ts
index b60e05b8..676d876d 100644
--- a/frontend/nuxt.config.ts
+++ b/frontend/nuxt.config.ts
@@ -14,10 +14,6 @@ export default defineNuxtConfig({
lang: 'en',
},
link: [
- {
- href: 'https://alexandrie-hub.fr',
- rel: 'canonical',
- },
{
href: '/manifest.webmanifest',
rel: 'manifest',
@@ -34,12 +30,10 @@ export default defineNuxtConfig({
rel: 'icon',
type: 'image/x-icon',
},
- { href: 'https://api.alexandrie-hub.fr', rel: 'preconnect' },
- { href: 'https://cdn.alexandrie-hub.fr', rel: 'preconnect' },
{ href: 'https://embed.diagrams.net', rel: 'preconnect' },
],
meta: [
- // SEO
+ // SEO (url meta tags are defined in App.vue for dynamic URLs)
{
content:
'Alexandrie is a modern note-taking and knowledge base application built for developers and power users. Write, organize and render beautiful notes using extended Markdown in a fast, clean and distraction-free interface. Self-hostable with Docker.',
@@ -69,7 +63,6 @@ export default defineNuxtConfig({
content: 'A modern note-taking and knowledge base app for developers, built around extended Markdown and self-hostable with Docker.',
property: 'og:description',
},
- { content: 'https://alexandrie-hub.fr', property: 'og:url' },
{ content: '/icons/icon-192.png', property: 'og:image' },
// Twitter Card
@@ -84,16 +77,34 @@ export default defineNuxtConfig({
],
title: 'Alexandrie',
viewport: 'width=device-width, initial-scale=1',
+
+ style: [
+ {
+ id: 'dynamic-theme-vars',
+ innerHTML: `
+ :root {
+ --primary: var(--accent);
+ --primary-dark: var(--accent-dark);
+ --primary-bg: var(--accent-bg);
+ --primary-border: var(--accent-border);
+ }
+ `,
+ },
+ ],
},
},
/**
************************ General ************************
*/
- ssr: false,
+ ssr: true,
compatibilityDate: '2024-07-19',
devtools: { enabled: process.env.NODE_ENV !== 'production' },
spaLoadingTemplate: './splash-screen.html',
+ routeRules: {
+ '/dashboard/**': { ssr: false },
+ '/dashboard': { ssr: false },
+ },
/**
************************ Imports & modules ************************
*/
@@ -302,6 +313,11 @@ export default defineNuxtConfig({
},
},
},
+ define: {
+ __BASE_URL__: JSON.stringify(import.meta.env.NUXT_PUBLIC_BASE_URL || ''),
+ __BASE_CDN__: JSON.stringify(import.meta.env.NUXT_PUBLIC_BASE_CDN || ''),
+ __BASE_API__: JSON.stringify(import.meta.env.NUXT_PUBLIC_BASE_API || ''),
+ },
plugins: [
createSvgIconsPlugin({
iconDirs: [resolve(process.cwd(), 'public/app-icons/')],
diff --git a/frontend/public/app-icons/no_synced.svg b/frontend/public/app-icons/no_synced.svg
new file mode 100644
index 00000000..cc65fd0f
--- /dev/null
+++ b/frontend/public/app-icons/no_synced.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M792-56 643-205q-19 11-39.5 20T560-170v-84q6-2 12-4.5t12-5.5L264-584q-11 25-17.5 51.5T240-478q0 45 17 87.5t53 78.5l10 10v-98h80v240H160v-80h110l-16-14q-49-49-71.5-106.5T160-478q0-45 11.5-86.5T205-643L56-792l57-57 736 736-57 57Zm-35-263-60-60q11-24 17-50t6-53q0-45-17-87.5T650-648l-10-10v98h-80v-240h240v80H690l16 14q49 49 71.5 106.5T800-482q0 45-11.5 85.5T757-319ZM379-697l-60-60q19-11 39-19t42-14v84q-5 2-10.5 4t-10.5 5Z"/></svg>
\ No newline at end of file
diff --git a/frontend/vite-env.d.ts b/frontend/vite-env.d.ts
new file mode 100644
index 00000000..e77deac4
--- /dev/null
+++ b/frontend/vite-env.d.ts
@@ -0,0 +1,3 @@
+declare const __BASE_URL__: string;
+declare const __BASE_CDN__: string;
+declare const __BASE_API__: string;