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: drawio support (#484)

Smauge431e6670ce3
diff --git a/backend/controllers/resources.controller.go b/backend/controllers/resources.controller.go
index 3c8f1e45..5566be6d 100644
--- a/backend/controllers/resources.controller.go
+++ b/backend/controllers/resources.controller.go
@@ -4,6 +4,7 @@ import (
"alexandrie/app"
"alexandrie/types"
"alexandrie/utils"
+ "encoding/json"
"errors"
"io"
"net/http"
@@ -14,6 +15,7 @@ import (
type ResourceController interface {
UploadFile(c *gin.Context) (int, any)
UploadAvatar(c *gin.Context) (int, any)
+ UpdateFile(c *gin.Context) (int, any)
}
func NewResourceController(app *app.App) ResourceController {
@@ -34,16 +36,27 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
c.Request.Body,
int64(ctr.app.Config.Cdn.MaxSize),
)
+
file, header, err := c.Request.FormFile("file")
if err != nil {
return http.StatusBadRequest, errors.New("file too large or failed to get file")
}
- parentIdStr := c.Request.FormValue("parent_id")
+ parentIdStr := c.Request.FormValue("parent_id")
var parentId *types.Snowflake = nil
if parentIdStr != "" {
parentId, err = types.SnowflakeFromString(parentIdStr)
}
+
+ metadataStr := c.Request.FormValue("metadata")
+ var metadata types.JSONB
+ if metadataStr != "" {
+ err = json.Unmarshal([]byte(metadataStr), &metadata)
+ if err != nil {
+ return http.StatusBadRequest, errors.New("invalid metadata format")
+ }
+ }
+
defer file.Close()
fileContent, err := io.ReadAll(file)
@@ -61,6 +74,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
header.Filename,
header.Size,
fileContent,
+ metadata,
mimeType,
parentId,
)
@@ -113,3 +127,74 @@ func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {
return http.StatusOK, "Avatar uploaded successfully"
}
+
+// UpdateFile handles file update for an existing resource
+// @Method PUT
+// @Description Update an existing file in the CDN and associated node.
+// @Router /resources/:id [put]
+func (ctr *Controller) UpdateFile(c *gin.Context) (int, any) {
+ resourceId := c.Param("id")
+ id, err := types.SnowflakeFromString(resourceId)
+ if err != nil {
+ return http.StatusBadRequest, errors.New("invalid resource id")
+ }
+
+ actor, err := actorFromRequest(c)
+ if err != nil {
+ return statusFromAccessError(err), err
+ }
+
+ // Limit request body size
+ c.Request.Body = http.MaxBytesReader(
+ c.Writer,
+ c.Request.Body,
+ int64(ctr.app.Config.Cdn.MaxSize),
+ )
+
+ file, header, err := c.Request.FormFile("file")
+ if err != nil {
+ // If no file is provided, user might be updating only metadata
+ file = nil
+ }
+
+ var fileContent []byte
+ var fileSize int64
+ if file != nil {
+ defer file.Close()
+ fileContent, err = io.ReadAll(file)
+ if err != nil {
+ return http.StatusInternalServerError, errors.New("failed to read file")
+ }
+ fileSize = int64(len(fileContent))
+ }
+
+ metadataStr := c.PostForm("metadata")
+ var metadata types.JSONB
+ if metadataStr != "" {
+ err = json.Unmarshal([]byte(metadataStr), &metadata)
+ if err != nil {
+ return http.StatusBadRequest, errors.New("invalid metadata format")
+ }
+ }
+
+ mimeType := ""
+ if file != nil {
+ mimeType = header.Header.Get("Content-Type")
+ }
+
+ node, err := ctr.app.Services.Resource.UpdateFile(
+ c.Request.Context(),
+ actor,
+ *id,
+ header.Filename,
+ fileContent,
+ fileSize,
+ metadata,
+ mimeType,
+ )
+ if err != nil {
+ return statusFromAccessError(err), err
+ }
+
+ return http.StatusOK, node
+}
diff --git a/backend/repositories/node.repository.go b/backend/repositories/node.repository.go
index cf80199f..d7b004d0 100644
--- a/backend/repositories/node.repository.go
+++ b/backend/repositories/node.repository.go
@@ -353,11 +353,11 @@ func (r *NodeRepositoryImpl) Update(node *models.Node) error {
UPDATE nodes
SET parent_id = ?, user_id = ?, name = ?, description = ?, tags = ?, role = ?, color = ?,
icon = ?, thumbnail = ?, theme = ?, accessibility = ?, access = ?, display = ?, `+"`order`"+` = ?,
- content = ?, content_compiled = ?, metadata = ?, updated_timestamp = ?
+ content = ?, content_compiled = ?, size = ?, metadata = ?, updated_timestamp = ?
WHERE id = ?`,
node.ParentId, node.UserId, node.Name, node.Description, node.Tags, node.Role, node.Color,
node.Icon, node.Thumbnail, node.Theme, node.Accessibility, node.Access, node.Display, node.Order,
- node.Content, node.ContentCompiled, node.Metadata, node.UpdatedTimestamp, node.Id)
+ node.Content, node.ContentCompiled, node.Size, node.Metadata, node.UpdatedTimestamp, node.Id)
if err != nil {
return fmt.Errorf("failed to update node: %w", err)
}
diff --git a/backend/router/routes/ressources.go b/backend/router/routes/ressources.go
index 4261db8f..87d1b75c 100644
--- a/backend/router/routes/ressources.go
+++ b/backend/router/routes/ressources.go
@@ -16,6 +16,7 @@ func Uploads(app *app.App, router *gin.RouterGroup) {
resources.Use(middlewares.Auth())
resources.POST("", utils.WP(resourcesCtrl.UploadFile))
resources.POST("/avatar", utils.WP(resourcesCtrl.UploadAvatar))
+ resources.PUT("/:id", utils.WP(resourcesCtrl.UpdateFile))
}
func Backup(app *app.App, router *gin.RouterGroup) {
diff --git a/backend/services/resource.service.go b/backend/services/resource.service.go
index e83235ae..a476c7bc 100644
--- a/backend/services/resource.service.go
+++ b/backend/services/resource.service.go
@@ -11,6 +11,7 @@ import (
"context"
"errors"
"fmt"
+ "maps"
"os"
"path/filepath"
"slices"
@@ -26,8 +27,9 @@ type ResourceConfig struct {
}
type ResourceService interface {
- UploadFile(ctx context.Context, filename string, fileSize int64, fileContent []byte, mimeType string, parentId *types.Snowflake) (*models.Node, error)
+ UploadFile(ctx context.Context, filename string, fileSize int64, fileContent []byte, metadata types.JSONB, mimeType string, parentId *types.Snowflake) (*models.Node, error)
UploadAvatar(filename string, fileSize int64, fileContent []byte, mimeType string, userId types.Snowflake) error
+ UpdateFile(ctx context.Context, actor permissions.Actor, nodeId types.Snowflake, name string, fileContent []byte, fileSize int64, metadata types.JSONB, mimeType string) (*models.Node, error)
}
type resourceService struct {
@@ -48,7 +50,7 @@ func NewResourceService(nodeRepo repositories.NodeRepository, snowflake *snowfla
}
}
-func (s *resourceService) UploadFile(ctx context.Context, filename string, fileSize int64, fileContent []byte, mimeType string, parentId *types.Snowflake) (*models.Node, error) {
+func (s *resourceService) UploadFile(ctx context.Context, filename string, fileSize int64, fileContent []byte, metadata types.JSONB, mimeType string, parentId *types.Snowflake) (*models.Node, error) {
actor, err := actorFromContext(ctx)
if err != nil {
return nil, err
@@ -74,11 +76,12 @@ func (s *resourceService) UploadFile(ctx context.Context, filename string, fileS
id := s.snowflake.Generate()
ext := filepath.Ext(filename)
transformedPath := fmt.Sprintf("%d%s", id, ext)
- metadata := types.JSONB{
+ metadata_final := types.JSONB{
"filetype": mimeType,
"original_path": filename,
"transformed_path": transformedPath,
}
+ maps.Copy(metadata_final, metadata)
name := filename
if len(name) > 50 {
@@ -112,7 +115,7 @@ func (s *resourceService) UploadFile(ctx context.Context, filename string, fileS
Size: &fileSize,
Content: &filename,
ContentCompiled: &transformedPath,
- Metadata: &metadata,
+ Metadata: &metadata_final,
CreatedTimestamp: time.Now().UnixMilli(),
UpdatedTimestamp: time.Now().UnixMilli(),
}
@@ -143,3 +146,77 @@ func (s *resourceService) UploadAvatar(filename string, fileSize int64, fileCont
_, err := s.minioClient.PutObject(context.Background(), os.Getenv("MINIO_BUCKET"), objectName, bytes.NewReader(fileContent), fileSize, minio.PutObjectOptions{ContentType: mimeType})
return err
}
+
+// UpdateFile updates an existing file and its associated node
+func (s *resourceService) UpdateFile(ctx context.Context, actor permissions.Actor, nodeId types.Snowflake, name string, fileContent []byte, fileSize int64, metadata types.JSONB, mimeType string) (*models.Node, error) {
+ if s.minioClient == nil {
+ return nil, errors.New("minio client not initialized")
+ }
+
+ // Get the existing node
+ node, err := s.nodeRepo.GetByID(nodeId)
+ if err != nil {
+ return nil, errors.New("resource not found")
+ }
+
+ // Check permissions - user must have update access
+ level, err := s.access.CheckNodeAction(actor, node, permissions.ActionUpdate)
+ if err != nil || level == permissions.PermNone {
+ return nil, errors.New("insufficient permissions to update this resource")
+ }
+
+ // Update file if a new one is provided
+ if len(fileContent) > 0 && mimeType != "" {
+ // Validate file type
+ if !slices.Contains(s.config.SupportedTypes, mimeType) {
+ return nil, errors.New("file type not supported")
+ }
+
+ // Check if new file size + other uploads would exceed limit
+ currentSize := int64(0)
+ if node.Size != nil {
+ currentSize = *node.Size
+ }
+ totalSize, err := s.nodeRepo.GetUserUploadsSize(actor.UserID)
+ if err != nil {
+ return nil, err
+ }
+ // Calculate the increase in size (new file - old file)
+ sizeIncrease := fileSize - currentSize
+ if totalSize+sizeIncrease > int64(s.config.MaxUploadsSize) {
+ return nil, errors.New("total size of uploads exceeds the limit")
+ }
+
+ // Update the file in MinIO
+ objectName := fmt.Sprintf("%d/%s", actor.UserID, *node.ContentCompiled)
+ _, err = s.minioClient.PutObject(context.Background(), os.Getenv("MINIO_BUCKET"), objectName, bytes.NewReader(fileContent), fileSize, minio.PutObjectOptions{ContentType: mimeType})
+ if err != nil {
+ return nil, errors.New("failed to update file in storage")
+ }
+
+ // Update file-related node fields
+ node.Size = &fileSize
+ if node.Metadata == nil {
+ node.Metadata = &types.JSONB{}
+ }
+ (*node.Metadata)["filetype"] = mimeType
+ }
+
+ // Update node properties if provided
+ if name != "" {
+ if len(name) > 50 {
+ name = name[:50]
+ }
+ node.Name = name
+ }
+
+ // Update timestamp
+ node.UpdatedTimestamp = time.Now().UnixMilli()
+
+ // Save the updated node
+ if err := s.nodeRepo.Update(node); err != nil {
+ return nil, errors.New("failed to update resource in database")
+ }
+
+ return node, nil
+}
diff --git a/backend/utils/escape-html.go b/backend/utils/escape-html.go
index 761bcdf4..35cdb3bb 100644
--- a/backend/utils/escape-html.go
+++ b/backend/utils/escape-html.go
@@ -86,7 +86,7 @@ func InitBluemonday() {
policy.RequireNoFollowOnLinks(false)
// Images videos audio
- policy.AllowAttrs("src", "alt", "title", "width", "height").OnElements("img")
+ policy.AllowAttrs("src", "alt", "title", "width", "height", "data").OnElements("img", "object")
policy.AllowAttrs("src", "controls", "alt").OnElements("audio", "video")
// Iframe (use with caution)
diff --git a/frontend/app/components/MarkdownEditor/DrawioSidebar.vue b/frontend/app/components/MarkdownEditor/DrawioSidebar.vue
new file mode 100644
index 00000000..450c44e5
--- /dev/null
+++ b/frontend/app/components/MarkdownEditor/DrawioSidebar.vue
@@ -0,0 +1,75 @@
+<template>
+ <div v-if="diagrams.length" class="drawio-sidebar">
+ <div class="sidebar-header">
+ <div class="header-title">
+ <Icon name="image" display="sm" />
+ <span>{{ t('markdown.drawio.linked') }}</span>
+ <span class="badge">{{ diagrams.length }}</span>
+ </div>
+ </div>
+
+ <div class="diagrams-list">
+ <NodeResourceInline v-for="diagram in diagrams" :key="diagram.id" :node="diagram" />
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import type { Node } from '~/stores';
+
+const { t } = useI18nT();
+
+defineProps<{ diagrams: Node[] }>();
+</script>
+
+<style scoped lang="scss">
+.drawio-sidebar {
+ display: flex;
+ padding: 12px;
+ border-top: 1px solid var(--border);
+ background: var(--surface-base);
+ flex-direction: column;
+ gap: 12px;
+ max-height: 45%;
+ overflow-y: auto;
+ overflow-x: hidden;
+}
+
+.sidebar-header {
+ display: flex;
+ align-items: center;
+ padding-bottom: 8px;
+ border-bottom: 1px solid var(--border);
+}
+
+.header-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--text-secondary);
+ text-transform: uppercase;
+ letter-spacing: 0.5px;
+}
+
+.badge {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ margin-left: auto;
+ background: var(--primary-bg);
+ border-radius: 50%;
+ font-size: 11px;
+ font-weight: 700;
+ color: var(--primary);
+}
+
+.diagrams-list {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+}
+</style>
diff --git a/frontend/app/components/MarkdownEditor/EditorAppHeader.vue b/frontend/app/components/MarkdownEditor/EditorAppHeader.vue
index 754473c7..fdedcf43 100644
--- a/frontend/app/components/MarkdownEditor/EditorAppHeader.vue
+++ b/frontend/app/components/MarkdownEditor/EditorAppHeader.vue
@@ -4,18 +4,21 @@
<Icon :name="icon" display="xxl" fill="var(--surface-base)" />
</div>
<h3>{{ title }}</h3>
- <p class="header-subtitle">{{ subtitle }}</p>
+ <p v-if="subtitle" class="header-subtitle">{{ subtitle }}</p>
+ <div class="floating-toolbar">
+ <slot name="toolbar" />
+ </div>
</div>
</template>
<script setup lang="ts">
-defineProps<{ icon: string; title: string; subtitle: string }>();
+defineProps<{ icon: string; title: string; subtitle?: string }>();
</script>
<style scoped lang="scss">
.modal-header {
display: flex;
- padding: 24px 0 20px;
+ padding: 16px 0 0;
text-align: center;
align-items: center;
flex-direction: column;
@@ -53,4 +56,12 @@ defineProps<{ icon: string; title: string; subtitle: string }>();
color: var(--text-secondary);
}
}
+
+.floating-toolbar {
+ position: absolute;
+ top: 1.3rem;
+ right: 50px;
+ display: flex;
+ gap: 8px;
+}
</style>
diff --git a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue b/frontend/app/components/MarkdownEditor/MarkdownEditor.vue
index 3f2b2832..4d5a03ef 100644
--- a/frontend/app/components/MarkdownEditor/MarkdownEditor.vue
+++ b/frontend/app/components/MarkdownEditor/MarkdownEditor.vue
@@ -3,7 +3,7 @@
<div class="editor-wrapper">
<div class="editor-container">
<!-- Toolbar Section -->
- <Toolbar v-model="document" @execute-action="commands.exec" />
+ <Toolbar v-model="document" @execute-action="handleToolbarAction" />
<!-- Compact Document Metadata -->
<div class="document-meta">
@@ -30,6 +30,7 @@
<span class="panel-label">{{ t('common.actions.preview') }}</span>
</div>
<NodeDocumentContentCompiled ref="markdownPreviewComponent" :node="document" />
+ <DrawioSidebar :diagrams="referencedDrawioResources" />
</div>
</div>
</div>
@@ -45,14 +46,16 @@ import { createUploadsHandlers } from './modules/editorUploads';
import { createSnippetSource } from './modules/editorUtils';
import { createCommands } from './modules/editorCommands';
import { createScrollSync } from './modules/scrollSync';
+import compile from '~/helpers/markdown';
import Toolbar from './Toolbar.vue';
+import DrawioSidebar from './DrawioSidebar.vue';
import NodeDocumentContentCompiled from '~/components/Node/Document/ContentCompiled.vue';
-import compile from '~/helpers/markdown';
import type { Node } from '~/stores';
const { t } = useI18nT();
const resourcesStore = useResourcesStore();
+const nodesStore = useNodesStore();
const preferences = usePreferencesStore();
const props = defineProps<{ doc?: Partial<Node> }>();
@@ -90,6 +93,16 @@ const uploadsHandlers = createUploadsHandlers({
insertText: (t: string) => commands.exec('insertText', t),
});
+const referencedDrawioResources = computed(() => {
+ const diagrams: Node[] = [];
+ nodesStore.resources.forEach((resource: Node) => {
+ if (!resource.metadata?.drawio) return;
+ diagrams.push(resource);
+ });
+
+ return diagrams;
+});
+
const state = createEditorState({
initialDoc: document.value.content || '',
spellCheck: preferences.get('editorSpellCheck'),
@@ -138,6 +151,9 @@ function handleGlobalKeys(e: KeyboardEvent) {
}
}
+function handleToolbarAction(action: string, payload?: string) {
+ commands.exec(action, payload);
+}
// Re-sync scroll after the preview DOM updates (e.g. after typing new content)
watch(
() => document.value.content_compiled,
diff --git a/frontend/app/components/MarkdownEditor/Toolbar.vue b/frontend/app/components/MarkdownEditor/Toolbar.vue
index bb83a307..1eda0692 100644
--- a/frontend/app/components/MarkdownEditor/Toolbar.vue
+++ b/frontend/app/components/MarkdownEditor/Toolbar.vue
@@ -163,8 +163,8 @@ const localValue = computed({
const emitAction = (action: string) => emit('execute-action', action);
-const openHelp = () => useModal().add(new Modal(shallowRef(ModalSyntax), { size: 'large' }));
-const openSettings = () => useModal().add(new Modal(shallowRef(EditorPreferences), { size: 'medium' }));
+const openHelp = () => useModal().add(new Modal(shallowRef(ModalSyntax), { size: 'medium' }));
+const openSettings = () => useModal().add(new Modal(shallowRef(EditorPreferences), { size: 'small' }));
const nodesTree = useNodesTree();
const categories = nodesTree.treeUpToRole(2);
@@ -194,6 +194,7 @@ const extendedFormattingTools = computed<ToolItem[]>(() => [
const insertTools = computed<ToolItem[]>(() => [
{ name: t('markdown.toolbar.link'), icon: 'format/link', action: 'link', shortcut: 'Ctrl+K' },
{ name: t('markdown.toolbar.image'), icon: 'format/image', action: 'image', shortcut: 'Ctrl+Shift+I' },
+ { name: t('markdown.toolbar.diagram'), icon: 'format/diagrams', action: 'diagram' },
{ name: t('markdown.toolbar.inlineCode'), icon: 'format/code', action: 'code', shortcut: 'Ctrl+E' },
{ name: t('markdown.toolbar.codeBlock'), icon: 'format/code-block', action: 'codeBlock', shortcut: 'Ctrl+Shift+C' },
{ name: t('markdown.toolbar.color'), icon: 'format/color', action: 'openColorPicker' },
diff --git a/frontend/app/components/MarkdownEditor/modules/editorCommands.ts b/frontend/app/components/MarkdownEditor/modules/editorCommands.ts
index 3bd9d251..ea3670e3 100644
--- a/frontend/app/components/MarkdownEditor/modules/editorCommands.ts
+++ b/frontend/app/components/MarkdownEditor/modules/editorCommands.ts
@@ -1,6 +1,7 @@
import ImageSelectorModal from '../ImageSelectorModal.vue';
import GridOrganizationModal from '../GridOrganizationModal.vue';
import ColorPickerModal from '../ColorPickerModal.vue';
+import DrawioEditorModal from '~/components/Node/Modals/DrawioEditor.vue';
import type { EditorView } from '@codemirror/view';
import type { Node } from '~/stores';
@@ -509,8 +510,9 @@ export function createCommands(params: CreateCommandsParams) {
view.focus();
}
+ const modalManager = useModal();
+
function openColorModal() {
- const modalManager = useModal();
modalManager.add(new Modal(shallowRef(ColorPickerModal), { props: { onColorSelect: handleColorSelect } }));
}
@@ -519,15 +521,25 @@ export function createCommands(params: CreateCommandsParams) {
}
function openImageSelector() {
- const modalManager = useModal();
- modalManager.add(new Modal(shallowRef(ImageSelectorModal), { props: { onImageSelect: handleImageSelect, nodeId: params.getDoc()?.id }, size: 'large' }));
+ modalManager.add(new Modal(shallowRef(ImageSelectorModal), { props: { onImageSelect: handleImageSelect, nodeId: params.getDoc()?.id }, size: 'medium' }));
}
function openGridOrganization() {
- const modalManager = useModal();
modalManager.add(new Modal(shallowRef(GridOrganizationModal), { props: { onGridSelect: handleGridSelect } }));
}
+ function openDrawioEditor() {
+ const modal = new Modal(shallowRef(DrawioEditorModal), {
+ props: {
+ insertText: (t: string) => insertText(t),
+ parentNode: params.getDoc(),
+ },
+ size: 'large',
+ noPadding: true,
+ });
+ modalManager.add(modal);
+ }
+
function handleImageSelect(imageUrl: string, altText: string) {
const view = params.getView();
if (!view) return;
@@ -566,6 +578,7 @@ export function createCommands(params: CreateCommandsParams) {
}
if (action === 'image') return openImageSelector();
if (action === 'gridOrganization') return openGridOrganization();
+ if (action === 'diagram') return openDrawioEditor();
if (action === 'insertText') return insertText(payload || '');
const view = params.getView();
diff --git a/frontend/app/components/ModalManager.vue b/frontend/app/components/ModalManager.vue
index 60876c75..0cf85972 100644
--- a/frontend/app/components/ModalManager.vue
+++ b/frontend/app/components/ModalManager.vue
@@ -63,7 +63,27 @@ onUnmounted(() => document.removeEventListener('keydown', handleKeydown));
-webkit-backdrop-filter: var(--backdrop-blur) var(--backdrop-saturate);
}
+.modal-container:has(> .full) {
+ max-width: calc(100vw - 32px);
+ max-height: calc(100vh - 20px);
+ width: 100%;
+ height: 100%;
+ .modal {
+ max-height: none;
+ }
+}
+
.modal-container:has(> .large) {
+ max-width: 95vw;
+ max-height: 90vh;
+ width: 100%;
+ height: 100%;
+ .modal {
+ max-height: none;
+ }
+}
+
+.modal-container:has(> .medium) {
max-width: 1115px;
}
diff --git a/frontend/app/components/Node/Document/ContentCompiled.vue b/frontend/app/components/Node/Document/ContentCompiled.vue
index a7f114e2..6b450109 100644
--- a/frontend/app/components/Node/Document/ContentCompiled.vue
+++ b/frontend/app/components/Node/Document/ContentCompiled.vue
@@ -10,6 +10,8 @@
<script setup lang="ts">
import type { Node } from '~/stores';
+import { subscribeDrawioCacheInvalidated } from '~/composables/useDrawioCache';
+import { rerenderImages } from '~/helpers/DOM';
const props = defineProps<{ node?: Partial<Node> }>();
@@ -26,6 +28,15 @@ const documentLineHeight = preferences.get('documentLineHeight');
const rootElement = ref<HTMLElement>();
defineExpose({ rootElement });
+
+onMounted(() => {
+ const unsub = subscribeDrawioCacheInvalidated(() => {
+ rerenderImages(rootElement.value!);
+ });
+ onUnmounted(() => {
+ unsub();
+ });
+});
</script>
<style lang="scss" scoped>
diff --git a/frontend/app/components/Node/Modals/DrawioEditor.vue b/frontend/app/components/Node/Modals/DrawioEditor.vue
new file mode 100644
index 00000000..b6b6a8fe
--- /dev/null
+++ b/frontend/app/components/Node/Modals/DrawioEditor.vue
@@ -0,0 +1,154 @@
+<template>
+ <div class="drawio-editor-modal">
+ <EditorAppHeader icon="image" :title="t('markdown.drawio.title')">
+ <template #toolbar>
+ <div class="btn-icon" :class="{ disabled: !isReady }" @click="requestSaveDiagram">
+ <Icon name="save" display="lg" />
+ </div>
+ <div class="btn-icon" :class="{ disabled: !isReady }" @click="toggleFullScreen">
+ <Icon name="fullsreen" display="lg" />
+ </div>
+ <div class="btn-icon" :class="{ disabled: !isReady }" @click="openDeleteModal">
+ <Icon name="delete" display="lg" />
+ </div>
+ </template>
+ </EditorAppHeader>
+
+ <div class="drawio-content">
+ <iframe :key="iframeKey" ref="iframe" class="drawio-iframe" :src="iframeUrl" />
+
+ <div v-if="!isReady" class="loading-overlay">
+ <LoaderSpinner />
+ <p>{{ t('common.status.loading') }}</p>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import EditorAppHeader from '~/components/MarkdownEditor/EditorAppHeader.vue';
+import NodeDeleteModal from '~/components/Node/Modals/Delete.vue';
+
+import type { Node } from '~/stores';
+
+const { t } = useI18nT();
+
+interface Props {
+ modalRef: Modal;
+ parentNode?: Node;
+ node?: Node;
+ insertText?: (text: string) => void;
+}
+
+const props = withDefaults(defineProps<Props>(), {
+ node: undefined,
+ parentNode: undefined,
+ insertText: undefined,
+});
+
+const emit = defineEmits<{ (e: 'close'): void }>();
+
+const iframe = ref<HTMLIFrameElement | null>(null);
+const iframeKey = ref(0);
+
+const iframeUrl = 'https://embed.diagrams.net/?embed=1&ui=min&spin=1&proto=json';
+
+const { handleMessage, isReady } = useDrawioIframe(iframe, props.node, props.parentNode, props.insertText);
+
+function requestSaveDiagram() {
+ if (!isReady.value) return;
+ postMessageToIframe({
+ action: 'export',
+ format: 'xmlsvg',
+ xml: true,
+ });
+}
+
+function postMessageToIframe(msg: object) {
+ if (!iframe.value?.contentWindow) return;
+ iframe.value.contentWindow.postMessage(JSON.stringify(msg), '*');
+}
+const toggleFullScreen = () => {
+ if (!props.modalRef) return;
+ // eslint-disable-next-line vue/no-mutating-props
+ props.modalRef.options.size = props.modalRef.options.size === 'full' ? 'large' : 'full';
+};
+
+const openDeleteModal = () => {
+ if (!props.node) return;
+
+ useModal().add(
+ new Modal(shallowRef(NodeDeleteModal), {
+ props: {
+ node: props.node,
+ },
+ onClose: () => emit('close'),
+ size: 'small',
+ }),
+ );
+};
+
+const exitHandleMessage = async (e: MessageEvent) => {
+ const result = await handleMessage(e);
+ if (result) emit('close');
+};
+
+onMounted(() => window.addEventListener('message', exitHandleMessage));
+
+onBeforeUnmount(() => window.removeEventListener('message', exitHandleMessage));
+</script>
+
+<style scoped lang="scss">
+.drawio-editor-modal {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ gap: 12px;
+}
+
+.drawio-content {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ border-radius: var(--radius-md);
+ overflow: hidden;
+ background: var(--surface-base);
+ border: 1px solid var(--border);
+}
+
+.drawio-iframe {
+ width: 100%;
+ height: 100%;
+ border: none;
+ background: var(--surface-base);
+}
+
+.loading-overlay {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ background: var(--surface-base);
+ z-index: 10;
+
+ p {
+ color: var(--text-secondary);
+ font-size: 14px;
+ }
+}
+
+@media (width <= 900px) {
+ .drawio-editor-modal {
+ height: 60vh;
+ }
+}
+
+@media (width <= 600px) {
+ .drawio-editor-modal {
+ height: 50vh;
+ }
+}
+</style>
diff --git a/frontend/app/components/Node/Resource/Inline.vue b/frontend/app/components/Node/Resource/Inline.vue
index e4b782fe..9566c8f2 100644
--- a/frontend/app/components/Node/Resource/Inline.vue
+++ b/frontend/app/components/Node/Resource/Inline.vue
@@ -6,18 +6,48 @@
<span class="file-name">{{ node.name }}</span>
<span class="file-size">{{ readableFileSize(node.size ?? 0) }}</span>
</div>
+
+ <button v-if="editable" class="btn-icon file-edit" @click="openDrawioEditor">
+ <Icon name="edit" />
+ </button>
+ <button class="btn-icon file-remove" @click="openDeleteModal">
+ <Icon name="close" />
+ </button>
</NuxtLink>
</template>
<script setup lang="ts">
+import NodeDeleteModal from '../Modals/Delete.vue';
+import DrawioEditorModal from '../Modals/DrawioEditor.vue';
import { isImageFile, readableFileSize, resolveFileIcon, resolvePreviewUrl } from '~/helpers/resources';
import type { Node } from '~/stores';
-const props = defineProps<{ node: Node }>();
+const props = defineProps<{
+ node: Node;
+}>();
+
+const editable = computed(() => props.node.metadata?.drawio);
const preview = ref<string | null>(null);
if (isImageFile(props.node.metadata?.filetype)) preview.value = resolvePreviewUrl(props.node);
+
+const openDeleteModal = () => {
+ useModal().add(new Modal(shallowRef(NodeDeleteModal), { size: 'small', props: { node: props.node, redirect: '/dashboard' } }));
+};
+
+function openDrawioEditor(e: MouseEvent) {
+ e.preventDefault();
+ const modalManager = useModal();
+ const modal = new Modal(shallowRef(DrawioEditorModal), {
+ props: {
+ node: props.node,
+ },
+ size: 'large',
+ noPadding: true,
+ });
+ modalManager.add(modal);
+}
</script>
<style scoped lang="scss">
diff --git a/frontend/app/components/Sidebar/Dock.vue b/frontend/app/components/Sidebar/Dock.vue
index 5cb9981a..6cd7cb24 100644
--- a/frontend/app/components/Sidebar/Dock.vue
+++ b/frontend/app/components/Sidebar/Dock.vue
@@ -16,6 +16,9 @@
<NuxtLink to="/dashboard/import">
<Icon name="import" display="lg" />
</NuxtLink>
+ <NuxtLink to="/dashboard/cdn/diagram">
+ <Icon name="format/diagrams" display="lg" />
+ </NuxtLink>
<NuxtLink v-if="userStore.user?.role === 2" to="/dashboard/admin">
<Icon name="users" display="lg" />
</NuxtLink>
@@ -36,7 +39,7 @@ import SettingsModal from '~/pages/dashboard/settings/index.vue';
const userStore = useUserStore();
const openSettings = () => {
- useModal().add(new Modal(shallowRef(SettingsModal), { props: { isModal: true }, size: 'large', noPadding: true }));
+ useModal().add(new Modal(shallowRef(SettingsModal), { props: { isModal: true }, size: 'medium', noPadding: true }));
};
function closeDock() {
usePreferencesStore().set('view_dock', false);
diff --git a/frontend/app/components/Sidebar/helpers.ts b/frontend/app/components/Sidebar/helpers.ts
index 85dd2b9d..f28a8935 100644
--- a/frontend/app/components/Sidebar/helpers.ts
+++ b/frontend/app/components/Sidebar/helpers.ts
@@ -108,7 +108,7 @@ export const navigationItems = (sidebarItemsPrefs?: Preferences['sidebarItems'])
label: 'components.sidebar.nav.settings',
onClick: () => {
if (isMobile.value) useRouter().push('/dashboard/settings');
- else useModal().add(new Modal(shallowRef(SettingsModal), { noPadding: true, props: { isModal: true }, size: 'large' }));
+ else useModal().add(new Modal(shallowRef(SettingsModal), { noPadding: true, props: { isModal: true }, size: 'medium' }));
},
parent_id: '',
route: '',
diff --git a/frontend/app/composables/useDrawioCache.ts b/frontend/app/composables/useDrawioCache.ts
new file mode 100644
index 00000000..714edd22
--- /dev/null
+++ b/frontend/app/composables/useDrawioCache.ts
@@ -0,0 +1,22 @@
+// Simple event bus for drawio cache invalidation
+type Listener = (payload?: unknown) => void;
+
+const listeners = new Set<Listener>();
+
+export function subscribeDrawioCacheInvalidated(fn: Listener) {
+ listeners.add(fn);
+ return () => listeners.delete(fn);
+}
+
+export function notifyDrawioCacheInvalidated(payload?: unknown) {
+ listeners.forEach(fn => {
+ try {
+ fn(payload);
+ } catch (e) {
+ console.error('[useDrawioCache] listener error', e);
+ }
+ });
+}
+
+// Backwards-compatible alias
+export const onDrawioCacheInvalidated = subscribeDrawioCacheInvalidated;
diff --git a/frontend/app/composables/useDrawioIframe.ts b/frontend/app/composables/useDrawioIframe.ts
new file mode 100644
index 00000000..e92e8063
--- /dev/null
+++ b/frontend/app/composables/useDrawioIframe.ts
@@ -0,0 +1,151 @@
+import { normalizeDrawioSvg, extractMxfileFromSvg, buildDrawioFilename } from '~/helpers/drawio';
+import type { Node } from '~/stores';
+import { notifyDrawioCacheInvalidated } from '~/composables/useDrawioCache';
+
+export function useDrawioIframe(iframe: Ref<HTMLIFrameElement | null>, node?: Node, parentNode?: Node, insertText: (text: string) => void = () => {}) {
+ const isReady = ref(false);
+ const { resourceURL } = useApi();
+ const notifications = useNotifications();
+ const resourcesStore = useResourcesStore();
+ const mode = useColorMode();
+
+ async function loadDiagram() {
+ postMessageToIframe({
+ action: 'load',
+ autosave: 1,
+ xml: await loadDiagramXml(),
+ noSaveBtn: true,
+ noExitBtn: true,
+ saveAndExit: false,
+ dark: mode.value === 'dark',
+ });
+ }
+
+ function postMessageToIframe(msg: object) {
+ if (!iframe.value?.contentWindow) return;
+ iframe.value.contentWindow.postMessage(JSON.stringify(msg), '*');
+ }
+
+ async function loadDiagramXml(): Promise<string> {
+ try {
+ const url = resourceURL(node);
+ if (!url || !node) return '';
+ const response = await fetch(url, { credentials: 'include' });
+
+ if (!response.ok) {
+ console.error(`Failed to fetch diagram: ${response.status} ${response.statusText}`);
+ throw new Error(`HTTP ${response.status}`);
+ }
+
+ const contentType = response.headers.get('content-type');
+ if (!contentType?.includes('svg')) {
+ console.warn(`Expected SVG but got Content-Type: ${contentType}`);
+ }
+
+ const svg = normalizeDrawioSvg(await response.text());
+
+ if (!svg.trim().startsWith('<')) {
+ console.error('Response does not appear to be SVG:', svg.substring(0, 100));
+ throw new Error('Invalid SVG format received');
+ }
+
+ const xml = extractMxfileFromSvg(svg);
+ if (!xml) {
+ console.warn('No mxfile XML found in SVG, diagram will open blank');
+ return '';
+ }
+
+ return xml;
+ } catch (error) {
+ console.error('Error loading diagram:', error);
+ notifications.add({ title: 'Warning', message: 'Unable to load the existing diagram. A new diagram will be opened.', type: 'warning' });
+ return '';
+ }
+ }
+
+ async function saveDiagram(svg: string, diagram_name?: string): Promise<void> {
+ const parentId = parentNode?.id;
+ const isNew = !node;
+
+ try {
+ const filename = diagram_name || node?.name || buildDrawioFilename(parentNode?.name || 'diagram');
+ const svgContent = normalizeDrawioSvg(svg);
+
+ const file = new File([svgContent], filename, { type: 'image/svg+xml' });
+
+ const body = new FormData();
+ if (parentId) body.append('parent_id', parentId);
+ body.append('file', file);
+ body.append('metadata', JSON.stringify({ drawio: true }));
+
+ let savedResource: Node;
+
+ if (node) {
+ savedResource = await resourcesStore.update(node.id, body);
+ } else {
+ savedResource = await resourcesStore.post(body);
+ }
+
+ if (isNew) {
+ insertText(`\n![${savedResource.name}](${resourceURL(savedResource)})\n`);
+ } else {
+ notifyDrawioCacheInvalidated({ id: savedResource.id, resource: savedResource });
+ }
+
+ notifications.add({ title: 'Success', message: 'Diagram saved and linked to this document.', type: 'success' });
+ } catch (error) {
+ console.error('[DrawioIntegration] Error saving diagram:', error);
+ notifications.add({ title: 'Error', message: String(error), type: 'error' });
+ throw error;
+ }
+ }
+
+ async function handleMessage(event: MessageEvent, diagram_name?: string): Promise<boolean> {
+ if (event.source !== iframe.value?.contentWindow) {
+ return false;
+ }
+
+ if (!event.data) {
+ return false;
+ }
+
+ let data: Record<string, unknown>;
+
+ if (typeof event.data === 'object') {
+ data = event.data;
+ } else if (typeof event.data === 'string') {
+ try {
+ data = JSON.parse(event.data);
+ } catch (e) {
+ console.error('[DrawioEditor] Failed to parse message:', e);
+ return false;
+ }
+ } else {
+ console.warn('[DrawioEditor] Unexpected message type:', typeof event.data);
+ return false;
+ }
+
+ if (data.event === 'init') {
+ isReady.value = true;
+ loadDiagram();
+ return false;
+ }
+
+ if (data.event === 'export' && typeof data.data === 'string') {
+ const svg = data.data;
+ //const xml = typeof data.xml === 'string' ? data.xml : extractMxfileFromSvg(svg) || undefined;
+
+ await saveDiagram(svg, diagram_name);
+
+ return true;
+ }
+
+ if (data.event === 'exit') return true;
+ return false;
+ }
+
+ return {
+ handleMessage,
+ isReady: computed(() => isReady.value),
+ };
+}
diff --git a/frontend/app/composables/useModal.ts b/frontend/app/composables/useModal.ts
index 1abcd137..6f88b6dd 100644
--- a/frontend/app/composables/useModal.ts
+++ b/frontend/app/composables/useModal.ts
@@ -8,6 +8,7 @@ const modals = ref<Modal[]>([]);
/** Open a new modal (adds to stack) */
function add(modal: Modal) {
document.body.classList.add('modal-open');
+ modal.options.props = { ...modal.options.props, modalRef: modal };
modals.value.push(modal);
}
@@ -43,15 +44,20 @@ export function useModal() {
}
interface ModalOptions {
- size?: 'small' | 'medium' | 'large';
+ size?: 'small' | 'medium' | 'large' | 'full';
noPadding?: boolean;
props?: object;
+ fullScreen?: boolean;
onClose?: () => void;
}
export class Modal {
+ public options: ModalOptions;
+
constructor(
public component: object,
- public options: ModalOptions = { size: 'medium' },
- ) {}
+ options: ModalOptions = { size: 'medium' },
+ ) {
+ this.options = reactive(options);
+ }
}
diff --git a/frontend/app/helpers/DOM.ts b/frontend/app/helpers/DOM.ts
new file mode 100644
index 00000000..de6c1c85
--- /dev/null
+++ b/frontend/app/helpers/DOM.ts
@@ -0,0 +1,12 @@
+export function rerenderImages(rootElement: HTMLElement) {
+ // Re-triggering image loading by resetting the data attribute (add v=timestamp), to bypass potential caching issues after a drawio diagram update
+ const obj = rootElement?.querySelectorAll('object');
+ obj?.forEach(img => {
+ const data = img.getAttribute('data') || '';
+ const url = new URL(data);
+ url.searchParams.set('v', Date.now().toString());
+ if (data) {
+ img.setAttribute('data', url.toString());
+ }
+ });
+}
diff --git a/frontend/app/helpers/drawio.ts b/frontend/app/helpers/drawio.ts
new file mode 100644
index 00000000..f664ff14
--- /dev/null
+++ b/frontend/app/helpers/drawio.ts
@@ -0,0 +1,94 @@
+export interface DrawioExportPayload {
+ svg: string;
+ xml?: string;
+}
+
+const DRAWIO_SVG_DATA_URI_PREFIX = 'data:image/svg+xml;base64,';
+
+function base64ToUtf8(base64: string): string {
+ const binary = atob(base64);
+ const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
+ return new TextDecoder('utf-8').decode(bytes);
+}
+
+export function normalizeDrawioSvg(svgText: string): string {
+ const trimmed = svgText.trim();
+
+ if (trimmed.startsWith(DRAWIO_SVG_DATA_URI_PREFIX)) {
+ const encoded = trimmed.slice(DRAWIO_SVG_DATA_URI_PREFIX.length);
+ return base64ToUtf8(encoded);
+ }
+
+ if (trimmed.startsWith('data:image/svg+xml,')) {
+ return decodeURIComponent(trimmed.slice('data:image/svg+xml,'.length));
+ }
+
+ return trimmed;
+}
+
+export function extractMxfileFromSvg(svgText: string): string | null {
+ if (!svgText) return null;
+
+ const normalizedSvg = normalizeDrawioSvg(svgText);
+
+ // Try to extract content attribute directly with regex first (faster, no DOM parsing needed)
+ const contentMatch = normalizedSvg.match(/content="([^"]*)"/);
+ if (contentMatch && contentMatch[1]) {
+ try {
+ // The content is already XML-encoded in the attribute, we need to decode it
+ const textarea = document.createElement('textarea');
+ textarea.innerHTML = contentMatch[1];
+ const decoded = textarea.value;
+
+ if (decoded && decoded.includes('<mxfile')) {
+ return decoded;
+ }
+ } catch {
+ // Fall through to DOM parser
+ }
+ }
+
+ // Fallback to DOM parsing
+ try {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(normalizedSvg, 'image/svg+xml');
+
+ // Check for parsing errors
+ if (doc.documentElement.tagName === 'parsererror') {
+ return null;
+ }
+
+ const svg = doc.documentElement;
+ if (!svg || svg.tagName.toLowerCase() !== 'svg') return null;
+
+ const encoded = svg.getAttribute('content') || '';
+ if (!encoded) return null;
+
+ const textarea = document.createElement('textarea');
+ textarea.innerHTML = encoded;
+ const decoded = textarea.value;
+
+ if (!decoded.includes('<mxfile')) return null;
+ return decoded;
+ } catch {
+ return null;
+ }
+}
+
+function formatDate(d: Date) {
+ return `${d.getFullYear()}${(d.getMonth() + 1).toString().padStart(2, '0')}${d.getDate().toString().padStart(2, '0')}`;
+}
+
+export function buildDrawioFilename(baseName: string): string {
+ const sanitized = (baseName || 'diagram')
+ .toLowerCase()
+ .replace(/[^a-z0-9\s_-]/g, '')
+ .trim()
+ .replace(/\s+/g, '-');
+
+ const safeBase = sanitized || 'diagram';
+
+ const suffix = formatDate(new Date());
+
+ return `${safeBase}-${suffix}`;
+}
diff --git a/frontend/app/helpers/markdown/index.ts b/frontend/app/helpers/markdown/index.ts
index 8bae40a8..bf93414f 100644
--- a/frontend/app/helpers/markdown/index.ts
+++ b/frontend/app/helpers/markdown/index.ts
@@ -9,7 +9,7 @@ import highlight from 'markdown-it-highlightjs';
// @ts-expect-error no types provided
import mark from 'markdown-it-mark';
import colorPlugin from './colors';
-import { subscriptPlugin, superscriptPlugin, footNotePlugin, html5MediaPlugin } from './other';
+import { subscriptPlugin, superscriptPlugin, footNotePlugin, html5MediaPlugin, svgObjectPlugin } from './other';
import { markdownItCheckbox } from './checkbox';
import { markdownItKatexPlugin } from './katex';
import { sourceMapPlugin } from './source-map';
@@ -33,6 +33,7 @@ md.use(colorPlugin, {
allowHex: true, // allow #rgb and #rrggbb
});
md.use(html5MediaPlugin);
+md.use(svgObjectPlugin);
md.use(sourceMapPlugin);
export default function compile(str: string = ''): string {
diff --git a/frontend/app/helpers/markdown/other.ts b/frontend/app/helpers/markdown/other.ts
index e76610eb..239765fd 100644
--- a/frontend/app/helpers/markdown/other.ts
+++ b/frontend/app/helpers/markdown/other.ts
@@ -153,4 +153,41 @@ function html5MediaPlugin(md: MarkdownIt) {
};
}
-export { superscriptPlugin, subscriptPlugin, footNotePlugin, html5MediaPlugin };
+const SVG_REGEX = /\.svg(\?.*)?$/i;
+
+function svgObjectPlugin(md: MarkdownIt) {
+ const defaultImageRenderer =
+ md.renderer.rules.image ||
+ function (tokens, idx, options, env, self) {
+ return self.renderToken(tokens, idx, options);
+ };
+
+ md.renderer.rules.image = (tokens, idx, options, env, self) => {
+ const token = tokens[idx];
+ if (!token) return '';
+
+ const src = token.attrGet('src') || '';
+ const alt = token.content || '';
+ const title = token.attrGet('title') || '';
+
+ if (SVG_REGEX.test(src)) {
+ const escapedSrc = md.utils.escapeHtml(src);
+ const escapedAlt = md.utils.escapeHtml(alt);
+ const escapedTitle = md.utils.escapeHtml(title);
+
+ return `
+<object
+ data="${escapedSrc}"
+ type="image/svg+xml"
+ aria-label="${escapedAlt}"
+ ${escapedTitle ? `title="${escapedTitle}"` : ''}
+>
+ ${escapedAlt}
+</object>`;
+ }
+
+ return defaultImageRenderer(tokens, idx, options, env, self);
+ };
+}
+
+export { superscriptPlugin, subscriptPlugin, footNotePlugin, html5MediaPlugin, svgObjectPlugin };
diff --git a/frontend/app/helpers/node.ts b/frontend/app/helpers/node.ts
index 8856bd0d..e2ed97f1 100644
--- a/frontend/app/helpers/node.ts
+++ b/frontend/app/helpers/node.ts
@@ -11,6 +11,7 @@ export const resolveIcon = (item: Node | DB_Node | NodeSearchResult): string =>
if (item.role === 2 && 'shared' in item) return item.shared ? 'shared_folder' : 'folder';
if (item.role === 3) return item.accessibility == 1 ? 'sidebar/file' : item.accessibility == 2 ? 'draft' : 'shared_doc';
if (item.role === 4) {
+ if (item.metadata?.drawio) return 'sidebar/diagram';
if (item.metadata?.filetype == 'application/pdf') return 'sidebar/pdf';
if (item.metadata?.filetype?.startsWith('video/')) return 'sidebar/video';
if (item.metadata?.filetype?.startsWith('audio/')) return 'sidebar/audio';
diff --git a/frontend/app/pages/dashboard/cdn/[id]/index.vue b/frontend/app/pages/dashboard/cdn/[id]/index.vue
index 11098767..054db906 100644
--- a/frontend/app/pages/dashboard/cdn/[id]/index.vue
+++ b/frontend/app/pages/dashboard/cdn/[id]/index.vue
@@ -44,7 +44,7 @@
import DeleteNodeModal from '~/components/Node/Modals/Delete.vue';
import { readableFileSize } from '~/helpers/resources';
-definePageMeta({ breadcrumb: {i18n: 'common.actions.edit'} });
+definePageMeta({ breadcrumb: { i18n: 'common.actions.edit' } });
const nodeStore = useNodesStore();
const { t } = useI18nT();
diff --git a/frontend/app/pages/dashboard/cdn/[id]/preview.vue b/frontend/app/pages/dashboard/cdn/[id]/preview.vue
index 0ea84000..3fd42aff 100644
--- a/frontend/app/pages/dashboard/cdn/[id]/preview.vue
+++ b/frontend/app/pages/dashboard/cdn/[id]/preview.vue
@@ -9,6 +9,10 @@
<Icon name="edit" display="lg" />
<p class="hint-tooltip">{{ t('common.actions.edit') }}</p>
</NuxtLink>
+ <button class="btn-icon" @click="showDrawioEditor">
+ <Icon name="format/diagrams" display="lg" />
+ <p class="hint-tooltip">{{ t('common.actions.edit') }}</p>
+ </button>
<span class="btn-icon" @click="copyLink">
<Icon name="copy" display="lg" />
<p class="hint-tooltip">{{ t('common.actions.copyLink') }}</p>
@@ -17,14 +21,15 @@
<Icon name="download" display="lg" />
<p class="hint-tooltip">{{ t('common.actions.download') }}</p>
</NuxtLink>
- <NuxtLink class="btn-icon" @click="showDeleteModal">
+ <button class="btn-icon" @click="showDeleteModal">
<Icon name="delete" display="lg" />
<p class="hint-tooltip">{{ t('common.actions.delete') }}</p>
- </NuxtLink>
+ </button>
</div>
</header>
- <div class="preview">
- <img v-if="isImageFile(mimeType)" :src="resourceURL(resource)" alt="Preview" />
+ <div ref="previewElement" class="preview">
+ <object v-if="resource.metadata?.drawio" :data="resourceURL(resource)" alt="Preview" />
+ <img v-else-if="isImageFile(mimeType)" :src="resourceURL(resource)" alt="Preview" />
<LazyPDFViewer v-else-if="isPdfFile(mimeType)" :src="resourceURL(resource)" :zoom="zoom" />
<video v-else-if="isVideoFile(mimeType)" :src="resourceURL(resource)" controls />
<audio v-else-if="isAudioFile(mimeType)" :src="resourceURL(resource)" controls />
@@ -43,14 +48,17 @@
<script setup lang="ts">
import DeleteNodeModal from '~/components/Node/Modals/Delete.vue';
+import DrawioEditorModal from '~/components/Node/Modals/DrawioEditor.vue';
import { PDF_SCALES } from '~/helpers/constants';
import { isImageFile, isPdfFile, isVideoFile, isAudioFile } from '~/helpers/resources';
+import { rerenderImages } from '~/helpers/DOM';
definePageMeta({ breadcrumb: { i18n: 'common.actions.preview' } });
const { t } = useI18nT();
const { resourceURL } = useApi();
+const previewElement = ref<HTMLElement | null>();
const zoom = ref<(typeof PDF_SCALES)[number]['id']>('automatic_zoom');
const resource = computed(() => useNodesStore().getById(useRoute().params.id as string));
@@ -60,7 +68,18 @@ const copyLink = () => {
const link = resourceURL(resource.value!);
navigator.clipboard.writeText(link);
};
-
+function showDrawioEditor() {
+ const modalManager = useModal();
+ const modal = new Modal(shallowRef(DrawioEditorModal), {
+ props: {
+ node: resource.value,
+ },
+ onClose: () => rerenderImages(previewElement.value!),
+ size: 'large',
+ noPadding: true,
+ });
+ modalManager.add(modal);
+}
const showDeleteModal = () => {
useModal().add(new Modal(shallowRef(DeleteNodeModal), { props: { nodes: [resource.value], redirectTo: '/dashboard/cdn' }, size: 'small' }));
};
diff --git a/frontend/app/pages/dashboard/cdn/diagram.vue b/frontend/app/pages/dashboard/cdn/diagram.vue
new file mode 100644
index 00000000..c766eb9d
--- /dev/null
+++ b/frontend/app/pages/dashboard/cdn/diagram.vue
@@ -0,0 +1,120 @@
+<template>
+ <div class="drawio-editor-modal">
+ <aside>
+ <input v-model="node.name" type="text" :placeholder="t('common.labels.name')" />
+
+ <button class="btn-icon" @click="requestSaveDiagram">
+ <Icon name="save" display="lg" />
+ <p class="hint-tooltip">{{ t('common.actions.save') }}</p>
+ </button>
+ </aside>
+
+ <div class="drawio-content">
+ <iframe :key="iframeKey" ref="iframe" class="drawio-iframe" :src="iframeUrl" />
+
+ <div v-if="!isReady" class="loading-overlay">
+ <LoaderSpinner />
+ <p>{{ t('common.status.loading') }}</p>
+ </div>
+ </div>
+ </div>
+</template>
+
+<script setup lang="ts">
+import type { Node } from '~/stores';
+
+const { t } = useI18nT();
+const router = useRouter();
+
+const iframe = ref<HTMLIFrameElement | null>(null);
+const iframeKey = ref(0);
+
+const iframeUrl = 'https://embed.diagrams.net/?embed=1&ui=min&spin=1&proto=json';
+
+const node: Ref<Partial<Node>> = ref({});
+const { handleMessage, isReady } = useDrawioIframe(iframe);
+
+function requestSaveDiagram() {
+ if (!isReady.value) return;
+ postMessageToIframe({
+ action: 'export',
+ format: 'xmlsvg',
+ xml: true,
+ });
+}
+
+function postMessageToIframe(msg: object) {
+ if (!iframe.value?.contentWindow) return;
+ iframe.value.contentWindow.postMessage(JSON.stringify(msg), '*');
+}
+const exitHandleMessage = async (e: MessageEvent) => {
+ const result = await handleMessage(e, node.value.name);
+ if (result) router.push(`/dashboard/cdn`);
+};
+
+onMounted(() => window.addEventListener('message', exitHandleMessage));
+
+onBeforeUnmount(() => window.removeEventListener('message', exitHandleMessage));
+</script>
+
+<style scoped lang="scss">
+.drawio-editor-modal {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ margin-top: 10px;
+ gap: 12px;
+}
+
+aside {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+}
+
+.drawio-content {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ border-radius: var(--radius-md);
+ overflow: hidden;
+ background: var(--surface-base);
+ border: 1px solid var(--border);
+}
+
+.drawio-iframe {
+ width: 100%;
+ height: 100%;
+ border: none;
+ background: var(--surface-base);
+}
+
+.loading-overlay {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ background: var(--surface-base);
+ z-index: 10;
+
+ p {
+ color: var(--text-secondary);
+ font-size: 14px;
+ }
+}
+
+@media (width <= 900px) {
+ .drawio-editor-modal {
+ height: 60vh;
+ }
+}
+
+@media (width <= 600px) {
+ .drawio-editor-modal {
+ height: 50vh;
+ }
+}
+</style>
diff --git a/frontend/app/pages/dashboard/cdn/index.vue b/frontend/app/pages/dashboard/cdn/index.vue
index 741cbbd6..dc7a1ea4 100644
--- a/frontend/app/pages/dashboard/cdn/index.vue
+++ b/frontend/app/pages/dashboard/cdn/index.vue
@@ -109,7 +109,7 @@ const MAX_STORAGE = 1024 * 1024 * 1024; // 1 GB in bytes
const nodes = computed(() => nodesStore.resources.toArray());
const filteredResources = ref(nodes.value);
-const totalUsedSpace = computed(() => nodes.value.reduce((acc, node) => acc + (node.size ?? 0), 0));
+const totalUsedSpace = computed(() => nodesStore.getTotalUsedStorage);
const storagePercentage = computed(() => Math.min((totalUsedSpace.value / MAX_STORAGE) * 100, 100));
const linksText = computed(() => fileLinks.value.join('\n'));
diff --git a/frontend/app/stores/db_strustures.d.ts b/frontend/app/stores/db_strustures.d.ts
index a1fc4fc9..195808fa 100644
--- a/frontend/app/stores/db_strustures.d.ts
+++ b/frontend/app/stores/db_strustures.d.ts
@@ -21,6 +21,7 @@ export interface DB_Node {
filetype?: string;
original_path?: string;
transformed_path?: string;
+ drawio?: boolean;
};
created_timestamp: number;
updated_timestamp: number;
diff --git a/frontend/app/stores/nodes.store.ts b/frontend/app/stores/nodes.store.ts
index 1cabba8a..6643bf6b 100644
--- a/frontend/app/stores/nodes.store.ts
+++ b/frontend/app/stores/nodes.store.ts
@@ -30,6 +30,7 @@ export const useNodesStore = defineStore('nodes', {
getAll: state => state.nodes,
getAllTags: state => state.allTags,
getById: state => (id: string) => state.nodes.get(id),
+ getTotalUsedStorage: state => state.nodes.toArray().reduce((total, node) => total + (node.size || 0), 0),
getByIdWithParents: state => (id: string) => {
const node = state.nodes.get(id);
diff --git a/frontend/app/stores/resources.store.ts b/frontend/app/stores/resources.store.ts
index cf23894f..b41d0cfc 100644
--- a/frontend/app/stores/resources.store.ts
+++ b/frontend/app/stores/resources.store.ts
@@ -15,6 +15,13 @@ export const useResourcesStore = defineStore('resources', {
} else throw request.message;
},
+ async update(id: string, resource: FormData): Promise<Node> {
+ const request = await makeRequest(`resources/${id}`, 'PUT', resource);
+ if (request.status == 'success') {
+ return request.result as Node;
+ } else throw request.message;
+ },
+
async postAvatar(resource: FormData): Promise<{ original_path: string; content_compiled: string }> {
const request = await makeRequest(`resources/avatar`, 'POST', resource);
if (request.status == 'success') {
diff --git a/frontend/app/styles/base/media.scss b/frontend/app/styles/base/media.scss
index fa01975d..64a4fdb1 100644
--- a/frontend/app/styles/base/media.scss
+++ b/frontend/app/styles/base/media.scss
@@ -1,4 +1,5 @@
-img {
+img,
+object {
width: auto;
max-width: 100%;
height: auto;
@@ -6,6 +7,7 @@ img {
margin-bottom: 5px;
}
+
audio,
video {
display: block;
diff --git a/frontend/i18n/locales/en/markdown.ts b/frontend/i18n/locales/en/markdown.ts
index 96e41e95..5c4390dd 100644
--- a/frontend/i18n/locales/en/markdown.ts
+++ b/frontend/i18n/locales/en/markdown.ts
@@ -13,6 +13,10 @@ export default {
title: 'Select an image',
uploadError: 'An error occurred while uploading.',
},
+ drawio: {
+ linked: 'Linked diagrams',
+ title: 'Diagram editor',
+ },
stats: {
chars: 'chars.',
lines: 'lines',
@@ -49,6 +53,7 @@ export default {
color: 'Color',
editorSettings: 'Editor settings',
+ diagram: 'Diagram',
footnote: 'Footnote',
goToDocument: 'Go to document',
diff --git a/frontend/i18n/locales/fr/markdown.ts b/frontend/i18n/locales/fr/markdown.ts
index 4a721061..b1877faf 100644
--- a/frontend/i18n/locales/fr/markdown.ts
+++ b/frontend/i18n/locales/fr/markdown.ts
@@ -13,6 +13,10 @@ export default {
title: 'Sélectionner une image',
uploadError: 'Une erreur est survenue lors du téléchargement.',
},
+ drawio: {
+ linked: 'Diagrammes liés',
+ title: 'Éditeur de diagrammes',
+ },
stats: {
chars: 'car.',
lines: 'lignes',
@@ -49,6 +53,7 @@ export default {
color: 'Couleur',
editorSettings: "Paramètres de l'éditeur",
+ diagram: 'Diagramme',
footnote: 'Note de bas de page',
goToDocument: 'Aller au document',
diff --git a/frontend/i18n/locales/uk/markdown.ts b/frontend/i18n/locales/uk/markdown.ts
index 18bdb152..f79c4967 100644
--- a/frontend/i18n/locales/uk/markdown.ts
+++ b/frontend/i18n/locales/uk/markdown.ts
@@ -13,6 +13,10 @@ export default {
title: 'Виберіть зображення',
uploadError: 'Під час завантаження сталася помилка.',
},
+ drawio: {
+ linked: "Пов'язані діаграми",
+ title: 'Редактор діаграм',
+ },
stats: {
chars: 'символів.',
lines: 'рядків',
@@ -29,7 +33,7 @@ export default {
layoutBlocks: 'Блоки макета',
linksAndImages: 'Посилання та зображення',
mathSyntax: 'Синтаксис математичних виразів',
- subtitle: "У цьому посібнику описано, як використовувати розширені функції Markdown у програмі Alexandrie для створення виразних і структурованих нотаток.",
+ subtitle: 'У цьому посібнику описано, як використовувати розширені функції Markdown у програмі Alexandrie для створення виразних і структурованих нотаток.',
tags: 'Теги',
title: 'Посібник із синтаксису Markdown для «Alexandrie»',
titles: 'Заголовки',
@@ -49,6 +53,7 @@ export default {
color: 'Колір',
editorSettings: 'Налаштування редактора',
+ diagram: 'Діаграма',
footnote: 'Примітка',
goToDocument: 'Перейти до документа',
diff --git a/frontend/public/app-icons/format/diagrams.svg b/frontend/public/app-icons/format/diagrams.svg
new file mode 100644
index 00000000..4b578fec
--- /dev/null
+++ b/frontend/public/app-icons/format/diagrams.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h360v80H200v560h560v-360h80v360q0 33-23.5 56.5T760-120H200Zm80-160h80v-280h-80v280Zm160 0h80v-400h-80v400Zm160 0h80v-160h-80v160Zm80-320v-80h-80v-80h80v-80h80v80h80v80h-80v80h-80ZM480-480Z"/></svg>
\ No newline at end of file
diff --git a/frontend/public/app-icons/fullsreen.svg b/frontend/public/app-icons/fullsreen.svg
new file mode 100644
index 00000000..3cca3097
--- /dev/null
+++ b/frontend/public/app-icons/fullsreen.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M120-120v-200h80v120h120v80H120Zm520 0v-80h120v-120h80v200H640ZM120-640v-200h200v80H200v120h-80Zm640 0v-120H640v-80h200v200h-80Z"/></svg>
\ No newline at end of file
diff --git a/frontend/public/app-icons/sidebar/diagram.svg b/frontend/public/app-icons/sidebar/diagram.svg
new file mode 100644
index 00000000..53844c29
--- /dev/null
+++ b/frontend/public/app-icons/sidebar/diagram.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960"><path d="M280-80q-50 0-85-35t-35-85q0-39 22.5-70t57.5-43v-334q-35-12-57.5-43T160-760q0-50 35-85t85-35q50 0 85 35t35 85q0 39-22.5 70T320-647v167q25-19 55.5-29.5T440-520h80q50 0 85-35t35-85v-7q-35-12-57.5-43T560-760q0-50 35-85t85-35q50 0 85 35t35 85q0 39-22.5 70T720-647v7q0 83-58.5 141.5T520-440h-80q-50 0-85 35t-35 85v7q35 12 57.5 43t22.5 70q0 50-35 85t-85 35Zm0-640q17 0 28.5-11.5T320-760q0-17-11.5-28.5T280-800q-17 0-28.5 11.5T240-760q0 17 11.5 28.5T280-720Zm400 0q17 0 28.5-11.5T720-760q0-17-11.5-28.5T680-800q-17 0-28.5 11.5T640-760q0 17 11.5 28.5T680-720ZM280-160q17 0 28.5-11.5T320-200q0-17-11.5-28.5T280-240q-17 0-28.5 11.5T240-200q0 17 11.5 28.5T280-160Zm0-600Zm400 0ZM280-200Z"/></svg>
\ No newline at end of file