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.

Start version 8: Introduce nodes

Smaug67391c9b2a927272
diff --git a/backend/app/app.go b/backend/app/app.go
index 3c06f747..e875e5a8 100644
--- a/backend/app/app.go
+++ b/backend/app/app.go
@@ -31,13 +31,11 @@ type Config struct {
}
type Services struct {
- User services.UserService
- Session services.AuthService
- Log services.LogService
- Document services.DocumentService
- Category services.CategoryService
- Ressource services.RessourceService
- Minio services.MinioService
+ User services.UserService
+ Session services.AuthService
+ Log services.LogService
+ Nodes services.NodeService
+ Minio services.MinioService
}
type App struct {
@@ -57,13 +55,11 @@ func InitApp(config Config) *App {
app.Snowflake = utils.NewSnowflake(1609459200000)
app.Config = config
app.Services = Services{
- User: services.NewUserService(app.DB),
- Session: services.NewAuthService(app.DB),
- Log: services.NewLogService(app.DB),
- Document: services.NewDocumentService(app.DB),
- Category: services.NewCategoryService(app.DB),
- Ressource: services.NewRessourceService(app.DB),
- Minio: services.NewMinioService(app.MinioClient),
+ User: services.NewUserService(app.DB),
+ Session: services.NewAuthService(app.DB),
+ Log: services.NewLogService(app.DB),
+ Nodes: services.NewNodeService(app.DB),
+ Minio: services.NewMinioService(app.MinioClient),
}
Migrate(&config)
diff --git a/backend/controllers/categories.controller.go b/backend/controllers/categories.controller.go
deleted file mode 100644
index 2bb46a58..00000000
--- a/backend/controllers/categories.controller.go
+++ /dev/null
@@ -1,155 +0,0 @@
-package controllers
-
-import (
- "alexandrie/app"
- "alexandrie/models"
- "alexandrie/utils"
- "net/http"
-
- "github.com/gin-gonic/gin"
-)
-
-type CategoriesController interface {
- GetCategories(c *gin.Context) (int, any)
- CreateCategory(c *gin.Context) (int, any)
- UpdateCategory(c *gin.Context) (int, any)
- DeleteCategory(c *gin.Context) (int, any)
-}
-
-func NewCategoriesController(app *app.App) CategoriesController {
- return &Controller{
- app: app,
- }
-}
-
-// Get categories
-// @Summary Get all categories
-// @Method GET
-// @Router /categories [get]
-// @Security Authenfification: Auth
-// @Success 200 {object} Success([]models.Category)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) GetCategories(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR, "userId")
- if err != nil {
- return http.StatusUnauthorized, err
- }
- categories, err := ctr.app.Services.Category.GetAllCategories(id)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, categories
-}
-
-// Create category
-// @Summary Create a new category
-// @Method POST
-// @Router /categories [post]
-// @Security Authenfification: Auth
-// @Param category body models.Category true "Category"
-// @Success 201 {object} Success(models.Category)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) CreateCategory(c *gin.Context) (int, any) {
- var category models.Category
- if err := c.ShouldBind(&category); err != nil {
- return http.StatusBadRequest, err
- }
-
- userId, err := utils.GetUserIdCtx(c)
- if err != nil {
- return http.StatusUnauthorized, err
- }
- category = models.Category{
- Id: ctr.app.Snowflake.Generate(),
- Name: category.Name,
- Icon: category.Icon,
- Color: category.Color,
- Order: category.Order,
- Role: category.Role,
- WorkspaceId: category.WorkspaceId,
- ParentId: category.ParentId,
- AuthorId: userId,
- }
-
- if err := ctr.app.Services.Category.CreateCategory(&category); err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusCreated, category
-}
-
-// Update category
-// @Summary Update a category
-// @Method PUT
-// @Router /categories/{id} [put]
-// @Security Authenfification: Auth
-// @Param id path string true "Category ID"
-// @Param category body models.Category true "Category"
-// @Success 200 {object} Success(models.Category)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) UpdateCategory(c *gin.Context) (int, any) {
- categoryid, err := utils.GetIdParam(c, c.Param("id"))
- if err != nil {
- return http.StatusBadRequest, err
- }
- dbCategory, err := ctr.app.Services.Category.GetCategory(categoryid)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- err = utils.RessourceAccess(c, dbCategory.AuthorId)
- if err != nil {
- return http.StatusUnauthorized, err
- }
- category := &models.Category{}
- if err := c.ShouldBind(category); err != nil {
- return http.StatusBadRequest, err
- }
- category = &models.Category{
- Id: categoryid,
- Name: category.Name,
- Icon: category.Icon,
- Color: category.Color,
- Order: category.Order,
- Role: category.Role,
- WorkspaceId: category.WorkspaceId,
- ParentId: category.ParentId,
- AuthorId: dbCategory.AuthorId,
- }
-
- err = ctr.app.Services.Category.UpdateCategory(category)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, category
-}
-
-// Delete category
-// @Summary Delete a category
-// @Method DELETE
-// @Router /categories/{id} [delete]
-// @Security Authenfification: Auth
-// @Param id path string true "Category ID"
-// @Success 204 {object} Success
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) DeleteCategory(c *gin.Context) (int, any) {
- categoryId, err := utils.GetIdParam(c, c.Param("id"))
- if err != nil {
- return http.StatusBadRequest, err
- }
- db_category, err := ctr.app.Services.Category.GetCategory(categoryId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- err = utils.RessourceAccess(c, db_category.AuthorId)
- if err != nil {
- return http.StatusUnauthorized, err
- }
- err = ctr.app.Services.Category.DeleteCategory(categoryId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, db_category
-}
diff --git a/backend/controllers/documents.controller.go b/backend/controllers/documents.controller.go
deleted file mode 100644
index 9a5f3d09..00000000
--- a/backend/controllers/documents.controller.go
+++ /dev/null
@@ -1,218 +0,0 @@
-package controllers
-
-import (
- "alexandrie/app"
- "alexandrie/models"
- "alexandrie/utils"
- "net/http"
- "time"
-
- "github.com/gin-gonic/gin"
-)
-
-type DocumentController interface {
- GetPublicDocument(c *gin.Context) (int, any)
- GetDocuments(c *gin.Context) (int, any)
- GetDocument(c *gin.Context) (int, any)
- CreateDocument(c *gin.Context) (int, any)
- UpdateDocument(c *gin.Context) (int, any)
- DeleteDocument(c *gin.Context) (int, any)
-}
-
-func NewDocumentController(app *app.App) DocumentController {
- return &Controller{
- app: app,
- }
-}
-
-// Get public document by id
-// @Summary Get public document by id
-// @Method GET
-// @Router /documents/public/{id} [get]
-// @Security Authenfification: None
-// @Param id path string true "Document ID"
-// @Success 200 {object} Success(models.Document)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) GetPublicDocument(c *gin.Context) (int, any) {
- documentId, err := utils.GetIdParam(c, c.Param("id"))
- if err != nil {
- return http.StatusBadRequest, err
- }
- document, err := ctr.app.Services.Document.GetPublicDocument(documentId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, document
-}
-
-// Get documents
-// @Summary Get all documents
-// @Method GET
-// @Router /documents [get]
-// @Security Authenfification: Auth
-// @Success 200 {object} Success([]models.Document)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) GetDocuments(c *gin.Context) (int, any) {
- id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR, "userId")
- if err != nil {
- return http.StatusUnauthorized, err
- }
- documents, err := ctr.app.Services.Document.GetAllDocuments(id)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, documents
-}
-
-// Get document by id
-// @Summary Get document by id
-// @Method GET
-// @Router /documents/{id} [get]
-// @Security Authenfification: Auth
-// @Param id path string true "Document ID"
-// @Success 200 {object} Success(models.Document)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) GetDocument(c *gin.Context) (int, any) {
- documentId, err := utils.GetIdParam(c, c.Param("id"))
- if err != nil {
- return http.StatusBadRequest, err
- }
- document, err := ctr.app.Services.Document.GetDocument(documentId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- err = utils.RessourceAccess(c, document.AuthorId)
- if err != nil {
- return http.StatusUnauthorized, err
- }
- return http.StatusOK, document
-}
-
-// Create document
-// @Summary Create document
-// @Method POST
-// @Router /documents [post]
-// @Security Authenfification: Auth
-// @Body document body models.Document true "Document"
-// @Success 200 {object} Success(models.Document)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) CreateDocument(c *gin.Context) (int, any) {
- document := &models.Document{}
- if err := c.ShouldBind(document); err != nil {
- return http.StatusBadRequest, err
- }
- userId, err := utils.GetUserIdCtx(c)
- if err != nil {
- return http.StatusUnauthorized, err
- }
- document = &models.Document{
- Id: ctr.app.Snowflake.Generate(),
- Name: document.Name,
- Description: document.Description,
- Tags: document.Tags,
- Pinned: document.Pinned,
- Thumbnail: document.Thumbnail,
- Theme: document.Theme,
- Icon: document.Icon,
- Color: document.Color,
- Category: document.Category,
- ParentId: document.ParentId,
- Accessibility: document.Accessibility,
- ContentMarkdown: document.ContentMarkdown,
- ContentHtml: document.ContentHtml,
- AuthorId: userId,
- CreatedTimestamp: time.Now().UnixMilli(),
- UpdatedTimestamp: time.Now().UnixMilli(),
- }
- err = ctr.app.Services.Document.CreateDocument(document)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, document
-}
-
-// Update document
-// @Summary Update document
-// @Method PUT
-// @Router /documents/{id} [put]
-// @Security Authenfification: Auth
-// @Param id path string true "Document ID"
-// @Body document body models.Document true "Document"
-// @Success 200 {object} Success(models.Document)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) UpdateDocument(c *gin.Context) (int, any) {
- documentId, err := utils.GetIdParam(c, c.Param("id"))
- if err != nil {
- return http.StatusBadRequest, err
- }
- db_document, err := ctr.app.Services.Document.GetDocument(documentId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- err = utils.RessourceAccess(c, db_document.AuthorId)
- if err != nil {
- return http.StatusUnauthorized, err
- }
- document := &models.Document{}
- if err := c.ShouldBind(document); err != nil {
- return http.StatusBadRequest, err
- }
- document = &models.Document{
- Id: documentId,
- Name: document.Name,
- Description: document.Description,
- Tags: document.Tags,
- Pinned: document.Pinned,
- Thumbnail: document.Thumbnail,
- Theme: document.Theme,
- Icon: document.Icon,
- Color: document.Color,
- Category: document.Category,
- ParentId: document.ParentId,
- Accessibility: document.Accessibility,
- ContentMarkdown: document.ContentMarkdown,
- ContentHtml: document.ContentHtml,
- AuthorId: db_document.AuthorId,
- CreatedTimestamp: time.Now().UnixMilli(),
- }
-
- err = ctr.app.Services.Document.UpdateDocument(document)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, document
-}
-
-// Delete document
-// @Summary Delete document
-// @Method DELETE
-// @Router /documents/{id} [delete]
-// @Security Authenfification: Auth
-// @Param id path string true "Document ID"
-// @Success 200 {object} Success(models.Document)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) DeleteDocument(c *gin.Context) (int, any) {
- documentId, err := utils.GetIdParam(c, c.Param("id"))
- if err != nil {
- return http.StatusBadRequest, err
- }
- db_document, err := ctr.app.Services.Document.GetDocument(documentId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- err = utils.RessourceAccess(c, db_document.AuthorId)
- if err != nil {
- return http.StatusUnauthorized, err
- }
- err = ctr.app.Services.Document.DeleteDocument(documentId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, db_document
-}
diff --git a/backend/controllers/nodes.controller.go b/backend/controllers/nodes.controller.go
new file mode 100644
index 00000000..95d0ae11
--- /dev/null
+++ b/backend/controllers/nodes.controller.go
@@ -0,0 +1,220 @@
+package controllers
+
+import (
+ "alexandrie/app"
+ "alexandrie/models"
+ "alexandrie/utils"
+ "net/http"
+ "time"
+
+ "github.com/gin-gonic/gin"
+)
+
+type NodeController interface {
+ GetPublicNode(c *gin.Context) (int, any)
+ GetNodes(c *gin.Context) (int, any)
+ GetNode(c *gin.Context) (int, any)
+ CreateNode(c *gin.Context) (int, any)
+ UpdateNode(c *gin.Context) (int, any)
+ DeleteNode(c *gin.Context) (int, any)
+}
+
+func NewNodeController(app *app.App) NodeController {
+ return &Controller{
+ app: app,
+ }
+}
+
+// Get public node by id
+// @Summary Get public node by id
+// @Method GET
+// @Router /nodes/public/{id} [get]
+// @Security Authenfification: None
+// @Param id path string true "Node ID"
+// @Success 200 {object} Success(models.Node)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) GetPublicNode(c *gin.Context) (int, any) {
+ nodeId, err := utils.GetIdParam(c, c.Param("id"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ node, err := ctr.app.Services.Nodes.GetPublicNode(nodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, node
+}
+
+// Get nodes
+// @Summary Get all nodes
+// @Method GET
+// @Router /nodes [get]
+// @Security Authenfification: Auth
+// @Success 200 {object} Success([]models.Node)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) GetNodes(c *gin.Context) (int, any) {
+ id, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR, "userId")
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ nodes, err := ctr.app.Services.Nodes.GetAllNodes(id)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, nodes
+}
+
+// Get node by id
+// @Summary Get node by id
+// @Method GET
+// @Router /nodes/{id} [get]
+// @Security Authenfification: Auth
+// @Param id path string true "Node ID"
+// @Success 200 {object} Success(models.Node)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) GetNode(c *gin.Context) (int, any) {
+ nodeId, err := utils.GetIdParam(c, c.Param("id"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ node, err := ctr.app.Services.Nodes.GetNode(nodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ err = utils.RessourceAccess(c, node.UserId)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ return http.StatusOK, node
+}
+
+// Create node
+// @Summary Create node
+// @Method POST
+// @Router /nodes [post]
+// @Security Authenfification: Auth
+// @Body node body models.Node true "Node"
+// @Success 200 {object} Success(models.Node)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) CreateNode(c *gin.Context) (int, any) {
+ node := &models.Node{}
+ if err := c.ShouldBind(node); err != nil {
+ return http.StatusBadRequest, err
+ }
+ userId, err := utils.GetUserIdCtx(c)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ node = &models.Node{
+ Id: ctr.app.Snowflake.Generate(),
+ ParentId: node.ParentId,
+ UserId: userId,
+ Name: node.Name,
+ Description: node.Description,
+ Role: node.Role,
+ Tags: node.Tags,
+ Thumbnail: node.Thumbnail,
+ Theme: node.Theme,
+ Icon: node.Icon,
+ Color: node.Color,
+ Accessibility: node.Accessibility,
+ Display: node.Display,
+ Order: node.Order,
+ Content: node.Content,
+ ContentCompiled: node.ContentCompiled,
+ CreatedTimestamp: time.Now().UnixMilli(),
+ UpdatedTimestamp: time.Now().UnixMilli(),
+ }
+ err = ctr.app.Services.Nodes.CreateNode(node)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, node
+}
+
+// Update node
+// @Summary Update node
+// @Method PUT
+// @Router /nodes/{id} [put]
+// @Security Authenfification: Auth
+// @Param id path string true "Node ID"
+// @Body node body models.Node true "Node"
+// @Success 200 {object} Success(models.Node)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) UpdateNode(c *gin.Context) (int, any) {
+ nodeId, err := utils.GetIdParam(c, c.Param("id"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ db_node, err := ctr.app.Services.Nodes.GetNode(nodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ err = utils.RessourceAccess(c, db_node.UserId)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ node := &models.Node{}
+ if err := c.ShouldBind(node); err != nil {
+ return http.StatusBadRequest, err
+ }
+ node = &models.Node{
+ Id: nodeId,
+ Name: node.Name,
+ Role: db_node.Role,
+ Description: node.Description,
+ Tags: node.Tags,
+ Thumbnail: node.Thumbnail,
+ Theme: node.Theme,
+ Icon: node.Icon,
+ Color: node.Color,
+ ParentId: node.ParentId,
+ Accessibility: node.Accessibility,
+ Display: node.Display,
+ Order: node.Order,
+ Content: node.Content,
+ ContentCompiled: node.ContentCompiled,
+ UserId: db_node.UserId,
+ CreatedTimestamp: time.Now().UnixMilli(),
+ }
+
+ err = ctr.app.Services.Nodes.UpdateNode(node)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, node
+}
+
+// Delete node
+// @Summary Delete node
+// @Method DELETE
+// @Router /nodes/{id} [delete]
+// @Security Authenfification: Auth
+// @Param id path string true "Node ID"
+// @Success 200 {object} Success(models.Node)
+// @Failure 400 {object} Error
+// @Failure 401 {object} Error
+func (ctr *Controller) DeleteNode(c *gin.Context) (int, any) {
+ nodeId, err := utils.GetIdParam(c, c.Param("id"))
+ if err != nil {
+ return http.StatusBadRequest, err
+ }
+ db_node, err := ctr.app.Services.Nodes.GetNode(nodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ err = utils.RessourceAccess(c, db_node.UserId)
+ if err != nil {
+ return http.StatusUnauthorized, err
+ }
+ err = ctr.app.Services.Nodes.DeleteNode(nodeId)
+ if err != nil {
+ return http.StatusInternalServerError, err
+ }
+ return http.StatusOK, db_node
+}
diff --git a/backend/controllers/ressources.controller.go b/backend/controllers/ressources.controller.go
index 8a75afd9..9e54a6ed 100644
--- a/backend/controllers/ressources.controller.go
+++ b/backend/controllers/ressources.controller.go
@@ -21,11 +21,9 @@ import (
)
type RessourceController interface {
- GetAllUploads(c *gin.Context) (int, any)
GetBackup(c *gin.Context) (int, any)
UploadFile(c *gin.Context) (int, any)
UploadAvatar(c *gin.Context) (int, any)
- UpdateUpload(c *gin.Context) (int, any)
DeleteUpload(c *gin.Context) (int, any)
}
@@ -35,20 +33,8 @@ func NewRessourceController(app *app.App) RessourceController {
}
}
-func (ctr *Controller) GetAllUploads(c *gin.Context) (int, any) {
- userId, err := utils.SelfOrPermission(c, utils.ADMINISTRATOR, "userId")
- if err != nil {
- return http.StatusUnauthorized, err
- }
- uploads, err := ctr.app.Services.Ressource.GetAllUploadsByUserId(userId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- return http.StatusOK, uploads
-}
-
// Get backup
-// @Summary Get backups files of database (documents, categories, ressources)
+// @Summary Get backups files of database (documents, categories, nodes)
// @Summary Save database as json file and save it in minio (/userid/backups)
// @Method GET
// @Router /uploads/backup [get]
@@ -58,30 +44,19 @@ func (ctr *Controller) GetAllUploads(c *gin.Context) (int, any) {
// @Failure 401 {object} Error
func (ctr *Controller) GetBackup(c *gin.Context) (int, any) {
if ctr.app.MinioClient == nil {
- return http.StatusInternalServerError, errors.New("Minio client not initialized")
+ return http.StatusInternalServerError, errors.New("minio client not initialized")
}
userId, err := utils.GetUserIdCtx(c)
if err != nil {
return http.StatusBadRequest, err
}
- // Create the backup file from database data
- documents_list, err := ctr.app.Services.Document.GetAllDocumentBackup(userId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- categories_list, err := ctr.app.Services.Category.GetAllCategories(userId)
- if err != nil {
- return http.StatusInternalServerError, err
- }
- ressources_list, err := ctr.app.Services.Ressource.GetAllUploadsByUserId(userId)
+ nodes_list, err := ctr.app.Services.Nodes.GetAllNodeBackup(userId)
if err != nil {
return http.StatusInternalServerError, err
}
backup := map[string]interface{}{
- "documents": documents_list,
- "categories": categories_list,
- "ressources": ressources_list,
+ "nodes": nodes_list,
}
jsonString, err := json.Marshal(backup)
if err != nil {
@@ -103,12 +78,12 @@ func (ctr *Controller) GetBackup(c *gin.Context) (int, any) {
// @Router /uploads/ [post]
// @Security Authenfification: Auth
// @Param file formData file true "File to upload"
-// @Success 200 {object} Success(ressource)
+// @Success 200 {object} Success(node)
// @Failure 400 {object} Error
// @Failure 401 {object} Error
func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
if ctr.app.MinioClient == nil {
- return http.StatusInternalServerError, errors.New("Minio client not initialized")
+ return http.StatusInternalServerError, errors.New("minio client not initialized")
}
file, header, err := c.Request.FormFile("file")
if err != nil {
@@ -136,32 +111,38 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
}
// Check total size of uploads
- totalSize, err := ctr.app.Services.Ressource.GetUserUploadsSize(userId)
+ totalSize, err := ctr.app.Services.Nodes.GetUserUploadsSize(userId)
if err != nil {
return http.StatusInternalServerError, err
}
if totalSize+header.Size > int64(ctr.app.Config.Cdn.MaxUploadsSize) {
return http.StatusBadRequest, errors.New("total size of uploads exceeds the limit")
}
-
- // Create a new ressource
id := ctr.app.Snowflake.Generate()
- ressource := &models.Ressource{
+ transformedPath := fmt.Sprintf("%d%s", id, ext)
+ metadata := map[string]interface{}{
+ "filetype": mimeType,
+ "original_path": header.Filename,
+ "transformed_path": transformedPath,
+ }
+ // Create a new node
+ node := &models.Node{
Id: id,
- Filename: fmt.Sprintf("%.*s", 40, header.Filename),
- Filesize: header.Size,
- Filetype: mimeType,
- OriginalPath: header.Filename,
- TransformedPath: fmt.Sprintf("%d%s", id, ext),
+ UserId: userId,
ParentId: nil,
- AuthorId: userId,
+ Name: fmt.Sprintf("%.*s", 50, header.Filename),
+ Role: 4, // Ressource role is always 4
+ Size: &header.Size,
+ Content: &header.Filename,
+ ContentCompiled: &transformedPath,
+ Metadata: &metadata,
CreatedTimestamp: time.Now().UnixMilli(),
}
- objectName := fmt.Sprintf("%d/%d%s", ressource.AuthorId, ressource.Id, ext)
+ objectName := fmt.Sprintf("%d/%d%s", node.UserId, node.Id, ext)
- _, err = ctr.app.Services.Ressource.CreateRessource(ressource)
+ err = ctr.app.Services.Nodes.CreateNode(node)
if err != nil {
- return http.StatusInternalServerError, errors.New("failed to create ressource")
+ return http.StatusInternalServerError, errors.New("failed to create node")
}
_, err = ctr.app.MinioClient.PutObject(c, os.Getenv("MINIO_BUCKET"), objectName, file, header.Size, minio.PutObjectOptions{ContentType: header.Header.Get("Content-Type")})
@@ -169,7 +150,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
return http.StatusInternalServerError, errors.New("failed to upload file")
}
- return http.StatusOK, ressource
+ return http.StatusOK, node
}
// Upload avatar
@@ -183,7 +164,7 @@ func (ctr *Controller) UploadFile(c *gin.Context) (int, any) {
// @Failure 401 {object} Error
func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {
if ctr.app.MinioClient == nil {
- return http.StatusInternalServerError, errors.New("Minio client not initialized")
+ return http.StatusInternalServerError, errors.New("minio client not initialized")
}
file, header, err := c.Request.FormFile("file")
if err != nil {
@@ -218,57 +199,6 @@ func (ctr *Controller) UploadAvatar(c *gin.Context) (int, any) {
return http.StatusOK, "File uploaded successfully"
}
-// UpdateUpload
-// @Summary Update an upload (only metadata)
-// @Method PUT
-// @Router /uploads/{id} [put]
-// @Security Authenfification: Auth
-// @Param id path string true "ID of the upload to update"
-// @Param upload body models.Ressource true "Upload data"
-// @Success 200 {object} Success(models.Ressource)
-// @Failure 400 {object} Error
-// @Failure 401 {object} Error
-func (ctr *Controller) UpdateUpload(c *gin.Context) (int, any) {
- id, err := utils.GetIdParam(c, c.Param("id"))
- if err != nil {
- return http.StatusBadRequest, errors.New("invalid id format")
- }
- db_ressource, err := ctr.app.Services.Ressource.GetRessourceById(id)
- if err != nil {
- return http.StatusInternalServerError, "failed to get ressource"
- }
- if db_ressource == nil {
- return http.StatusBadRequest, errors.New("ressource not found")
- }
- err = utils.RessourceAccess(c, db_ressource.AuthorId)
- if err != nil {
- return http.StatusUnauthorized, err
- }
-
- var updatedRessource *models.Ressource
- if err := c.ShouldBindJSON(&updatedRessource); err != nil {
- return http.StatusBadRequest, errors.New("failed to bind JSON")
- }
- updatedRessource = &models.Ressource{
- Id: db_ressource.Id,
- Filename: updatedRessource.Filename,
- Filesize: db_ressource.Filesize,
- Filetype: db_ressource.Filetype,
- OriginalPath: db_ressource.OriginalPath,
- TransformedPath: db_ressource.TransformedPath,
- ParentId: updatedRessource.ParentId,
- AuthorId: db_ressource.AuthorId,
- CreatedTimestamp: db_ressource.CreatedTimestamp,
- }
-
- _, err = ctr.app.Services.Ressource.UpdateRessource(updatedRessource)
- if err != nil {
- return http.StatusInternalServerError, errors.New("failed to update ressource")
- }
-
- return http.StatusOK, updatedRessource
-}
-
// DeleteUpload
// @Summary Delete an upload
// @Method DELETE
@@ -280,7 +210,7 @@ func (ctr *Controller) UpdateUpload(c *gin.Context) (int, any) {
// @Failure 401 {object} Error
func (ctr *Controller) DeleteUpload(c *gin.Context) (int, any) {
if ctr.app.MinioClient == nil {
- return http.StatusInternalServerError, errors.New("Minio client not initialized")
+ return http.StatusInternalServerError, errors.New("minio client not initialized")
}
id, err := utils.GetIdParam(c, c.Param("id"))
if err != nil {
@@ -290,18 +220,18 @@ func (ctr *Controller) DeleteUpload(c *gin.Context) (int, any) {
if err != nil {
return http.StatusUnauthorized, err
}
- ressource, err := ctr.app.Services.Ressource.GetRessourceById(id)
+ node, err := ctr.app.Services.Nodes.GetNode(id)
if err != nil {
- return http.StatusInternalServerError, "failed to get ressource"
+ return http.StatusInternalServerError, "failed to get node"
}
- if ressource == nil {
- return http.StatusBadRequest, errors.New("ressource not found")
+ if node == nil {
+ return http.StatusBadRequest, errors.New("node not found")
}
- if ressource.AuthorId != userId && !utils.CheckUserRequestPermission(c, utils.ADMINISTRATOR) {
- return http.StatusUnauthorized, errors.New("you are not authorized to delete this ressource")
+ if node.UserId != userId && !utils.CheckUserRequestPermission(c, utils.ADMINISTRATOR) {
+ return http.StatusUnauthorized, errors.New("you are not authorized to delete this node")
}
- prefix := fmt.Sprintf("%d/%d", ressource.AuthorId, ressource.Id)
+ prefix := fmt.Sprintf("%d/%d", node.UserId, node.Id)
// List all objects in the bucket with the given prefix
ctx := context.Background()
objectCh := ctr.app.MinioClient.ListObjects(ctx, os.Getenv("MINIO_BUCKET"), minio.ListObjectsOptions{
@@ -319,7 +249,7 @@ func (ctr *Controller) DeleteUpload(c *gin.Context) (int, any) {
return http.StatusInternalServerError, fmt.Errorf("failed to delete object: %v", err)
}
}
- err = ctr.app.Services.Ressource.DeleteRessource(id)
+ err = ctr.app.Services.Nodes.DeleteNode(id)
if err != nil {
return http.StatusInternalServerError, err
}
diff --git a/backend/main.go b/backend/main.go
index c5625003..b9ae16a4 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -10,5 +10,5 @@ func main() {
fmt.Println("Starting server on port:", application.Config.Port)
defer application.DB.Close()
- server.Run(":" + fmt.Sprintf("%d", application.Config.Port))
+ server.Run("127.0.0.1:" + fmt.Sprintf("%d", application.Config.Port))
}
diff --git a/backend/migrations/000010_nodes.down.sql b/backend/migrations/000010_nodes.down.sql
new file mode 100644
index 00000000..e69de29b
diff --git a/backend/migrations/000010_nodes.up.sql b/backend/migrations/000010_nodes.up.sql
new file mode 100644
index 00000000..9e91310e
--- /dev/null
+++ b/backend/migrations/000010_nodes.up.sql
@@ -0,0 +1,107 @@
+-- ========================================
+-- 1. Create new nodes table
+-- ========================================
+DROP TABLE IF EXISTS `nodes`;
+
+CREATE TABLE `nodes` (
+ `id` BIGINT UNSIGNED PRIMARY KEY,
+ `user_id` BIGINT UNSIGNED NOT NULL,
+ `parent_id` BIGINT UNSIGNED NULL,
+ `name` VARCHAR(50) NOT NULL,
+ `description` VARCHAR(255) NULL,
+ `tags` VARCHAR(200) NULL,
+ `role` TINYINT NOT NULL COMMENT '1=workspace, 2=category, 3=document, 4=ressource',
+ `color` INT NULL,
+ `icon` TEXT NULL,
+ `thumbnail` TEXT NULL,
+ `theme` VARCHAR(30) NULL,
+ `accessibility` tinyint(1) NULL,
+ `display` TINYINT NULL,
+ `order` INT NULL,
+ `content` LONGTEXT NULL,
+ `content_compiled` LONGTEXT NULL,
+ `size` INT NULL,
+ `metadata` JSON NULL,
+ `created_timestamp` BIGINT NOT NULL,
+ `updated_timestamp` BIGINT NOT NULL,
+ CONSTRAINT `nodes_parent_fk` FOREIGN KEY (`parent_id`) REFERENCES `nodes` (`id`) ON DELETE CASCADE,
+ CONSTRAINT `nodes_users_fk` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
+
+
+SET FOREIGN_KEY_CHECKS=0;
+
+-- ========================================
+-- 2. Migrate categories
+-- ========================================
+
+INSERT INTO nodes (`id`, `user_id`, `parent_id`, `name`, `role`, `color`, `icon`, `order`, `created_timestamp`, `updated_timestamp`)
+SELECT
+ c.id,
+ c.author_id,
+ c.parent_id,
+ c.name,
+ CASE WHEN CAST(c.role AS UNSIGNED) = 2 THEN 1 ELSE 2 END AS role, -- workspace si role=2 sinon category
+ c.color,
+ c.icon,
+ c.order,
+ UNIX_TIMESTAMP() * 1000,
+ UNIX_TIMESTAMP() * 1000
+FROM categories c;
+
+
+-- ========================================
+-- 3. Migrate documents
+-- ========================================
+
+INSERT INTO nodes (`id`, `user_id`, `parent_id`, `name`, `description`, `tags`, `role`, `color`, `icon`, `thumbnail`, `theme`, `accessibility`, `content`, `content_compiled`, `created_timestamp`, `updated_timestamp`)
+SELECT
+ d.id,
+ d.author_id,
+ COALESCE(d.parent_id, d.category),
+ d.name,
+ d.description,
+ d.tags,
+ 3 AS role, -- document role is always 3
+ d.color,
+ d.icon,
+ d.thumbnail,
+ d.theme,
+ d.accessibility,
+ d.content_markdown,
+ d.content_html,
+ d.created_timestamp,
+ d.updated_timestamp
+FROM documents d;
+
+
+-- ========================================
+-- 4. Migrate ressources
+-- ========================================
+
+INSERT INTO nodes (`id`, `user_id`, `parent_id`, `name`, `role`, `size`, `content`, `content_compiled`, `metadata`, `created_timestamp`, `updated_timestamp`)
+SELECT
+ r.id,
+ r.author_id,
+ r.parent_id,
+ r.filename,
+ 4 AS role,
+ r.file_size,
+ r.original_path,
+ r.transformed_path,
+ JSON_OBJECT(
+ 'filetype', r.file_type
+ ),
+ r.created_timestamp,
+ r.created_timestamp
+FROM ressources r;
+
+SET FOREIGN_KEY_CHECKS=1;
+
+-- ========================================
+-- 5. Delete old tables
+-- ========================================
+
+DROP TABLE IF EXISTS `ressources`;
+DROP TABLE IF EXISTS `documents`;
+DROP TABLE IF EXISTS `categories`;
\ No newline at end of file
diff --git a/backend/migrations/000011_permissions.up.sql b/backend/migrations/000011_permissions.up.sql
new file mode 100644
index 00000000..da15cfb3
--- /dev/null
+++ b/backend/migrations/000011_permissions.up.sql
@@ -0,0 +1,9 @@
+CREATE TABLE permissions (
+ `id` BIGINT UNSIGNED PRIMARY KEY,
+ node_id BIGINT UNSIGNED NOT NULL,
+ user_id BIGINT UNSIGNED NOT NULL,
+ permission TINYINT NOT NULL DEFAULT 0,
+ `created_timestamp` BIGINT NOT NULL,
+ FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE CASCADE,
+ FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
+);
\ No newline at end of file
diff --git a/backend/models/category.model.go b/backend/models/category.model.go
deleted file mode 100644
index 3aa54f04..00000000
--- a/backend/models/category.model.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package models
-
-import "alexandrie/types"
-
-type Category struct {
- Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
- Name string `json:"name" form:"name" binding:"required,max=50"`
- Icon string `json:"icon" form:"icon" binding:"omitempty,max=30000"`
- Color *int `json:"color" form:"color" binding:"omitempty"`
- Order int `json:"order" form:"order" binding:"omitempty"`
- Role int `json:"role" form:"role" binding:"omitempty"` // 0 category; 1 workspace;
- WorkspaceId *types.Snowflake `json:"workspace_id" form:"workspace_id" binding:"omitempty"`
- ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty"`
- AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`
-}
diff --git a/backend/models/document.model.go b/backend/models/document.model.go
deleted file mode 100644
index c63128d2..00000000
--- a/backend/models/document.model.go
+++ /dev/null
@@ -1,23 +0,0 @@
-package models
-
-import "alexandrie/types"
-
-type Document struct {
- Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
- Name string `json:"name" form:"name" binding:"required,max=50"`
- Description *string `json:"description" form:"description" binding:"omitempty,max=250"`
- Tags *string `json:"tags" form:"tags" binding:"omitempty,max=250"`
- Pinned int `json:"pinned" form:"pinned" binding:"omitempty"` // 0: Not pinned; 1: Pinned; 2: Pinned to top
- Thumbnail *string `json:"thumbnail" form:"thumbnail" binding:"omitempty"`
- Theme *string `json:"theme" form:"theme" binding:"omitempty"`
- Icon *string `json:"icon" form:"icon" binding:"omitempty"`
- Color *int `json:"color" form:"color" binding:"omitempty"`
- Category *types.Snowflake `json:"category" form:"category" binding:"omitempty"`
- ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty"`
- Accessibility int `json:"accessibility" form:"accessibility" binding:"required"` // 0: Public; 1: Private; 2: Unlisted;
- ContentMarkdown *string `json:"content_markdown" form:"content_markdown"`
- ContentHtml *string `json:"content_html" form:"content_html"`
- AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`
- CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
- UpdatedTimestamp int64 `json:"updated_timestamp" form:"updated_timestamp" binding:"omitempty"`
-}
diff --git a/backend/models/node.model.go b/backend/models/node.model.go
new file mode 100644
index 00000000..47b821c7
--- /dev/null
+++ b/backend/models/node.model.go
@@ -0,0 +1,27 @@
+package models
+
+import "alexandrie/types"
+
+type Node struct {
+ // Node
+ Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
+ UserId types.Snowflake `json:"user_id" form:"user_id" binding:"omitempty"`
+ ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty"`
+ Name string `json:"name" form:"name" binding:"required,max=50"`
+ Description *string `json:"description" form:"description" binding:"omitempty,max=250"`
+ Tags *string `json:"tags" form:"tags" binding:"omitempty,max=250"`
+ Role int `json:"role" form:"role" binding:"omitempty"`
+ Color *int `json:"color" form:"color" binding:"omitempty"`
+ Icon *string `json:"icon" form:"icon" binding:"omitempty"`
+ Thumbnail *string `json:"thumbnail" form:"thumbnail" binding:"omitempty"`
+ Theme *string `json:"theme" form:"theme" binding:"omitempty"`
+ Accessibility *int `json:"accessibility" form:"accessibility" binding:"omitempty"` // 0: Public; 1: Private; 2: Unlisted;
+ Display *int `json:"display" form:"display" binding:"omitempty"`
+ Order *int `json:"order" form:"order" binding:"omitempty"` // -1 for pinned and -2 for bookmark
+ Content *string `json:"content" form:"content"`
+ ContentCompiled *string `json:"content_compiled" form:"content_compiled"`
+ Size *int64 `json:"size" form:"size" binding:"omitempty"`
+ Metadata *map[string]interface{} `json:"metadata" form:"metadata"` // <- flexible JSON
+ CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
+ UpdatedTimestamp int64 `json:"updated_timestamp" form:"updated_timestamp" binding:"omitempty"`
+}
diff --git a/backend/models/ressource.model.go b/backend/models/ressource.model.go
deleted file mode 100644
index 67c3dc66..00000000
--- a/backend/models/ressource.model.go
+++ /dev/null
@@ -1,15 +0,0 @@
-package models
-
-import "alexandrie/types"
-
-type Ressource struct {
- Id types.Snowflake `json:"id" form:"id" binding:"omitempty"`
- Filename string `json:"filename" form:"filename" binding:"required,max=50"`
- Filesize int64 `json:"filesize" form:"filesize" binding:"omitempty"`
- Filetype string `json:"filetype" form:"filetype" binding:"omitempty"`
- OriginalPath string `json:"original_path" form:"original_path" binding:"omitempty"`
- TransformedPath string `json:"transformed_path" form:"transformed_path" binding:"omitempty"`
- ParentId *types.Snowflake `json:"parent_id" form:"parent_id" binding:"omitempty"`
- AuthorId types.Snowflake `json:"author_id" form:"author_id" binding:"omitempty"`
- CreatedTimestamp int64 `json:"created_timestamp" form:"created_timestamp" binding:"omitempty"`
-}
diff --git a/backend/router/router.go b/backend/router/router.go
index 7401300e..0495dc5b 100644
--- a/backend/router/router.go
+++ b/backend/router/router.go
@@ -38,7 +38,6 @@ func InitRouter(app *app.App) *gin.Engine {
routes.Users(app, mainGroup)
routes.Auth(app, mainGroup)
routes.Uploads(app, mainGroup)
- routes.Documents(app, mainGroup)
- routes.Categories(app, mainGroup)
+ routes.Nodes(app, mainGroup)
return router
}
diff --git a/backend/router/routes/categories.go b/backend/router/routes/categories.go
deleted file mode 100644
index 4b4d673c..00000000
--- a/backend/router/routes/categories.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package routes
-
-import (
- "alexandrie/app"
- "alexandrie/controllers"
- "alexandrie/middlewares"
- "alexandrie/utils"
-
- "github.com/gin-gonic/gin"
-)
-
-func Categories(app *app.App, router *gin.RouterGroup) {
- doc := router.Group("/categories")
- docCtrl := controllers.NewCategoriesController(app)
-
- doc.GET("/:userId", middlewares.Auth(), utils.WP(docCtrl.GetCategories))
- doc.POST("", middlewares.Auth(), utils.WP(docCtrl.CreateCategory))
- doc.PUT("/:id", middlewares.Auth(), utils.WP(docCtrl.UpdateCategory))
- doc.DELETE("/:id", middlewares.Auth(), utils.WP(docCtrl.DeleteCategory))
-}
diff --git a/backend/router/routes/documents.go b/backend/router/routes/documents.go
index f55c7b3f..2ed849ad 100644
--- a/backend/router/routes/documents.go
+++ b/backend/router/routes/documents.go
@@ -9,14 +9,14 @@ import (
"github.com/gin-gonic/gin"
)
-func Documents(app *app.App, router *gin.RouterGroup) {
- doc := router.Group("/documents")
- docCtrl := controllers.NewDocumentController(app)
+func Nodes(app *app.App, router *gin.RouterGroup) {
+ doc := router.Group("/nodes")
+ docCtrl := controllers.NewNodeController(app)
- doc.GET("/public/:id", middlewares.Auth(), utils.WP(docCtrl.GetPublicDocument))
- doc.GET("/:userId", middlewares.Auth(), utils.WP(docCtrl.GetDocuments))
- doc.GET("/:userId/:id", middlewares.Auth(), utils.WP(docCtrl.GetDocument))
- doc.POST("", middlewares.Auth(), utils.WP(docCtrl.CreateDocument))
- doc.PUT("/:id", middlewares.Auth(), utils.WP(docCtrl.UpdateDocument))
- doc.DELETE("/:id", middlewares.Auth(), utils.WP(docCtrl.DeleteDocument))
+ doc.GET("/public/:id", middlewares.Auth(), utils.WP(docCtrl.GetPublicNode))
+ doc.GET("/:userId", middlewares.Auth(), utils.WP(docCtrl.GetNodes))
+ doc.GET("/:userId/:id", middlewares.Auth(), utils.WP(docCtrl.GetNode))
+ doc.POST("", middlewares.Auth(), utils.WP(docCtrl.CreateNode))
+ doc.PUT("/:id", middlewares.Auth(), utils.WP(docCtrl.UpdateNode))
+ doc.DELETE("/:id", middlewares.Auth(), utils.WP(docCtrl.DeleteNode))
}
diff --git a/backend/router/routes/ressources.go b/backend/router/routes/ressources.go
index f3b3b1a1..c6ab3b80 100644
--- a/backend/router/routes/ressources.go
+++ b/backend/router/routes/ressources.go
@@ -14,10 +14,8 @@ func Uploads(app *app.App, router *gin.RouterGroup) {
ressourcesCtrl := controllers.NewRessourceController(app)
ressources.Use(middlewares.Auth())
- ressources.GET(("/:userId"), utils.WP(ressourcesCtrl.GetAllUploads))
ressources.GET(("/backup"), utils.WP(ressourcesCtrl.GetBackup))
ressources.POST("", utils.WP(ressourcesCtrl.UploadFile))
ressources.POST("/avatar", utils.WP(ressourcesCtrl.UploadAvatar))
- ressources.PUT("/:id", utils.WP(ressourcesCtrl.UpdateUpload))
ressources.DELETE("/:id", utils.WP(ressourcesCtrl.DeleteUpload))
}
diff --git a/backend/services/category.service.go b/backend/services/category.service.go
deleted file mode 100644
index 30496e9d..00000000
--- a/backend/services/category.service.go
+++ /dev/null
@@ -1,87 +0,0 @@
-package services
-
-import (
- "alexandrie/models"
- "alexandrie/types"
- "database/sql"
-)
-
-type CategoryService interface {
- GetAllCategories(userId types.Snowflake) ([]*models.Category, error)
- GetCategory(categoryId types.Snowflake) (*models.Category, error)
- CreateCategory(category *models.Category) error
- UpdateCategory(category *models.Category) error
- DeleteCategory(categoryId types.Snowflake) error
-}
-
-func NewCategoryService(db *sql.DB) CategoryService {
- return &Service{db: db}
-}
-
-func (s *Service) GetAllCategories(userId types.Snowflake) ([]*models.Category, error) {
- var categories = make([]*models.Category, 0)
- rows, err := s.db.Query("SELECT * FROM categories WHERE author_id = ? ORDER BY `order`", userId)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- for rows.Next() {
- var category models.Category
- if err := rows.Scan(&category.Id, &category.Name, &category.Icon, &category.Color, &category.Order, &category.Role, &category.WorkspaceId, &category.ParentId, &category.AuthorId); err != nil {
- return nil, err
- }
- categories = append(categories, &category)
- }
- return categories, nil
-}
-
-func (s *Service) GetCategory(categoryId types.Snowflake) (*models.Category, error) {
- var category models.Category
- err := s.db.QueryRow("SELECT * FROM categories WHERE id = ?", categoryId).Scan(
- &category.Id,
- &category.Name,
- &category.Icon,
- &category.Color,
- &category.Order,
- &category.Role,
- &category.WorkspaceId,
- &category.ParentId,
- &category.AuthorId)
- if err != nil {
- return nil, err
- }
- return &category, nil
-}
-
-func (s *Service) CreateCategory(category *models.Category) error {
- _, err := s.db.Exec("INSERT INTO categories (id, name, icon, color, `order`, role, workspace_id, parent_id, author_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
- category.Id,
- category.Name,
- category.Icon,
- category.Color,
- category.Order,
- category.Role,
- category.WorkspaceId,
- category.ParentId,
- category.AuthorId)
- return err
-}
-
-func (s *Service) UpdateCategory(category *models.Category) error {
- _, err := s.db.Exec("UPDATE categories SET name = ?, icon = ?, color = ?, `order` = ?, role = ?, workspace_id = ?, parent_id = ? WHERE id = ?",
- category.Name,
- category.Icon,
- category.Color,
- category.Order,
- category.Role,
- category.WorkspaceId,
- category.ParentId,
- category.Id)
- return err
-}
-
-func (s *Service) DeleteCategory(categoryId types.Snowflake) error {
- _, err := s.db.Exec("DELETE FROM categories WHERE id = ?", categoryId)
- return err
-}
diff --git a/backend/services/document.service.go b/backend/services/document.service.go
deleted file mode 100644
index bdbfd57e..00000000
--- a/backend/services/document.service.go
+++ /dev/null
@@ -1,184 +0,0 @@
-package services
-
-import (
- "alexandrie/models"
- "alexandrie/types"
- "database/sql"
-)
-
-type DocumentService interface {
- GetAllDocuments(userId types.Snowflake) ([]*models.Document, error)
- GetAllDocumentBackup(author_id types.Snowflake) ([]*models.Document, error)
- GetPublicDocument(documentId types.Snowflake) (*models.Document, error)
- GetDocument(documentId types.Snowflake) (*models.Document, error)
- CreateDocument(document *models.Document) error
- UpdateDocument(document *models.Document) error
- DeleteDocument(documentId types.Snowflake) error
-}
-
-func NewDocumentService(db *sql.DB) DocumentService {
- return &Service{db: db}
-}
-
-func (s *Service) GetAllDocuments(userId types.Snowflake) ([]*models.Document, error) {
- var documents = make([]*models.Document, 0)
- rows, err := s.db.Query("SELECT id, name, description, tags, pinned, theme, icon, color, category, parent_id, accessibility, author_id, created_timestamp, updated_timestamp FROM documents WHERE author_id = ? ORDER BY pinned DESC, name", userId)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- for rows.Next() {
- var document models.Document
- if err := rows.Scan(
- &document.Id,
- &document.Name,
- &document.Description,
- &document.Tags,
- &document.Pinned,
- &document.Theme,
- &document.Icon,
- &document.Color,
- &document.Category,
- &document.ParentId,
- &document.Accessibility,
- &document.AuthorId,
- &document.CreatedTimestamp,
- &document.UpdatedTimestamp); err != nil {
- return nil, err
- }
- documents = append(documents, &document)
- }
- return documents, nil
-}
-
-func (s *Service) GetAllDocumentBackup(author_id types.Snowflake) ([]*models.Document, error) {
- var documents = make([]*models.Document, 0)
- rows, err := s.db.Query("SELECT id, name, description, tags, pinned, thumbnail, theme, icon, color, category, parent_id, accessibility, content_markdown, content_html, author_id, created_timestamp, updated_timestamp FROM documents WHERE author_id = ?", author_id)
- if err != nil {
- return nil, err
- }
- for rows.Next() {
- var document models.Document
- if err := rows.Scan(
- &document.Id,
- &document.Name,
- &document.Description,
- &document.Tags,
- &document.Pinned,
- &document.Thumbnail,
- &document.Theme,
- &document.Icon,
- &document.Color,
- &document.Category,
- &document.ParentId,
- &document.Accessibility,
- &document.ContentMarkdown,
- &document.ContentHtml,
- &document.AuthorId,
- &document.CreatedTimestamp,
- &document.UpdatedTimestamp); err != nil {
- return nil, err
- }
- documents = append(documents, &document)
- }
- return documents, nil
-}
-
-func (s *Service) GetPublicDocument(documentId types.Snowflake) (*models.Document, error) {
- var document models.Document
- err := s.db.QueryRow("SELECT id, name, description, tags, pinned, thumbnail, theme, icon, color, category, parent_id, accessibility, content_markdown, content_html, author_id, created_timestamp, updated_timestamp FROM documents WHERE id = ? AND accessibility = 3", documentId).Scan(
- &document.Id,
- &document.Name,
- &document.Description,
- &document.Tags,
- &document.Pinned,
- &document.Thumbnail,
- &document.Theme,
- &document.Icon,
- &document.Color,
- &document.Category,
- &document.ParentId,
- &document.Accessibility,
- &document.ContentMarkdown,
- &document.ContentHtml,
- &document.AuthorId,
- &document.CreatedTimestamp,
- &document.UpdatedTimestamp)
- if err != nil {
- return nil, err
- }
- return &document, nil
-}
-
-func (s *Service) GetDocument(documentId types.Snowflake) (*models.Document, error) {
- var document models.Document
- err := s.db.QueryRow("SELECT id, name, description, tags, pinned, thumbnail, theme, icon, color, category, parent_id, accessibility, content_markdown, content_html, author_id, created_timestamp, updated_timestamp FROM documents WHERE id = ?", documentId).Scan(
- &document.Id,
- &document.Name,
- &document.Description,
- &document.Tags,
- &document.Pinned,
- &document.Thumbnail,
- &document.Theme,
- &document.Icon,
- &document.Color,
- &document.Category,
- &document.ParentId,
- &document.Accessibility,
- &document.ContentMarkdown,
- &document.ContentHtml,
- &document.AuthorId,
- &document.CreatedTimestamp,
- &document.UpdatedTimestamp)
- if err != nil {
- return nil, err
- }
- return &document, nil
-}
-
-func (s *Service) CreateDocument(document *models.Document) error {
- _, err := s.db.Exec("INSERT INTO documents (id, name, description, tags, pinned, thumbnail, theme, icon, color, category, parent_id, accessibility, content_markdown, content_html, author_id, created_timestamp, updated_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
- document.Id,
- document.Name,
- document.Description,
- document.Tags,
- document.Pinned,
- document.Thumbnail,
- document.Theme,
- document.Icon,
- document.Color,
- document.Category,
- document.ParentId,
- document.Accessibility,
- document.ContentMarkdown,
- document.ContentHtml,
- document.AuthorId,
- document.CreatedTimestamp,
- document.UpdatedTimestamp)
- return err
-}
-
-func (s *Service) UpdateDocument(document *models.Document) error {
- _, err := s.db.Exec("UPDATE documents SET name = ?, description = ?, tags = ?, pinned = ?, thumbnail = ?, theme = ?, icon = ?, color = ?, category = ?, parent_id = ?, accessibility = ?, content_markdown = ?, content_html = ? WHERE id = ?",
- document.Name,
- document.Description,
- document.Tags,
- document.Pinned,
- document.Thumbnail,
- document.Theme,
- document.Icon,
- document.Color,
- document.Category,
- document.ParentId,
- document.Accessibility,
- document.ContentMarkdown,
- document.ContentHtml,
- document.Id)
- return err
-}
-
-func (s *Service) DeleteDocument(documentId types.Snowflake) error {
- _, err := s.db.Exec("DELETE FROM documents WHERE id = ?", documentId)
- return err
-}
diff --git a/backend/services/node.service.go b/backend/services/node.service.go
new file mode 100644
index 00000000..499b54f3
--- /dev/null
+++ b/backend/services/node.service.go
@@ -0,0 +1,215 @@
+package services
+
+import (
+ "alexandrie/models"
+ "alexandrie/types"
+ "database/sql"
+)
+
+type NodeService interface {
+ GetAllNodes(userId types.Snowflake) ([]*models.Node, error)
+ GetAllNodeBackup(user_id types.Snowflake) ([]*models.Node, error)
+ GetUserUploadsSize(userId types.Snowflake) (int64, error)
+ GetPublicNode(nodeId types.Snowflake) (*models.Node, error)
+ GetNode(nodeId types.Snowflake) (*models.Node, error)
+ CreateNode(node *models.Node) error
+ UpdateNode(node *models.Node) error
+ DeleteNode(nodeId types.Snowflake) error
+}
+
+func NewNodeService(db *sql.DB) NodeService {
+ return &Service{db: db}
+}
+
+func (s *Service) GetAllNodes(userId types.Snowflake) ([]*models.Node, error) {
+ var nodes = make([]*models.Node, 0)
+ rows, err := s.db.Query("SELECT `id`, `user_id`, `parent_id`, `name`, `description`, `tags`, `role`, `color`, `icon`, `theme`, `accessibility`, `display`, `order`, `created_timestamp`, `updated_timestamp` FROM nodes WHERE user_id = ? ORDER BY `order` DESC, name", userId)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ for rows.Next() {
+ var node models.Node
+ if err := rows.Scan(
+ &node.Id,
+ &node.UserId,
+ &node.ParentId,
+ &node.Name,
+ &node.Description,
+ &node.Tags,
+ &node.Role,
+ &node.Color,
+ &node.Icon,
+ &node.Theme,
+ &node.Accessibility,
+ &node.Display,
+ &node.Order,
+ &node.CreatedTimestamp,
+ &node.UpdatedTimestamp,
+ ); err != nil {
+ return nil, err
+ }
+ nodes = append(nodes, &node)
+ }
+ return nodes, nil
+}
+
+func (s *Service) GetAllNodeBackup(user_id types.Snowflake) ([]*models.Node, error) {
+ var nodes = make([]*models.Node, 0)
+ rows, err := s.db.Query("SELECT `id`, user_id, parent_id, name, description, tags, role, color, icon, thumbnail, theme, accessibility, display, order, content, content_compiled, size, metadata, created_timestamp, updated_timestamp FROM nodes WHERE user_id = ?", user_id)
+ if err != nil {
+ return nil, err
+ }
+ for rows.Next() {
+ var node models.Node
+ if err := rows.Scan(
+ &node.Id,
+ &node.UserId,
+ &node.ParentId,
+ &node.Name,
+ &node.Description,
+ &node.Tags,
+ &node.Role,
+ &node.Color,
+ &node.Icon,
+ &node.Thumbnail,
+ &node.Theme,
+ &node.Accessibility,
+ &node.Display,
+ &node.Order,
+ &node.Content,
+ &node.ContentCompiled,
+ &node.Size,
+ &node.Metadata,
+ &node.CreatedTimestamp,
+ &node.UpdatedTimestamp); err != nil {
+ return nil, err
+ }
+ nodes = append(nodes, &node)
+ }
+ return nodes, nil
+}
+
+func (s *Service) GetUserUploadsSize(userId types.Snowflake) (int64, error) {
+ var totalSize *int64
+ err := s.db.QueryRow("SELECT SUM(file_size) FROM nodes WHERE user_id = ?", userId).Scan(&totalSize)
+ if err != nil {
+ return 0, err
+ }
+ if totalSize == nil {
+ return 0, nil
+ }
+ return *totalSize, nil
+}
+
+func (s *Service) GetPublicNode(nodeId types.Snowflake) (*models.Node, error) {
+ var node models.Node
+ err := s.db.QueryRow("SELECT `id`, `user_id`, `parent_id`, `name`, `description`, `tags`, `role`, `color`, `icon`, `thumbnail`, `theme`, `accessibility`, `display`, `order`, `content`, `content_compiled`, `size`, `metadata`, `created_timestamp`, `updated_timestamp` FROM nodes WHERE id = ? AND accessibility = 3", nodeId).Scan(
+ &node.Id,
+ &node.UserId,
+ &node.ParentId,
+ &node.Name,
+ &node.Description,
+ &node.Tags,
+ &node.Role,
+ &node.Color,
+ &node.Icon,
+ &node.Thumbnail,
+ &node.Theme,
+ &node.Accessibility,
+ &node.Display,
+ &node.Order,
+ &node.Content,
+ &node.ContentCompiled,
+ &node.Size,
+ &node.Metadata,
+ &node.CreatedTimestamp,
+ &node.UpdatedTimestamp)
+ if err != nil {
+ return nil, err
+ }
+ return &node, nil
+}
+
+func (s *Service) GetNode(nodeId types.Snowflake) (*models.Node, error) {
+ var node models.Node
+ err := s.db.QueryRow("SELECT `id`, `user_id`, `parent_id`, `name`, `description`, `tags`, `role`, `color`, `icon`, `thumbnail`, `theme`, `accessibility`, `display`, `order`, `content`, `content_compiled`, `size`, `metadata`, `created_timestamp`, `updated_timestamp` FROM nodes WHERE id = ?", nodeId).Scan(
+ &node.Id,
+ &node.UserId,
+ &node.ParentId,
+ &node.Name,
+ &node.Description,
+ &node.Tags,
+ &node.Role,
+ &node.Color,
+ &node.Icon,
+ &node.Thumbnail,
+ &node.Theme,
+ &node.Accessibility,
+ &node.Display,
+ &node.Order,
+ &node.Content,
+ &node.ContentCompiled,
+ &node.Size,
+ &node.Metadata,
+ &node.CreatedTimestamp,
+ &node.UpdatedTimestamp)
+ if err != nil {
+ return nil, err
+ }
+ return &node, nil
+}
+
+func (s *Service) CreateNode(node *models.Node) error {
+ _, err := s.db.Exec("INSERT INTO nodes (`id`, `user_id`, `parent_id`, `name`, `description`, `tags`, `role`, `color`, `icon`, `thumbnail`, `theme`, `accessibility`, `display`, `order`, `content`, `content_compiled`, `size`, `metadata`, `created_timestamp`, `updated_timestamp`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ node.Id,
+ node.UserId,
+ node.ParentId,
+ node.Name,
+ node.Description,
+ node.Tags,
+ node.Role,
+ node.Color,
+ node.Icon,
+ node.Thumbnail,
+ node.Theme,
+ node.Accessibility,
+ node.Display,
+ node.Order,
+ node.Content,
+ node.ContentCompiled,
+ node.Size,
+ node.Metadata,
+ node.CreatedTimestamp,
+ node.UpdatedTimestamp)
+ return err
+}
+
+func (s *Service) UpdateNode(node *models.Node) error {
+ _, err := s.db.Exec("UPDATE nodes SET `parent_id` = ?, `name` = ?, `description` = ?, `tags` = ?, `role` = ?, `color` = ?, `icon` = ?, `thumbnail` = ?, `theme` = ?, `accessibility` = ?, `display` = ?, `order` = ?, `content` = ?, `content_compiled` = ?, `size` = ?, `metadata` = ?, `updated_timestamp` = ? WHERE id = ?",
+ node.ParentId,
+ node.Name,
+ node.Description,
+ node.Tags,
+ node.Role,
+ node.Color,
+ node.Icon,
+ node.Thumbnail,
+ node.Theme,
+ node.Accessibility,
+ node.Display,
+ node.Order,
+ node.Content,
+ node.ContentCompiled,
+ node.Size,
+ node.Metadata,
+ node.UpdatedTimestamp,
+ node.Id)
+ return err
+}
+
+func (s *Service) DeleteNode(nodeId types.Snowflake) error {
+ _, err := s.db.Exec("DELETE FROM nodes WHERE `id` = ?", nodeId)
+ return err
+}
diff --git a/backend/services/ressource.service.go b/backend/services/ressource.service.go
deleted file mode 100644
index cc160ef6..00000000
--- a/backend/services/ressource.service.go
+++ /dev/null
@@ -1,80 +0,0 @@
-package services
-
-import (
- "alexandrie/models"
- "alexandrie/types"
- "database/sql"
-)
-
-type RessourceService interface {
- GetAllUploadsByUserId(userId types.Snowflake) ([]*models.Ressource, error)
- GetRessourceById(id types.Snowflake) (*models.Ressource, error)
- GetUserUploadsSize(userId types.Snowflake) (int64, error)
- CreateRessource(ressource *models.Ressource) (*models.Ressource, error)
- UpdateRessource(ressource *models.Ressource) (*models.Ressource, error)
- DeleteRessource(id types.Snowflake) error
-}
-
-func NewRessourceService(db *sql.DB) RessourceService {
- return &Service{db: db}
-}
-
-func (s *Service) GetAllUploadsByUserId(userId types.Snowflake) ([]*models.Ressource, error) {
- var ressources = make([]*models.Ressource, 0)
- rows, err := s.db.Query("SELECT * from ressources WHERE author_id = ? ORDER BY created_timestamp DESC", userId)
- if err != nil {
- return nil, err
- }
- defer rows.Close()
-
- for rows.Next() {
- var ressource models.Ressource
- if err := rows.Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.ParentId, &ressource.AuthorId, &ressource.CreatedTimestamp); err != nil {
- return nil, err
- }
- ressources = append(ressources, &ressource)
- }
- return ressources, nil
-}
-
-func (s *Service) GetRessourceById(id types.Snowflake) (*models.Ressource, error) {
- var ressource models.Ressource
- err := s.db.QueryRow("SELECT * FROM ressources WHERE id = ?", id).Scan(&ressource.Id, &ressource.Filename, &ressource.Filesize, &ressource.Filetype, &ressource.OriginalPath, &ressource.TransformedPath, &ressource.ParentId, &ressource.AuthorId, &ressource.CreatedTimestamp)
- if err != nil {
- return nil, err
- }
- return &ressource, nil
-}
-
-func (s *Service) GetUserUploadsSize(userId types.Snowflake) (int64, error) {
- var totalSize *int64
- err := s.db.QueryRow("SELECT SUM(file_size) FROM ressources WHERE author_id = ?", userId).Scan(&totalSize)
- if err != nil {
- return 0, err
- }
- if totalSize == nil {
- return 0, nil
- }
- return *totalSize, nil
-}
-
-func (s *Service) CreateRessource(ressource *models.Ressource) (*models.Ressource, error) {
- _, err := s.db.Exec("INSERT INTO ressources (id, filename, file_size, file_type, original_path, transformed_path, parent_id, author_id, created_timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", ressource.Id, ressource.Filename, ressource.Filesize, ressource.Filetype, ressource.OriginalPath, ressource.TransformedPath, ressource.ParentId, ressource.AuthorId, ressource.CreatedTimestamp)
- if err != nil {
- return nil, err
- }
- return ressource, nil
-}
-
-func (s *Service) UpdateRessource(ressource *models.Ressource) (*models.Ressource, error) {
- _, err := s.db.Exec("UPDATE ressources SET filename = ?, file_size = ?, file_type = ?, original_path = ?, transformed_path = ?, parent_id = ?, author_id = ?, created_timestamp = ? WHERE id = ?", ressource.Filename, ressource.Filesize, ressource.Filetype, ressource.OriginalPath, ressource.TransformedPath, ressource.ParentId, ressource.AuthorId, ressource.CreatedTimestamp, ressource.Id)
- if err != nil {
- return nil, err
- }
- return ressource, nil
-}
-
-func (s *Service) DeleteRessource(id types.Snowflake) error {
- _, err := s.db.Exec("DELETE FROM ressources WHERE id = ?", id)
- return err
-}
diff --git a/frontend/app/components/AppColorPicker.vue b/frontend/app/components/AppColorPicker.vue
index 163b3ee4..fd9a2339 100644
--- a/frontend/app/components/AppColorPicker.vue
+++ b/frontend/app/components/AppColorPicker.vue
@@ -75,30 +75,6 @@ function selectColor(color: number) {
outline-offset: 2px;
}
-.hint-wrapper {
- position: relative;
- display: inline-block;
- margin-left: 0.25rem;
-}
-
-.hint-tooltip {
- position: absolute;
- top: 100%;
- left: 50%;
- z-index: 100;
- display: none;
- padding: 0.4rem 0.6rem;
- border-radius: 0.4rem;
- font-size: 0.75rem;
- color: white;
- background-color: #1f2937;
- box-shadow: 0 2px 8px var(--shadow);
- margin-top: 0.4rem;
- text-transform: capitalize;
- transform: translateX(-50%);
- white-space: nowrap;
-}
-
.color-option:hover .hint-tooltip {
display: block;
}
diff --git a/frontend/app/components/AppRadio.vue b/frontend/app/components/AppRadio.vue
index 37bc3408..a159d615 100644
--- a/frontend/app/components/AppRadio.vue
+++ b/frontend/app/components/AppRadio.vue
@@ -7,11 +7,11 @@
<script setup lang="ts">
const props = defineProps<{
items: Array<{ id: number | string; label: string }>;
- modelValue: number | string | null;
+ modelValue: number | string | null | undefined;
}>();
const emit = defineEmits<{
- (e: 'update:modelValue', value: number | string | null): void;
+ (e: 'update:modelValue', value: number | string | null | undefined): void;
}>();
const selected = ref(props.modelValue);
diff --git a/frontend/app/components/CommandCenter/AdvancedSearchTab.vue b/frontend/app/components/CommandCenter/AdvancedSearchTab.vue
index bae27982..3754aa0d 100644
--- a/frontend/app/components/CommandCenter/AdvancedSearchTab.vue
+++ b/frontend/app/components/CommandCenter/AdvancedSearchTab.vue
@@ -111,7 +111,7 @@
<script setup lang="ts">
import SearchResultsList from './SearchResultsList.vue';
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
const props = defineProps<{
query: string;
selectedIndex: number;
@@ -129,8 +129,8 @@ const showFilters = ref(true);
const showSuggestions = ref(false);
const selectedSuggestionIndex = ref(0);
-const documentStore = useDocumentsStore();
-const categoriesTree = new TreeStructure(useSidebarTree().categories.value).generateTree().filter(i => i.data.type === 'category' && i.data.role == 2);
+const documentStore = useNodesStore();
+const categoriesTree = new TreeStructure(useSidebarTree().nodes.value.filter(n => n.data.role <= 2)).generateTree().filter(i => i.data.role === 2);
const filteredTagSuggestions = computed(() => {
if (!tagInput.value) return [];
@@ -226,9 +226,8 @@ function clearFilters() {
selectedCategory.value = '';
}
-function getDocumentIcon(doc: Document) {
- if (doc.pinned === 1) return 'pin';
- if (doc.pinned === 2) return 'pin';
+function getDocumentIcon(doc: Node) {
+ if (doc.order ?? 0 < 0) return 'pin';
return 'files';
}
diff --git a/frontend/app/components/CommandCenter/QuickSearchTab.vue b/frontend/app/components/CommandCenter/QuickSearchTab.vue
index 0467acf6..45ae6e63 100644
--- a/frontend/app/components/CommandCenter/QuickSearchTab.vue
+++ b/frontend/app/components/CommandCenter/QuickSearchTab.vue
@@ -18,7 +18,7 @@ const props = defineProps<{
searchQuery: string;
selectedIndex: number;
}>();
-const documentStore = useDocumentsStore();
+const documentStore = useNodesStore();
defineEmits<{ updateSelectedIndex: [index: number] }>();
diff --git a/frontend/app/components/CommandCenter/SearchResultsList.vue b/frontend/app/components/CommandCenter/SearchResultsList.vue
index 56b61e15..e57f3676 100644
--- a/frontend/app/components/CommandCenter/SearchResultsList.vue
+++ b/frontend/app/components/CommandCenter/SearchResultsList.vue
@@ -31,9 +31,9 @@
</template>
<script setup lang="ts">
-import type { Item } from './types';
+import type { ItemCommand } from './types';
const props = defineProps<{
- items: Item[];
+ items: ItemCommand[];
selectedIndex: number;
query: string;
emptyIcon: string;
diff --git a/frontend/app/components/CommandCenter/index.vue b/frontend/app/components/CommandCenter/index.vue
index 7807930c..00bfe889 100644
--- a/frontend/app/components/CommandCenter/index.vue
+++ b/frontend/app/components/CommandCenter/index.vue
@@ -61,7 +61,7 @@ import TabNavigation from './TabNavigation.vue';
import QuickSearchTab from './QuickSearchTab.vue';
import AdvancedSearchTab from './AdvancedSearchTab.vue';
import { useModal, Modal } from '~/composables/ModalBus';
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
const router = useRouter();
const isOpen = ref(false);
@@ -156,7 +156,7 @@ function handleQuickSelect() {
}
}
-function handleDocumentSelect(document: Document) {
+function handleDocumentSelect(document: Node) {
navigateTo(`/dashboard/docs/${document.id}`);
closeSearch();
}
diff --git a/frontend/app/components/CommandCenter/types.ts b/frontend/app/components/CommandCenter/types.ts
index 799a9147..e01a898d 100644
--- a/frontend/app/components/CommandCenter/types.ts
+++ b/frontend/app/components/CommandCenter/types.ts
@@ -1,4 +1,4 @@
-export interface Item {
+export interface ItemCommand {
id: string;
icon: string;
title: string;
diff --git a/frontend/app/components/DocumentCard.vue b/frontend/app/components/DocumentCard.vue
index c1708347..0e5959e3 100644
--- a/frontend/app/components/DocumentCard.vue
+++ b/frontend/app/components/DocumentCard.vue
@@ -3,7 +3,7 @@
<div class="top">
<div class="header">
<span style="display: flex">
- <Icon :name="category?.icon || 'files'" :class="`category-icon ${getAppColor(category?.color as number, true)}`" />
+ <Icon :name="category?.icon || 'files'" :class="`category-icon ${getAppColor(document.color || category?.color as number, true)}`" />
<NuxtLink :to="`/dashboard/docs/${document.id}`" class="document-title">{{ document.name }}</NuxtLink>
</span>
<DocumentDotMenu :document="document" :user="user" @delete="deleteDoc" />
@@ -33,12 +33,12 @@
</template>
<script setup lang="ts">
-import type { Document } from '@/stores';
+import type { Node } from '@/stores';
import DeleteDocumentModal from '~/pages/dashboard/docs/_modals/DeleteDocumentModal.vue';
-const props = defineProps<{ document: Document }>();
-const categoriesStore = useCategoriesStore();
-const category = computed(() => categoriesStore.getById(props.document.category || ''));
+const props = defineProps<{ document: Node }>();
+const nodesStore = useNodesStore();
+const category = computed(() => nodesStore.getById(props.document.parent_id || ''));
const user = useUserStore().user;
const deleteDoc = () => useModal().add(new Modal(shallowRef(DeleteDocumentModal), { props: { documentId: props.document.id } }));
</script>
diff --git a/frontend/app/components/DocumentDotMenu.vue b/frontend/app/components/DocumentDotMenu.vue
index 4c34e0d2..893d9ae3 100644
--- a/frontend/app/components/DocumentDotMenu.vue
+++ b/frontend/app/components/DocumentDotMenu.vue
@@ -6,7 +6,9 @@
>
<button @click="edit"><Icon fill="var(--font-color)" name="edit_page" /> Edit</button>
<button @click="copyLink"><Icon fill="var(--font-color)" name="link" /> Copy link</button>
- <button @click="pin"><Icon fill="var(--font-color)" :name="document.pinned ? 'pin_off' : 'pin'" /> {{ document.pinned ? 'Unpin' : 'Pin' }}</button>
+ <button @click="pin">
+ <Icon fill="var(--font-color)" :name="document.order === -1 ? 'pin_off' : 'pin'" /> {{ document.order === -1 ? 'Unpin' : 'Pin' }}
+ </button>
<hr style="margin: 2px 0" />
<button @click="emitDelete"><Icon name="delete" fill="red" /> Delete</button>
<hr style="margin: 2px 0" />
@@ -20,10 +22,10 @@
</template>
<script setup lang="ts">
-import type { Document, User } from '~/stores';
+import type { Node, User } from '~/stores';
const dotMenu = ref();
-const props = defineProps<{ document: Document; user?: User }>();
+const props = defineProps<{ document: Node; user?: User }>();
const emit = defineEmits<{
(e: 'open' | 'close' | 'edit' | 'rename' | 'delete'): void;
}>();
@@ -49,7 +51,7 @@ const emitDelete = () => {
emit('delete');
};
const pin = async () => {
- await useDocumentsStore().update({ ...props.document, pinned: props.document.pinned === 1 ? 0 : 1 });
+ await useNodesStore().update({ ...props.document });
};
</script>
diff --git a/frontend/app/components/DocumentLine.vue b/frontend/app/components/DocumentLine.vue
index 369f5af5..0fed55d8 100644
--- a/frontend/app/components/DocumentLine.vue
+++ b/frontend/app/components/DocumentLine.vue
@@ -3,7 +3,7 @@
<header style="display: flex; justify-content: space-between">
<div style="display: flex; align-items: center; justify-content: flex-start">
<div>
- <Icon :name="category?.icon || 'files'" :class="`category-icon ${getAppColor(category?.color as number, true)}`" />
+ <Icon :name="document.icon || category?.icon || 'files'" :class="`category-icon ${getAppColor(document.color || category?.color as number, true)}`" />
</div>
<NuxtLink :to="`/dashboard/docs/${document.id}`" class="document-title">{{ document.name }}</NuxtLink>
</div>
@@ -25,11 +25,11 @@
</template>
<script setup lang="ts">
-import type { Document } from '@/stores';
+import type { Node } from '@/stores';
import DeleteDocumentModal from '~/pages/dashboard/docs/_modals/DeleteDocumentModal.vue';
-const props = defineProps<{ document: Document }>();
-const categoriesStore = useCategoriesStore();
-const category = computed(() => categoriesStore.getById(props.document.category || ''));
+const props = defineProps<{ document: Node }>();
+const categoriesStore = useNodesStore();
+const category = computed(() => categoriesStore.getById(props.document.parent_id || ''));
const user = useUserStore().user;
const deleteDoc = () => useModal().add(new Modal(shallowRef(DeleteDocumentModal), { props: { documentId: props.document.id } }));
</script>
diff --git a/frontend/app/components/DocumentsGrid.vue b/frontend/app/components/DocumentsGrid.vue
index 15bb4d38..344b439b 100644
--- a/frontend/app/components/DocumentsGrid.vue
+++ b/frontend/app/components/DocumentsGrid.vue
@@ -5,8 +5,8 @@
</template>
<script setup lang="ts">
-import type { Document } from '@/stores';
-defineProps<{ documents: Document[] }>();
+import type { Node } from '@/stores';
+defineProps<{ documents: Node[] }>();
</script>
<style scoped lang="scss">
diff --git a/frontend/app/components/MarkdownEditor/EditorPreferences.vue b/frontend/app/components/MarkdownEditor/EditorPreferences.vue
index 95a0a384..ea8e43d9 100644
--- a/frontend/app/components/MarkdownEditor/EditorPreferences.vue
+++ b/frontend/app/components/MarkdownEditor/EditorPreferences.vue
@@ -39,25 +39,4 @@ textarea {
font-size: 14px;
resize: none;
}
-
-.public-info {
- padding: 0 5px;
- border-radius: 7px;
- margin-bottom: 10px;
-}
-
-.info-text {
- margin: 5px 0;
- font-size: 14px;
- color: var(--font-color-light);
-}
-
-.public-link {
- display: flex;
- color: var(--primary);
- align-items: flex-end;
- gap: 2px;
- text-decoration: underline;
- word-break: break-all;
-}
</style>
diff --git a/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue b/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue
index 6a65561a..575a3661 100644
--- a/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue
+++ b/frontend/app/components/MarkdownEditor/ImageSelectorModal.vue
@@ -7,10 +7,10 @@
<div class="modal-content">
<div class="images-grid">
<div v-for="image in filteredImages" :key="image.id" class="image-item" @click="selectImage(image)">
- <img :src="CDN + `/${useUserStore().user?.id}/` + image.transformed_path" :alt="image.filename" class="image-preview" @error="handleImageError" />
+ <img :src="CDN + `/${useUserStore().user?.id}/` + image.content_compiled" :alt="image.name" class="image-preview" @error="handleImageError" />
<div class="image-info">
- <span class="image-name">{{ image.filename }}</span>
- <span class="image-size">{{ formatFileSize(image.filesize) }}</span>
+ <span class="image-name">{{ image.name }}</span>
+ <span class="image-size">{{ formatFileSize(image.size ?? 0) }}</span>
</div>
</div>
</div>
@@ -28,7 +28,7 @@
<script setup lang="ts">
import EditorAppHeader from './EditorAppHeader.vue';
-import { useRessourcesStore, type Ressource } from '~/stores';
+import type { Node } from '~/stores';
const props = defineProps<{
onImageSelect: (imageUrl: string, altText: string) => void;
@@ -38,17 +38,17 @@ const emit = defineEmits<{
(e: 'close'): void;
}>();
-const ressourcesStore = useRessourcesStore();
+const nodesStore = useNodesStore();
const searchQuery = ref('');
-const images = ref<Ressource[]>([]);
+const images = ref<Node[]>([]);
const loading = ref(false);
const filteredImages = computed(() => {
if (!searchQuery.value.trim()) {
- return images.value.filter(img => isImageFile(img.filetype));
+ return images.value.filter(img => isImageFile(img.metadata?.filetype as string));
}
- return images.value.filter(img => isImageFile(img.filetype) && img.filename.toLowerCase().includes(searchQuery.value.toLowerCase()));
+ return images.value.filter(img => isImageFile(img.metadata?.filetype as string) && img.name.toLowerCase().includes(searchQuery.value.toLowerCase()));
});
const isImageFile = (filetype: string): boolean => {
@@ -68,9 +68,9 @@ const handleImageError = (event: Event) => {
img.style.display = 'none';
};
-const selectImage = (image: Ressource) => {
- const imageUrl = CDN + `/${useUserStore().user?.id}/` + image.transformed_path;
- const altText = image.filename.replace(/\.[^/.]+$/, '');
+const selectImage = (image: Node) => {
+ const imageUrl = CDN + `/${useUserStore().user?.id}/` + image.content_compiled;
+ const altText = image.name.replace(/\.[^/.]+$/, '');
props.onImageSelect(imageUrl, altText);
emit('close');
};
@@ -82,8 +82,7 @@ const closeModal = () => {
const loadImages = async () => {
try {
loading.value = true;
- await ressourcesStore.fetch();
- images.value = ressourcesStore.getAll;
+ images.value = nodesStore.getAll.filter(i => i.role === 4);
} catch (error) {
console.error('Failed to load images:', error);
} finally {
diff --git a/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue b/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
index 97374149..0b54fe8a 100644
--- a/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
+++ b/frontend/app/components/MarkdownEditor/LazyMarkdownEditor.vue
@@ -15,7 +15,7 @@
ref="markdownPreview"
:class="['markdown-preview', `${usePreferences().get('theme').value}-theme`]"
style="position: relative"
- v-html="document.content_html"
+ v-html="document.content_compiled"
/>
</div>
</div>
@@ -36,13 +36,13 @@ import GridOrganizationModal from './GridOrganizationModal.vue';
import ColorPickerModal from './ColorPickerModal.vue';
import compile from '~/helpers/markdown';
-import type { Document, Ressource } from '~/stores';
+import type { Node } from '~/stores';
import { useModal, Modal } from '~/composables/ModalBus';
const resourcesStore = useRessourcesStore();
const preferencesStore = usePreferences();
-const props = defineProps<{ doc?: Partial<Document>; minimal?: boolean }>();
+const props = defineProps<{ doc?: Partial<Node>; minimal?: boolean }>();
const emit = defineEmits(['save', 'exit', 'autoSave']);
const editorContainer = ref<HTMLDivElement>();
@@ -50,9 +50,9 @@ const markdownPreview = ref<HTMLDivElement>();
const editorView = ref<EditorView | null>(null);
const showPreview = ref(false);
-const document = ref<Partial<Document>>({
+const document = ref<Partial<Node>>({
...props.doc,
- content_html: compile(props.doc?.content_markdown || ''),
+ content_compiled: compile(props.doc?.content || ''),
});
function exec(action: string, payload?: string) {
@@ -237,8 +237,8 @@ const fileUploadHandler = EditorView.domEventHandlers({
if (!file) return;
const body = new FormData();
body.append('file', file);
- resourcesStore.post(body).then(result => {
- const url = `${CDN}/${(result as Ressource).author_id}/${(result as Ressource).transformed_path}`;
+ resourcesStore.post(body).then((result: Node) => {
+ const url = `${CDN}/${(result as Node).user_id}/${(result as Node).content_compiled}`;
exec('insertText', `![${file.name}](${url})\n`);
});
}
@@ -253,8 +253,8 @@ const fileUploadHandler = EditorView.domEventHandlers({
if (!file) return;
const body = new FormData();
body.append('file', file);
- resourcesStore.post(body).then(result => {
- const url = `${CDN}/${(result as Ressource).author_id}/${(result as Ressource).transformed_path}`;
+ resourcesStore.post(body).then((result: Node) => {
+ const url = `${CDN}/${(result as Node).user_id}/${(result as Node).content_compiled}`;
exec('insertText', `![${file.name}](${url})\n`);
});
}
@@ -320,7 +320,7 @@ const updateListener = EditorView.updateListener.of(v => {
}
});
const state = EditorState.create({
- doc: document.value.content_markdown || '',
+ doc: document.value.content || '',
extensions: [
lineNumbers(),
highlightSpecialChars(),
@@ -387,8 +387,8 @@ function autoSaveConditional() {
const updateDocumentContent = debounce(() => {
const content = editorView.value?.state.doc.toString() || '';
- document.value.content_markdown = content;
- document.value.content_html = compile(content);
+ document.value.content = content;
+ document.value.content_compiled = compile(content);
}, 100);
const save = debounce(() => {
diff --git a/frontend/app/components/MarkdownEditor/Toolbar.vue b/frontend/app/components/MarkdownEditor/Toolbar.vue
index a41349fd..265aff48 100644
--- a/frontend/app/components/MarkdownEditor/Toolbar.vue
+++ b/frontend/app/components/MarkdownEditor/Toolbar.vue
@@ -6,7 +6,7 @@
</button>
<VoiceRecognition @transcription="handleTranscription" />
<AppSelect v-if="!minimal" v-model="localValue.accessibility" :items="DOCUMENT_ACCESSIBILITIES" placeholder="Access" size="100px" class="entry" />
- <AppSelect v-if="!minimal" v-model="localValue.category" :items="categories" placeholder="Select category" size="300px" class="entry" />
+ <AppSelect v-if="!minimal" v-model="localValue.parent_id" :items="categories" placeholder="Select category" size="300px" class="entry" />
<div class="help">
<button @click="openSettings">
@@ -20,20 +20,20 @@
</template>
<script setup lang="ts">
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
import ModalSyntax from './ModalSyntax.vue';
import VoiceRecognition from './VoiceRecognition.vue';
import EditorPreferences from './EditorPreferences.vue';
const props = defineProps<{
- modelValue: Partial<Document>;
+ modelValue: Partial<Node>;
minimal?: boolean;
}>();
const handleTranscription = (text: string) => {
emit('execute-action', 'insertText', text);
};
const emit = defineEmits<{
- (e: 'update:modelValue', value: Partial<Document>): void;
+ (e: 'update:modelValue', value: Partial<Node>): void;
(e: 'execute-action', action: string, payload?: string): void;
}>();
@@ -47,9 +47,7 @@ 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 categories = computed(() =>
- new TreeStructure(useSidebarTree().categories.value).generateTree().filter(i => i.data.type === 'category' && i.data.role == 2),
-);
+const categories = computed(() => new TreeStructure(useSidebarTree().nodes.value.filter(n => n.data.role <= 2)).generateTree().filter(i => i.data.role === 1));
const toolbar = [
{
diff --git a/frontend/app/components/QuickSearch.vue b/frontend/app/components/QuickSearch.vue
index f964091d..25a11509 100644
--- a/frontend/app/components/QuickSearch.vue
+++ b/frontend/app/components/QuickSearch.vue
@@ -12,7 +12,7 @@
<NuxtLink v-for="doc of docs" :key="doc.id" class="item-search" :to="`/dashboard/docs/${doc.id}`" @click="close">
<Icon name="draft" :big="true" fill="var(--font-color)" /> {{ doc.name }}
<span class="category">
- <tag :class="getAppColor(categoryStore.getById(doc.category || '')?.color)">{{ categoryStore.getById(doc.category || '')?.name }}</tag>
+ <tag :class="getAppColor(categoryStore.getById(doc.parent_id || '')?.color)">{{ categoryStore.getById(doc.parent_id || '')?.name }}</tag>
</span>
</NuxtLink>
<p v-if="!docs.length" class="no-result">No result found.</p>
@@ -21,12 +21,10 @@
</template>
<script setup lang="ts">
-const categoryStore = useCategoriesStore();
+const categoryStore = useNodesStore();
const documents = computed(() =>
- useDocumentsStore().getAll.filter(
- c => c.name.toLowerCase().includes(filter.value.toLowerCase()) || c.tags?.toLowerCase().includes(filter.value.toLowerCase()),
- ),
+ useNodesStore().getAll.filter(c => c.name.toLowerCase().includes(filter.value.toLowerCase()) || c.tags?.toLowerCase().includes(filter.value.toLowerCase())),
);
const filter = ref<string>('');
const showSearchModal = ref<boolean>(false);
diff --git a/frontend/app/components/Sidebar/CollapseItem.vue b/frontend/app/components/Sidebar/CollapseItem.vue
index d6c908c1..aadf7ba6 100644
--- a/frontend/app/components/Sidebar/CollapseItem.vue
+++ b/frontend/app/components/Sidebar/CollapseItem.vue
@@ -1,23 +1,19 @@
<template>
<div v-if="item.childrens?.length">
- <SidebarItem v-if="true || (root && item.data.type == 'document')" :item="item" class="collapse-header doc">
+ <SidebarItem :item="item" class="collapse-header doc">
<svg :class="{ rotated: !props.item.show.value }" xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24" @click="toggleShow">
<path d="M480-345 240-585l56-56 184 184 184-184 56 56-240 240Z" />
</svg>
</SidebarItem>
- <SidebarItem v-else-if="root" :item="item" class="collapse-header" @click="toggleShow">
- <svg :class="{ rotated: !props.item.show.value }" xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24">
- <path d="M480-345 240-585l56-56 184 184 184-184 56 56-240 240Z" />
- </svg>
- </SidebarItem>
- <SidebarItem v-else :item="item" class="collapse-header" />
- <!--eslint-disable-next-line vue/no-use-v-if-with-v-for -->
- <div v-for="child in item.childrens" v-if="getCollapseState(item.id)" :key="child.id" class="collapse-body" style="margin-left: 15px">
- <CollapseItem v-if="child.childrens?.length" :item="child" :root="child.data.type === 'document'" />
- <SidebarItem v-else :item="child" />
- </div>
+ <template v-if="getCollapseState(item.id)">
+ <div v-for="child in item.childrens" :key="child.id" class="collapse-body" style="margin-left: 15px">
+ <CollapseItem v-if="child.childrens?.length" :item="child" :root="child.data.role === 3" />
+ <SidebarItem v-else :item="child" />
+ </div>
+ </template>
</div>
- <SidebarItem v-else-if="item.show.value" :item="item" />
+ <!-- Filter hidden "navigation items" -->
+ <SidebarItem v-else-if="item.data.role !== -1 || item.show.value" :item="item" />
</template>
<script setup lang="ts">
const props = defineProps<{ item: Item; root?: boolean }>();
diff --git a/frontend/app/components/Sidebar/Sidebar.vue b/frontend/app/components/Sidebar/Sidebar.vue
index 125bff8b..7e5472d2 100644
--- a/frontend/app/components/Sidebar/Sidebar.vue
+++ b/frontend/app/components/Sidebar/Sidebar.vue
@@ -20,16 +20,29 @@
<div class="email">{{ userStore.user.email }}</div>
</NuxtLink>
<div class="icons">
- <NuxtLink to="/dashboard/docs/new" :prefetch="false" @click="onClick"><Icon name="add_file" :mid="true" fill="var(--font-color)" /></NuxtLink>
- <NuxtLink @click="newCategory"><Icon name="add_folder" :mid="true" fill="var(--font-color)" /></NuxtLink>
- <NuxtLink @click="sidebarTree.collapseAll"><Icon name="collapse" :mid="true" fill="var(--font-color)" /></NuxtLink>
- <NuxtLink @click="toggleDock"><Icon name="dock" :mid="true" fill="var(--font-color)" /></NuxtLink>
+ <NuxtLink to="/dashboard/docs/new" class="nav-item" :prefetch="false" @click="onClick">
+ <Icon name="add_file" :mid="true" fill="var(--font-color)" />
+ <p class="hint-tooltip">New doc</p>
+ </NuxtLink>
+ <NuxtLink class="nav-item" @click="newCategory"
+ ><Icon name="add_folder" :mid="true" fill="var(--font-color)" />
+ <p class="hint-tooltip">New category</p></NuxtLink
+ >
+ <NuxtLink class="nav-item" @click="sidebarTree.collapseAll"
+ ><Icon name="collapse" :mid="true" fill="var(--font-color)" />
+ <p class="hint-tooltip">Close all</p></NuxtLink
+ >
+ <NuxtLink class="nav-item" @click="toggleDock"
+ ><Icon name="dock" :mid="true" fill="var(--font-color)" />
+ <p class="hint-tooltip">Toggle dock</p></NuxtLink
+ >
</div>
</div>
</div>
<SidebarWorkspaces :options="workspaces" />
<CollapseItem v-for="item in navigationItems" :key="item.id" :item="item" :root="true" />
<hr style="width: 100%; margin: 5px 0" />
+
<template v-if="tree.length">
<CollapseItem v-for="item in tree" :key="item.id" :item="item" :root="true" />
</template>
@@ -51,12 +64,12 @@ import NewCategoryModal from '@/pages/dashboard/categories/_modals/CreateCategor
import Dock from './Dock.vue';
const { isOpened, hasSidebar } = useSidebar();
-const categoriesStore = useCategoriesStore();
+const nodesStore = useNodesStore();
const preferences = usePreferences();
const userStore = useUserStore();
const filter = ref<string>('');
-const workspaces = computed(() => [...categoriesStore.getAll.filter(c => c.role === 2).map(c => ({ text: c.name, value: c.id, meta: c }))]);
-const isLoading = computed(() => categoriesStore.isFetching || useDocumentsStore().isFetching || useRessourcesStore().isFetching);
+const workspaces = computed(() => [...nodesStore.getAll.filter(c => c.role === 1).map(c => ({ text: c.name, value: c.id, meta: c }))]);
+const isLoading = computed(() => nodesStore.isFetching);
const sidebarTree = useSidebarTree();
const toggleDock = () => preferences.set('view_dock', !preferences.get('view_dock').value);
@@ -72,7 +85,7 @@ const handleClickOutside = (e: MouseEvent) => {
};
const newCategory = () => {
onClick();
- useModal().add(new Modal(shallowRef(NewCategoryModal), { props: { role: 1 } }));
+ useModal().add(new Modal(shallowRef(NewCategoryModal), { props: { role: 2 } }));
};
const onClick = () => {
if (isMobile()) isOpened.value = false;
@@ -123,8 +136,11 @@ onBeforeUnmount(() => {
align-items: center;
}
}
-
+.nav-item:hover .hint-tooltip {
+ display: block;
+}
.icons {
+ position: relative;
display: flex;
height: fit-content;
diff --git a/frontend/app/components/Sidebar/SidebarItem.vue b/frontend/app/components/Sidebar/SidebarItem.vue
index fa4442b8..7c80fd76 100644
--- a/frontend/app/components/Sidebar/SidebarItem.vue
+++ b/frontend/app/components/Sidebar/SidebarItem.vue
@@ -13,21 +13,20 @@
<NuxtLink :to="item.route" style="flex: 1" class="close">{{ item.label }}</NuxtLink>
- <NuxtLink v-if="item.data.type === 'category'" :to="`/dashboard/categories/${item.id}/edit`" class="nav close">
+ <NuxtLink v-if="item.data.role === 2" :to="`/dashboard/categories/${item.id}/edit`" class="nav close">
<Icon name="settings" fill="var(--font-color)" />
</NuxtLink>
- <NuxtLink v-if="item.data.type === 'category'" :to="`/dashboard/docs/new?cat=${item.id}`" :prefetch="false" class="nav close">
+ <NuxtLink v-if="item.data.role === 2" :to="`/dashboard/docs/new?cat=${item.id}`" :prefetch="false" class="nav close">
<Icon name="plus" fill="var(--font-color)" />
</NuxtLink>
- <Icon v-if="item.data.type === 'document' && item.data.pinned" name="pin" fill="var(--font-color-light)" class="ni" />
+ <Icon v-if="item.data.role === 3 && item.data.order === -1" name="pin" fill="var(--font-color-light)" class="ni" />
<slot />
</span>
</template>
<script setup lang="ts">
import { navigationItems } from './helpers';
-const documentStore = useDocumentsStore();
-const categoriesStore = useCategoriesStore();
+const nodesStore = useNodesStore();
const { isOpened } = useSidebar();
const props = defineProps<{ item: Item }>();
const customClass = computed(() => {
@@ -62,42 +61,41 @@ const dragLeave = () => {
// RΓ©initialise l'Γ©tat de survol lorsque l'Γ©lΓ©ment quitte la zone de dΓ©pΓ΄t
isDragOver.value = false;
};
-
+const { workspaceId } = useSidebar();
const drop = async (event: DragEvent) => {
isDragOver.value = false;
const draggedItemId = event.dataTransfer!.getData('text/plain');
- let draggedItem =
- documentStore.getById(draggedItemId) || categoriesStore.getById(draggedItemId) || navigationItems.find(item => item.id === draggedItemId)?.data;
+ let draggedItem = nodesStore.getById(draggedItemId) || navigationItems.find(item => item.id === draggedItemId)?.data;
if (!draggedItem) return;
- if (draggedItem.type === 'document' && draggedItem.partial) {
- draggedItem = await documentStore.fetch({ id: draggedItem.id });
+ if (draggedItem.role === 3 && draggedItem.partial) {
+ draggedItem = await nodesStore.fetch({ id: draggedItem.id });
}
- if (draggedItem.type === 'document' && props.item.data.type === 'category') {
+ if (draggedItem.role === 3 && props.item.data.role === 2) {
// Move document to category
- documentStore.update({ ...draggedItem, category: props.item.id, parent_id: null });
+ nodesStore.update({ ...draggedItem, parent_id: props.item.id });
}
- if (draggedItem.type === 'category' && props.item.data.type === 'category') {
+ if (draggedItem.role === 2 && props.item.data.role === 2) {
// Move category to category
if (draggedItem.id === props.item.id) return; // Prevent moving to the same category
- categoriesStore.update({ ...draggedItem, parent_id: props.item.id, workspace_id: undefined });
+ nodesStore.update({ ...draggedItem, parent_id: props.item.id });
}
- if (draggedItem.type === 'document' && props.item.data.type === 'document') {
+ if (draggedItem.role === 3 && props.item.data.role === 3) {
// Move document to document
- if (documentStore.getAllChildrensIds(draggedItem.id).includes(props.item.parent_id ?? '')) return; // Prevent moving parent to child
+ if (nodesStore.getAllChildrensIds(draggedItem.id).includes(props.item.parent_id ?? '')) return; // Prevent moving parent to child
if (draggedItem.id === props.item.id) return; // Prevent moving to the same document
- documentStore.update({ ...draggedItem, parent_id: props.item.id, category: props.item.data.category });
+ nodesStore.update({ ...draggedItem, parent_id: props.item.id });
}
- if (draggedItem.type === 'category' && props.item.data.type === 'navigation') {
+ if (draggedItem.role === 2 && props.item.data.role === -1) {
// Move category to root
- categoriesStore.update({ ...draggedItem, parent_id: undefined, workspace_id: useSidebar().workspaceId.value || undefined });
+ nodesStore.update({ ...draggedItem, parent_id: workspaceId.value });
}
- if (draggedItem.type === 'document' && props.item.data.type === 'navigation') {
+ if (draggedItem.role === 3 && props.item.data.role === -1) {
// Move document to root
- documentStore.update({ ...draggedItem, parent_id: undefined, category: useSidebar().workspaceId.value || undefined });
+ nodesStore.update({ ...draggedItem, parent_id: workspaceId.value });
}
};
</script>
diff --git a/frontend/app/components/Sidebar/SidebarWorkspaces.vue b/frontend/app/components/Sidebar/SidebarWorkspaces.vue
index b3d1e045..001478bf 100644
--- a/frontend/app/components/Sidebar/SidebarWorkspaces.vue
+++ b/frontend/app/components/Sidebar/SidebarWorkspaces.vue
@@ -30,7 +30,7 @@ import type { Workspace } from './helpers';
const { workspaceId } = useSidebar();
const props = defineProps<{ options: Workspace[] }>();
-const all_workspaces = ref({ text: 'All Workspaces', value: null, meta: { color: -1 } });
+const all_workspaces = ref({ text: 'All Workspaces', value: undefined, meta: { color: -1 } });
watch(
() => props.options,
diff --git a/frontend/app/components/Sidebar/helpers.ts b/frontend/app/components/Sidebar/helpers.ts
index 0131ab2f..cc58e0f1 100644
--- a/frontend/app/components/Sidebar/helpers.ts
+++ b/frontend/app/components/Sidebar/helpers.ts
@@ -1,8 +1,9 @@
-import type { Category } from '~/stores';
+import type { Node } from '~/stores';
export interface DefaultItem {
id: string;
type: 'navigation';
+ role: -1; // 0: Navigation item
label: string;
icon?: string;
route: string;
@@ -10,8 +11,8 @@ export interface DefaultItem {
}
export interface Workspace {
text: string;
- value: string | null;
- meta?: Partial<Category>;
+ value?: string;
+ meta?: Partial<Node>;
}
const sidebarItemsPrefs = usePreferences().get('sidebarItems');
export const navigationItems: Item<DefaultItem>[] = [
@@ -24,6 +25,7 @@ export const navigationItems: Item<DefaultItem>[] = [
data: {
id: 'home',
type: 'navigation',
+ role: -1,
label: 'Home',
icon: 'dashboard',
route: '/dashboard/home',
@@ -40,6 +42,7 @@ export const navigationItems: Item<DefaultItem>[] = [
data: {
id: 'manage-categories',
type: 'navigation',
+ role: -1,
label: 'Manage categories',
icon: 'categories',
route: '/dashboard/categories',
@@ -56,6 +59,7 @@ export const navigationItems: Item<DefaultItem>[] = [
data: {
id: 'cdn',
type: 'navigation',
+ role: -1,
label: 'CDN',
icon: 'cdn',
route: '/dashboard/cdn',
@@ -72,6 +76,7 @@ export const navigationItems: Item<DefaultItem>[] = [
data: {
id: 'settings',
type: 'navigation',
+ role: -1,
label: 'Settings',
icon: 'user_settings',
route: '/dashboard/settings',
@@ -88,6 +93,7 @@ export const navigationItems: Item<DefaultItem>[] = [
data: {
id: 'documents',
type: 'navigation',
+ role: -1,
label: 'Documents',
icon: 'files',
route: '/dashboard/docs',
@@ -104,6 +110,7 @@ export const navigationItems: Item<DefaultItem>[] = [
data: {
id: 'import',
type: 'navigation',
+ role: -1,
label: 'Import',
icon: 'import',
route: '/dashboard/import',
@@ -120,6 +127,7 @@ export const navigationItems: Item<DefaultItem>[] = [
data: {
id: 'new-page',
type: 'navigation',
+ role: -1,
label: 'New Page',
icon: 'add_file',
route: '/dashboard/docs/new',
diff --git a/frontend/app/composables/Sidebar.ts b/frontend/app/composables/Sidebar.ts
index 8084b71e..b90778f4 100644
--- a/frontend/app/composables/Sidebar.ts
+++ b/frontend/app/composables/Sidebar.ts
@@ -2,8 +2,8 @@ const isOpened = ref(false);
const hasSidebar = ref(false);
const paneWidth = ref(isMobile() ? 350 : 390); // initial width of pane 1
const isResizing = ref(false);
-const workspaceId = ref<string | null>(null);
-
+const workspaceId = ref<string | undefined>(undefined);
+const active_id = ref<string | null>(null);
export function useSidebar() {
const toggleSidebar = () => (isOpened.value = !isOpened.value);
@@ -14,5 +14,6 @@ export function useSidebar() {
paneWidth,
isResizing,
workspaceId,
+ active_id,
};
}
diff --git a/frontend/app/composables/TreeStructure.ts b/frontend/app/composables/TreeStructure.ts
index e4630909..dd0411a0 100644
--- a/frontend/app/composables/TreeStructure.ts
+++ b/frontend/app/composables/TreeStructure.ts
@@ -1,4 +1,4 @@
-import type { Document, Category, Ressource } from '~/stores';
+import type { Node } from '~/stores';
import type { DefaultItem } from '../components/Sidebar/helpers';
export interface ANode {
@@ -8,7 +8,7 @@ export interface ANode {
childrens?: ANode[];
}
-export interface Item<T = Document | Category | DefaultItem | Ressource> extends ANode {
+export interface Item<T = Node | DefaultItem> extends ANode {
id: string;
route: string;
data: T;
@@ -31,7 +31,7 @@ export class TreeStructure {
for (const item of items) {
if (!this.childrenMap.has(item.parent_id || '')) this.childrenMap.set(item.parent_id || '', []);
- this.childrenMap.get(item.parent_id || '')!.push(item);
+ this.childrenMap.get(item.parent_id!)!.push(item);
}
}
@@ -42,7 +42,7 @@ export class TreeStructure {
public generateTree(): Item[] {
return this.items
- .filter(item => item.parent_id === '' || !this.itemMap.has(item.parent_id || '') || (item.data.type === 'category' && item.data.role === 2))
+ .filter(item => item.data.role === 1 || item.parent_id === '' || (item.parent_id && !this.itemMap.has(item.parent_id || '')))
.map(root => this.buildTree(root, new Set()));
}
public getSubTreeById(id: string): Item | undefined {
diff --git a/frontend/app/composables/constants.ts b/frontend/app/composables/constants.ts
index a94b62b4..acff912b 100644
--- a/frontend/app/composables/constants.ts
+++ b/frontend/app/composables/constants.ts
@@ -24,3 +24,8 @@ export const EDITOR_FONTS = [
{ label: 'Arial', id: 'Arial' },
{ label: 'Times New Roman', id: 'Times New Roman' },
];
+
+export const CATEGORY_ROLES = [
+ { id: 1, label: 'Workspace' },
+ { id: 2, label: 'Category' },
+];
diff --git a/frontend/app/composables/useSidebarTree.ts b/frontend/app/composables/useSidebarTree.ts
index 084956b9..022ea262 100644
--- a/frontend/app/composables/useSidebarTree.ts
+++ b/frontend/app/composables/useSidebarTree.ts
@@ -1,101 +1,89 @@
// useSidebarTree.ts
import type { DefaultItem } from '~/components/Sidebar/helpers';
-import type { Category, Document, Ressource } from '~/stores';
+import type { Node } from '~/stores';
-export function useSidebarTree() {
- const categoriesStore = useCategoriesStore();
- const documentsStore = useDocumentsStore();
- const ressourcesStore = useRessourcesStore();
- const preferencesStore = usePreferences();
- const { workspaceId } = useSidebar();
+const preferencesStore = usePreferences();
+const { workspaceId } = useSidebar();
- // Wait for categories and documents to be fetched
- const isReady = computed(() => !categoriesStore.isFetching && !documentsStore.isFetching && !ressourcesStore.isFetching);
-
- const categories = computed<Item<Category>[]>(() =>
- isReady.value
- ? categoriesStore.categories.map(cat => ({
- id: cat.id,
- parent_id: cat.parent_id || '',
- label: cat.name,
- route: `/dashboard/categories/${cat.id}`,
- icon: cat.icon || 'folder',
- data: cat,
- show: ref(getCollapseState(cat.id)),
- }))
- : [],
- );
+let nodes: ComputedRef<Item<Node>[]> | Ref<Item<Node>[]> = ref([]);
+const allItems = computed(() => nodes.value.filter(n => n.data.role !== 1));
+const structure = computed(() => new TreeStructure(allItems.value));
- const documents = computed<Item<Document>[]>(() =>
- isReady.value
- ? documentsStore.documents
- .sort((a, b) => b.pinned - a.pinned || a.name.localeCompare(b.name))
- .map(doc => ({
- id: doc.id,
- parent_id: doc.parent_id || doc.category || '',
- label: doc.name,
- route: `/dashboard/docs/${doc.id}`,
- icon: doc.accessibility == 1 ? 'file' : doc.accessibility == 2 ? 'draft' : 'shared_doc',
- data: doc,
- show: ref(getCollapseState(doc.id)),
- }))
- : [],
- );
- const ressources = computed<Item<Ressource>[]>(() => {
- if (!preferencesStore.get('hideSidebarRessources').value && isReady.value)
- return ressourcesStore.getAll
- .filter(res => res.parent_id)
- .map(res => ({
- id: res.id,
- parent_id: res.parent_id || '',
- label: res.filename,
- route: `/dashboard/cdn/${res.id}/preview`,
- icon: res.filetype == 'application/pdf' ? 'pdf' : 'image',
- data: res,
- show: ref(true),
- }));
- return [];
- });
+const resolveIcon = (item: Node) => {
+ if (item.role === 1 || item.role === 2) return item.icon || 'folder';
+ if (item.role === 3) return item.accessibility == 1 ? 'file' : item.accessibility == 2 ? 'draft' : 'shared_doc';
+ if (item.role === 4) return item.metadata?.filetype == 'application/pdf' ? 'pdf' : 'image';
+ return 'file';
+};
- const allItems = computed(() => [...documents.value, ...ressources.value, ...categories.value.filter(cat => cat.data.role == 1)]);
- const structure = computed(() => new TreeStructure(allItems.value));
+const resolveLink = (item: Node) => {
+ if (item.role === 1 || item.role === 2) return `/dashboard/categories/${item.id}`;
+ if (item.role === 3) return `/dashboard/docs/${item.id}`;
+ if (item.role === 4) return `/dashboard/cdn/${item.id}/preview`;
+ return '/dashboard';
+};
- // Tree with normalized icons
- const tree = computed(() => {
- if (!preferencesStore.get('normalizeFileIcons').value) {
- for (const i of structure.value.childrenMap.keys()) {
- const ref = structure.value.itemMap.get(i);
- const subs = structure.value.childrenMap.get(i);
- if (ref?.data.type === 'document' && subs?.some(c => c.data.type != 'ressource')) {
- structure.value.itemMap.get(i)!.icon = 'file_parent';
- }
+const tree = computed(() => {
+ if (!preferencesStore.get('normalizeFileIcons').value) {
+ for (const i of structure.value.childrenMap.keys()) {
+ const ref = structure.value.itemMap.get(i);
+ const subs = structure.value.childrenMap.get(i);
+ if (ref?.data.role === 3 && subs?.some(c => c.data.role != 4)) {
+ structure.value.itemMap.get(i)!.icon = 'file_parent';
}
}
- return structure.value.generateTree();
+ }
+ return structure.value.generateTree();
+});
+
+const filtered = computed(() =>
+ tree.value.filter(item => {
+ if (workspaceId.value) return (item as Item<Node>).parent_id === workspaceId.value;
+ return true;
+ }),
+);
+const collapseAll = () => {
+ allItems.value.forEach(item => {
+ if (item.show.value) item.show.value = false;
+ collapseAllStates();
});
+};
+const getSubTreeById = (id: string) => {
+ return structure.value.treeToArray(structure.value.getSubTreeById(id)?.childrens || []);
+};
- // Filtered tree based on workspace
- const filtered = computed(() =>
- tree.value.filter(item => {
- if (item.data.type === 'category' && workspaceId.value) return item.data.parent_id === workspaceId.value && item.data.role == 1;
- if (item.data.type === 'document' && workspaceId.value) return item.data.category === workspaceId.value;
- return true;
- }),
- );
- const collapseAll = () => {
- allItems.value.forEach(item => {
- if (item.show.value) item.show.value = false;
- collapseAllStates();
- });
- };
- const getSubTreeById = (id: string) => {
- return structure.value.treeToArray(structure.value.getSubTreeById(id)?.childrens || []);
- };
+function useSidebarTree() {
+ const nodesStore = useNodesStore();
+
+ // Wait for categories and documents to be fetched
+ const isReady = computed(() => !nodesStore.isFetching);
+
+ if (!nodes.value.length) {
+ nodes = computed(() =>
+ isReady.value
+ ? nodesStore.nodes
+ .sort((a, b) => {
+ if ((a.order ?? 0) !== (b.order ?? 0)) return (a.order ?? 0) - (b.order ?? 0);
+ return a.name.localeCompare(b.name);
+ })
+ .sort((a, b) => (a.order ?? 0) - (b.order ?? 0) || a.name.localeCompare(b.name))
+ .map(node => ({
+ id: node.id,
+ parent_id: node.parent_id || '',
+ label: node.name,
+ route: resolveLink(node),
+ icon: resolveIcon(node),
+ data: node,
+ show: ref(getCollapseState(node.id)),
+ }))
+ : [],
+ );
+ }
const groupedByWorkspace = () => {
- const workspaces: Item<Category | Document | Ressource | DefaultItem>[] = [
- ...categoriesStore.getAll
- .filter(c => c.role === 2)
+ const workspaces: Item<Node | DefaultItem>[] = [
+ ...nodesStore.getAll
+ .filter(c => c.role === 1)
.map(c => ({
id: c.id,
parent_id: c.parent_id || '',
@@ -119,13 +107,30 @@ export function useSidebarTree() {
return workspaces;
};
+ const getCategoryFromNode = (parentId?: string | null) => {
+ let category: Item<Node> | null = null;
+ let parent_id: string | undefined | null = parentId;
+ while (parent_id) {
+ const parent = structure.value.itemMap.get(parent_id);
+ if (parent?.data.role === 2) {
+ category = parent as Item<Node>;
+ break;
+ }
+ parent_id = parent?.parent_id;
+ }
+ return category;
+ };
+
return {
structure,
+ nodes,
collapseAll,
getSubTreeById,
groupedByWorkspace,
- categories,
+ getCategoryFromNode,
tree,
filtered,
};
}
+
+export { useSidebarTree, tree, filtered };
diff --git a/frontend/app/helpers/importations.ts b/frontend/app/helpers/importations.ts
index 6e79f368..994443ec 100644
--- a/frontend/app/helpers/importations.ts
+++ b/frontend/app/helpers/importations.ts
@@ -1,9 +1,7 @@
-import type { DB_Category, DB_Document, DB_Ressource } from '~/stores';
+import type { DB_Node } from '~/stores';
interface ImportationStructure {
- documents: DB_Document[];
- categories: DB_Category[];
- ressources: DB_Ressource[];
+ nodes: DB_Node[];
}
function analyseFile(file: File): Promise<ImportationStructure> {
@@ -30,16 +28,16 @@ function analyseFile(file: File): Promise<ImportationStructure> {
}
function validateFileStructure(data: ImportationStructure): data is ImportationStructure {
- if (typeof data === 'object' && data !== null && Array.isArray(data.documents)) {
+ if (typeof data === 'object' && data !== null && Array.isArray(data.nodes)) {
return true;
}
return false;
}
function compareDocumentsAndLocal(data: ImportationStructure) {
- const diff: DB_Document[] = [];
+ const diff: DB_Node[] = [];
const local = useSidebarTree().structure.value;
- for (const doc of data.documents) {
+ for (const doc of data.nodes) {
const localDoc = local.getItem(doc.id);
if (!localDoc) {
diff.push(doc);
@@ -48,28 +46,25 @@ function compareDocumentsAndLocal(data: ImportationStructure) {
return diff;
}
-function prepareNewDocuments(new_docs: Partial<DB_Document>[]) {
+function prepareNewDocuments(new_docs: Partial<DB_Node>[]) {
// For each document, check if parent_id and category are valid
// If not, set them to null
const local = useSidebarTree().structure.value;
for (const doc of new_docs) {
if (doc.parent_id && !local.getItem(doc.parent_id)) {
- doc.parent_id = null;
- }
- if (doc.category && !local.getItem(doc.category)) {
- doc.category = undefined;
+ doc.parent_id = undefined;
}
}
}
-async function uploadDocument(document: DB_Document) {
- const documentsStore = useDocumentsStore();
- await documentsStore.post({ type: 'document', ...document });
+async function uploadDocument(document: DB_Node) {
+ const documentsStore = useNodesStore();
+ await documentsStore.post(document);
}
-async function uploadDocuments(documents: DB_Document[]) {
- const documentsStore = useDocumentsStore();
+async function uploadDocuments(documents: DB_Node[]) {
+ const documentsStore = useNodesStore();
for (const doc of documents) {
- await documentsStore.post({ type: 'document', ...doc });
+ await documentsStore.post(doc);
}
}
diff --git a/frontend/app/middleware/navigation.global.ts b/frontend/app/middleware/navigation.global.ts
new file mode 100644
index 00000000..03304130
--- /dev/null
+++ b/frontend/app/middleware/navigation.global.ts
@@ -0,0 +1,4 @@
+export default defineNuxtRouteMiddleware(async (to, _) => {
+ if (!import.meta.client) return;
+ useSidebar().active_id.value = to.params.id as string | null;
+});
diff --git a/frontend/app/pages/(public)/doc/[id].vue b/frontend/app/pages/(public)/doc/[id].vue
index e71ec6ad..1fe49efa 100644
--- a/frontend/app/pages/(public)/doc/[id].vue
+++ b/frontend/app/pages/(public)/doc/[id].vue
@@ -17,7 +17,7 @@
ref="element"
:class="`${article.theme || preferencesStore.get('theme').value}-theme`"
style="max-width: 100%"
- v-html="article.content_html"
+ v-html="article.content_compiled"
/>
<DocumentSkeleton v-else />
</div>
@@ -36,14 +36,14 @@
import TableOfContent from '../../dashboard/docs/_components/table-of-content/TableOfContents.vue';
import DocumentSkeleton from '../../dashboard/docs/_components/DocumentSkeleton.vue';
import DocumentCardHeader from '../../dashboard/docs/_components/DocumentCardHeader.vue';
-import type { Document } from '@/stores';
+import type { Node } from '@/stores';
const route = useRoute();
-const documentsStore = useDocumentsStore();
+const documentsStore = useNodesStore();
const preferencesStore = usePreferences();
const element = ref<HTMLElement>();
-const article = ref<Document | undefined>();
+const article = ref<Node | undefined>();
const error: Ref<false | string> = ref(false);
watchEffect(async () => {
diff --git a/frontend/app/pages/dashboard.vue b/frontend/app/pages/dashboard.vue
index 431edfb5..50298d03 100644
--- a/frontend/app/pages/dashboard.vue
+++ b/frontend/app/pages/dashboard.vue
@@ -14,8 +14,6 @@
</template>
<script setup lang="ts">
definePageMeta({ breadcrumb: 'Home' });
-useDocumentsStore().fetch();
-useCategoriesStore().fetch();
+useNodesStore().fetch();
useUserStore().fetch();
-useRessourcesStore().fetch();
</script>
diff --git a/frontend/app/pages/dashboard/admin/index.vue b/frontend/app/pages/dashboard/admin/index.vue
deleted file mode 100644
index 95109708..00000000
--- a/frontend/app/pages/dashboard/admin/index.vue
+++ /dev/null
@@ -1,6 +0,0 @@
-<template>
- <div class="card-component">
- <h1>Admin dashboard</h1>
- <AppButton type="primary" @click="useRouter().push('/dashboard/admin/users')">Manage users</AppButton>
- </div>
-</template>
diff --git a/frontend/app/pages/dashboard/admin/users.vue b/frontend/app/pages/dashboard/admin/users.vue
deleted file mode 100644
index 2bb89aa4..00000000
--- a/frontend/app/pages/dashboard/admin/users.vue
+++ /dev/null
@@ -1,6 +0,0 @@
-<template>
- <NuxtPage />
-</template>
-<script setup lang="ts">
-definePageMeta({ breadcrumb: 'Users' });
-</script>
diff --git a/frontend/app/pages/dashboard/admin/users/[id]/documents/[doc_id].vue b/frontend/app/pages/dashboard/admin/users/[id]/documents/[doc_id].vue
deleted file mode 100644
index 8cb840ef..00000000
--- a/frontend/app/pages/dashboard/admin/users/[id]/documents/[doc_id].vue
+++ /dev/null
@@ -1,45 +0,0 @@
-<template>
- <div class="card-component" style="height: 100%">
- <h1>Document view</h1>
- <div v-if="document" style="display: flex; width: 100%; height: 95%; min-height: 0; flex-direction: column">
- <h2>{{ document.name }}</h2>
- <p>{{ document.description }}</p>
- <div style="display: flex; width: 100%; min-height: 0; flex: 1; gap: 10px; overflow: auto">
- <textarea v-model="document.content_markdown" style="flex: 1"></textarea>
- <!-- eslint-disable-next-line vue/no-v-html -->
- <div style="flex: 1" v-html="document.content_html" />
- </div>
- </div>
-
- <div v-else>No document found.</div>
- </div>
-</template>
-
-<script setup lang="ts">
-import type { Document } from '@/stores';
-
-definePageMeta({ breadcrumb: 'Document view' });
-const document = ref<Document | undefined>();
-const route = useRoute();
-const store = useAdminStore();
-
-document.value = await store.fetchUserDocument(route.params.id as string, route.params.doc_id as string);
-</script>
-
-<style scoped lang="scss">
-.user-detail {
- display: flex;
- width: 100%;
- align-items: flex-start;
- flex-direction: column;
- gap: 0.5rem;
-}
-
-label {
- font-weight: bold;
-}
-
-button {
- margin-top: 1rem;
-}
-</style>
diff --git a/frontend/app/pages/dashboard/admin/users/[id]/documents/index.vue b/frontend/app/pages/dashboard/admin/users/[id]/documents/index.vue
deleted file mode 100644
index 902a0899..00000000
--- a/frontend/app/pages/dashboard/admin/users/[id]/documents/index.vue
+++ /dev/null
@@ -1,68 +0,0 @@
-<template>
- <div class="card-component">
- <h2 style="text-align: center">Search documents</h2>
- <DataTable :headers="headers" :rows="rows">
- <template #actions="{ cell }">
- <NuxtLink :to="`/dashboard/admin/users/${route.params.id}/documents/${(cell?.data as Document).id}`"><Icon name="view" /></NuxtLink>
- </template>
- </DataTable>
- </div>
-</template>
-
-<script setup lang="ts">
-import type { Document } from '~/stores';
-definePageMeta({ breadcrumb: 'Documents' });
-
-const documents = ref<Document[]>([]);
-const route = useRoute();
-const store = useAdminStore();
-
-watchEffect(async () => {
- documents.value = (await store.fetchUserDocuments(route.params.id as string)) || [];
-});
-
-const categoriesStore = useCategoriesStore();
-const headers = [
- { label: 'Name', key: 'name' },
- { label: 'Category', key: 'category' },
- { label: 'Tags', key: 'tags' },
- { label: 'Last update', key: 'last_update' },
- { label: 'Status', key: 'status' },
- { label: 'Actions', key: 'actions' },
-];
-const rows = computed(() =>
- documents.value.map(doc => {
- let badges = '';
- switch (doc.accessibility) {
- case 1:
- badges = '<tag class="green">Document</tag>';
- break;
- case 2:
- badges = '<tag class="teal">Draft</tag>';
- break;
- case 3:
- badges = '<tag class="red">Archived</tag>';
- }
- if (doc.parent_id) badges += '<tag class="yellow">Child</tag>';
- if (documents.value.some(d => d.parent_id === doc.id)) badges += '<tag class="yellow">Parent</tag>';
- return {
- name: { content: doc.name, type: 'text' as const },
- category: { content: categoriesStore.getById(doc.category || '')?.name || '', type: 'text' as const },
- tags: { content: stringToBadge(doc.tags), type: 'html' as const },
- last_update: { content: new Date(parseInt(doc.updated_timestamp)).toLocaleDateString(), type: 'text' as const },
- status: { content: badges, type: 'html' as const },
- actions: { type: 'slot' as const, data: { id: doc.id } },
- };
- }),
-);
-
-function stringToBadge(str?: string): string {
- if (str?.length)
- return str
- .trim()
- .split(',')
- .map(t => `<tag class="blue">${t.trim()}</tag>`)
- .join('');
- return '';
-}
-</script>
diff --git a/frontend/app/pages/dashboard/admin/users/[id]/index.vue b/frontend/app/pages/dashboard/admin/users/[id]/index.vue
deleted file mode 100644
index a986e48f..00000000
--- a/frontend/app/pages/dashboard/admin/users/[id]/index.vue
+++ /dev/null
@@ -1,93 +0,0 @@
-<template>
- <div class="card-component">
- <h2 style="display: flex; align-items: center; justify-content: space-between">User Details <img v-if="user" style=" width: 40px; height: 40px;border-radius: 50%" :src="useAvatar(user)" ></h2>
- <div v-if="user" style="width: 100%">
- <div class="user-details">
- <div class="user-detail">
- <label for="username">Username</label>
- <input id="username" v-model="user.username" type="text" >
- </div>
- <div class="user-detail">
- <label for="firstname">Firstname</label>
- <input id="firstname" v-model="user.firstname" type="text" >
- </div>
- <div class="user-detail">
- <label for="lastname">Lastname</label>
- <input id="lastname" v-model="user.lastname" type="text" >
- </div>
- <div class="user-detail">
- <label for="email">Email</label>
- <input id="email" v-model="user.email" type="email" >
- </div>
- <div class="user-detail">
- <label for="role">Role</label>
- <select id="role" v-model="user.role">
- <option :value="1">User</option>
- <option :value="2">Admin</option>
- </select>
- </div>
- <div style="display: flex; width: 100%">
- <div class="user-detail">
- <label>Created At</label>
- <div class="value">{{ new Date(user.created_timestamp).toLocaleDateString() }}</div>
- </div>
- <div class="user-detail">
- <label>Updated At</label>
- <div class="value">{{ new Date(user.updated_timestamp || 0).toLocaleDateString() }}</div>
- </div>
- </div>
- </div>
-
- <AppButton type="success" @click="saveChanges">Save Changes</AppButton>
- <AppButton type="primary" @click="useRouter().push(`/dashboard/admin/users/${user.id}/documents`)">View documents</AppButton>
- </div>
- <div v-else>No user found.</div>
- </div>
-</template>
-
-<script setup lang="ts">
-import type { User } from '@/stores';
-
-definePageMeta({ breadcrumb: 'User Details' });
-
-const route = useRoute();
-const user = ref<User | undefined>(undefined);
-const store = useAdminStore();
-watchEffect(async () => {
- user.value = await store.fetchById(route.params.id as string);
-});
-
-const saveChanges = async () => {
- if (!user.value) return;
- store
- .update(user.value)
- .then(() => useNotifications().add({ type: 'success', title: 'User updated successfully' }))
- .catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }));
-};
-</script>
-
-<style scoped lang="scss">
-.user-details {
- display: flex;
- width: 100%;
- align-items: flex-start;
- flex-direction: column;
- gap: 1rem;
-}
-
-.user-detail {
- display: flex;
- width: 100%;
- align-items: flex-start;
- flex-direction: column;
- gap: 0.5rem;
-}
-
-label {
- font-weight: bold;
-}
-
-button {
- margin-top: 1rem;
-}
-</style>
diff --git a/frontend/app/pages/dashboard/admin/users/index.vue b/frontend/app/pages/dashboard/admin/users/index.vue
deleted file mode 100644
index cc7f1183..00000000
--- a/frontend/app/pages/dashboard/admin/users/index.vue
+++ /dev/null
@@ -1,44 +0,0 @@
-<template>
- <div class="card-component">
- <header>
- <h1>Users manager</h1>
- </header>
- <DataTable v-if="rows?.length" :headers="headers" :rows="rows || []">
- <template #action="{ cell }">
- <NuxtLink :to="`/dashboard/admin/users/${(cell?.data as User).id}`"><Icon name="view" /></NuxtLink>
- </template>
- </DataTable>
- <div v-else>No user found.</div>
- </div>
-</template>
-<script setup lang="ts">
-import { useAdminStore } from '~/stores/admin.store';
-import type { User } from '~/stores';
-
-const adminStore = useAdminStore();
-adminStore.fetchAll();
-
-const headers = [
- { label: 'Name', key: 'username' },
- { label: 'Firstname', key: 'firstname' },
- { label: 'Lastname', key: 'lastname' },
- { label: 'Email', key: 'email' },
- { label: 'Role', key: 'role' },
- { label: 'Created at', key: 'created_at' },
- { label: 'Action', key: 'action' },
-];
-
-const rows = computed(() =>
- adminStore.users?.map(u => {
- return {
- username: { content: `<img style="border-radius:50%;width:25px;height:25px;" src="${useAvatar(u)}"/>&nbsp;&nbsp;&nbsp;${u.username}`, type: 'html' as const },
- firstname: { content: u.firstname, type: 'text' as const },
- lastname: { content: u.lastname, type: 'text' as const },
- email: { content: u.email, type: 'text' as const },
- role: { content: u.role == 2 ? `<tag class="red">Admin</tag>` : `<tag class="blue">User</tag>`, type: 'html' as const },
- created_at: { content: new Date(u.created_timestamp).toLocaleDateString(), type: 'text' as const },
- action: { type: 'slot' as const, data: { id: u.id } },
- };
- }),
-);
-</script>
diff --git a/frontend/app/pages/dashboard/categories/[id]/edit.vue b/frontend/app/pages/dashboard/categories/[id]/edit.vue
index 30a8c857..ab64a435 100644
--- a/frontend/app/pages/dashboard/categories/[id]/edit.vue
+++ b/frontend/app/pages/dashboard/categories/[id]/edit.vue
@@ -9,13 +9,7 @@
</div>
<div class="form-column">
<label>Role</label>
- <AppRadio
- v-model="category.role"
- :items="[
- { id: 1, label: 'Category' },
- { id: 2, label: 'Workspace' },
- ]"
- />
+ <AppRadio v-model="category.role" :items="CATEGORY_ROLES" />
</div>
</div>
<label>Name</label>
@@ -47,18 +41,16 @@
<script lang="ts" setup>
import DeleteModal from '../_modals/DeleteCategoryModal.vue';
-const categoriesStore = useCategoriesStore();
+const nodesStore = useNodesStore();
const route = useRoute();
-const category = computed(() => categoriesStore.getById(route.params.id as string));
-const categoriesItem = computed(() =>
- new TreeStructure(useSidebarTree().categories.value).generateTree().filter(i => i.data.type === 'category' && i.data.role == 2),
-);
+const category = computed(() => nodesStore.getById(route.params.id as string));
+const categoriesItem = computed(() => new TreeStructure(useSidebarTree().nodes.value).generateTree().filter(i => i.data.role == 1));
definePageMeta({ breadcrumb: 'Edit' });
const updateCategory = async () => {
if (category.value)
- categoriesStore
+ nodesStore
.update(category.value)
.then(() => {
useNotifications().add({ type: 'success', title: 'Category updated' });
diff --git a/frontend/app/pages/dashboard/categories/[id]/index.vue b/frontend/app/pages/dashboard/categories/[id]/index.vue
index 22454500..c7be8b20 100644
--- a/frontend/app/pages/dashboard/categories/[id]/index.vue
+++ b/frontend/app/pages/dashboard/categories/[id]/index.vue
@@ -15,12 +15,7 @@
<DocumentsGrid :documents="documents" />
</div>
</div>
- <NoContent
- v-else
- style="width: 100%; height: 100%"
- title="No documents found"
- description="There are no documents in this category
-"
+ <NoContent v-else style="width: 100%; height: 100%" title="No documents found" description="There are no documents in this category"
><NuxtLink to="/dashboard/docs/new"><AppButton type="link" style="font-weight: bold">+ Create new document </AppButton></NuxtLink>
</NoContent>
</div>
@@ -29,21 +24,20 @@
<script setup lang="ts">
const route = useRoute();
const categoryId = route.params.id as string;
-const categoriesStore = useCategoriesStore();
-const documentsStore = useDocumentsStore();
+const nodesStore = useNodesStore();
const view: Ref<'table' | 'list'> = ref('list');
-definePageMeta({
- breadcrumb: () => {
- const category = useCategoriesStore().getById(useRoute().params.id as string);
- return category?.name || '';
- },
-});
+// definePageMeta({
+// breadcrumb: () => {
+// const category = nodesStore.getById(route.params.id as string);
+// return category?.name || '';
+// },
+// });
const documents = computed(() => {
- const documents = documentsStore.getByCategories(categoryId);
- const childCategories = categoriesStore.getChilds(categoryId);
+ const documents = nodesStore.getByCategories(categoryId);
+ const childCategories = nodesStore.getChilds(categoryId);
for (const childCategory of childCategories) {
- const childDocuments = documentsStore.getByCategories(childCategory.id);
+ const childDocuments = nodesStore.getByCategories(childCategory.id);
documents.push(...childDocuments);
}
return documents;
diff --git a/frontend/app/pages/dashboard/categories/_components/WorkspaceTree.vue b/frontend/app/pages/dashboard/categories/_components/WorkspaceTree.vue
index 29bb77b0..bffd1977 100644
--- a/frontend/app/pages/dashboard/categories/_components/WorkspaceTree.vue
+++ b/frontend/app/pages/dashboard/categories/_components/WorkspaceTree.vue
@@ -1,5 +1,5 @@
<template>
- <div v-if="node.data.type === 'category'" class="tree-node">
+ <div v-if="node.data.role === 2" class="tree-node">
<div class="tree-content">
<div class="tree-label">
<Icon class="icon" name="folder" style="display: inline; width: 15px" />
@@ -18,9 +18,9 @@
</template>
<script lang="ts" setup>
-import type { Category } from '~/stores';
+import type { Node } from '~/stores';
-defineProps<{ node: Item<Category> }>();
+defineProps<{ node: Item<Node> }>();
defineEmits(['edit', 'delete']);
</script>
diff --git a/frontend/app/pages/dashboard/categories/_modals/CreateCategoryModal.vue b/frontend/app/pages/dashboard/categories/_modals/CreateCategoryModal.vue
index 7a2b2655..215ccef8 100644
--- a/frontend/app/pages/dashboard/categories/_modals/CreateCategoryModal.vue
+++ b/frontend/app/pages/dashboard/categories/_modals/CreateCategoryModal.vue
@@ -1,6 +1,6 @@
<template>
<div class="modal">
- <h2>New {{ role == 1 ? 'category' : 'workspace' }}</h2>
+ <h2>New {{ role == 1 ? 'workspace' : 'category' }}</h2>
<label for="name">Name</label>
<input id="name" v-model="category.name" class="entry" type="text" required placeholder="Display name" />
@@ -26,20 +26,18 @@
</template>
<script setup lang="ts">
-import type { Category } from '~/stores';
+import type { Node } from '~/stores';
-const categoriesStore = useCategoriesStore();
-const categoriesItem = computed(() =>
- new TreeStructure(useSidebarTree().categories.value).generateTree().filter(i => i.data.type === 'category' && i.data.role == 2),
-);
-const props = defineProps<{ role: number }>();
+const categoriesStore = useNodesStore();
+const sidebarTree = useSidebarTree();
+const sidebar = useSidebar();
+const categoriesItem = computed(() => new TreeStructure(sidebarTree.nodes.value).generateTree().filter(i => i.data.role == 1));
+const props = defineProps<{ role: 1 | 2 }>();
-const category = ref<Partial<Category>>({
+const category = ref<Partial<Node>>({
name: '',
- type: 'category',
role: props.role,
- order: 0,
- id: '0',
+ parent_id: sidebarTree.getCategoryFromNode(sidebar.active_id.value)?.id || sidebar.workspaceId.value,
});
const emit = defineEmits(['close']);
diff --git a/frontend/app/pages/dashboard/categories/_modals/DeleteCategoryModal.vue b/frontend/app/pages/dashboard/categories/_modals/DeleteCategoryModal.vue
index b1609650..7c23219d 100644
--- a/frontend/app/pages/dashboard/categories/_modals/DeleteCategoryModal.vue
+++ b/frontend/app/pages/dashboard/categories/_modals/DeleteCategoryModal.vue
@@ -14,7 +14,7 @@
<script setup lang="ts">
const props = defineProps<{ categoryId: string }>();
const deleteDoc = () => {
- useCategoriesStore()
+ useNodesStore()
.delete(props.categoryId)
.then(() => {
useNotifications().add({ type: 'success', title: 'Category successfully deleted' });
diff --git a/frontend/app/pages/dashboard/categories/index.vue b/frontend/app/pages/dashboard/categories/index.vue
index ef9fa34a..f27bf84f 100644
--- a/frontend/app/pages/dashboard/categories/index.vue
+++ b/frontend/app/pages/dashboard/categories/index.vue
@@ -29,18 +29,18 @@
import CreateCategoryModal from './_modals/CreateCategoryModal.vue';
import DeleteCategoryModal from './_modals/DeleteCategoryModal.vue';
import WorkspaceTree from './_components/WorkspaceTree.vue';
-import type { Category } from '~/stores';
+import type { Node } from '~/stores';
const filter = ref('');
-const tree = computed(() => new TreeStructure(useSidebarTree().categories.value).generateTree() as Item<Category>[]);
+const tree = computed(() => new TreeStructure(useSidebarTree().nodes.value).generateTree().filter(c => c.data.role === 1) as Item<Node>[]);
const filteredItems = computed(() => {
if (!filter.value.trim()) return tree.value;
- return filterRecursive<Item<Category>>(tree.value, filter);
+ return filterRecursive<Item<Node>>(tree.value, filter);
});
-const createWorkspace = () => useModal().add(new Modal(shallowRef(CreateCategoryModal), { props: { role: 2 } }));
-const createCategory = () => useModal().add(new Modal(shallowRef(CreateCategoryModal), { props: { role: 1 } }));
+const createWorkspace = () => useModal().add(new Modal(shallowRef(CreateCategoryModal), { props: { role: 1 } }));
+const createCategory = () => useModal().add(new Modal(shallowRef(CreateCategoryModal), { props: { role: 2 } }));
function editNode(node: Item) {
useRouter().push('/dashboard/categories/' + node.id + '/edit');
diff --git a/frontend/app/pages/dashboard/cdn/[id]/index.vue b/frontend/app/pages/dashboard/cdn/[id]/index.vue
index 9a710a01..bbc502ca 100644
--- a/frontend/app/pages/dashboard/cdn/[id]/index.vue
+++ b/frontend/app/pages/dashboard/cdn/[id]/index.vue
@@ -12,23 +12,23 @@
</div>
<div class="form-column">
<label>Size</label>
- <input id="size" type="text" :value="readableFileSize(ressource.filesize)" disabled />
+ <input id="size" type="text" :value="readableFileSize(ressource.size ?? 0)" disabled />
</div>
</div>
<label>Name</label>
- <input id="name" v-model="ressource.filename" type="text" required />
+ <input id="name" v-model="ressource.name" type="text" required />
<label style="display: flex; align-items: center">Parent <AppHint text="To organize your uploads" /></label>
- <AppSelect v-model="ressource.parent_id" :items="tree" :disabled="(i) => (i as Item).data?.type !== 'document'" placeholder="Select a ressource parent" />
+ <AppSelect v-model="ressource.parent_id" :items="tree" :disabled="(i) => (i as Item).data?.role !== 3" placeholder="Select a ressource parent" />
<label>Type</label>
- <input id="id" type="text" :value="ressource.filetype" disabled />
+ <input id="id" type="text" :value="ressource.metadata?.filetype" disabled />
<label>Original path</label>
- <input id="original_path" type="text" :value="ressource.original_path" disabled />
+ <input id="content" type="text" :value="ressource.content" disabled />
<label>Path</label>
- <input id="path" type="text" :value="ressource.transformed_path" disabled />
+ <input id="path" type="text" :value="ressource.content_compiled" disabled />
<p style="overflow-wrap: break-word">
Ressource:
- <a :href="`${CDN}/${ressource.author_id}/${ressource.transformed_path || ressource.original_path}`" target="_blank">{{
- `${CDN}/${ressource.author_id}/${ressource.transformed_path || ressource.original_path}`
+ <a :href="`${CDN}/${ressource.user_id}/${ressource.content_compiled || ressource.content}`" target="_blank">{{
+ `${CDN}/${ressource.user_id}/${ressource.content_compiled || ressource.content}`
}}</a>
</p>
<div style="display: flex; justify-content: flex-end">
@@ -37,8 +37,8 @@
<h4>Preview</h4>
<div class="preview">
<img
- v-if="ressource.filetype.startsWith('image/')"
- :src="`${CDN}/${ressource.author_id}/${ressource.transformed_path || ressource.original_path}`"
+ v-if="(ressource.metadata?.filetype as string).startsWith('image/')"
+ :src="`${CDN}/${ressource.user_id}/${ressource.content_compiled || ressource.content}`"
alt="Preview"
/>
<p v-else>Preview not available for this file type.</p>
diff --git a/frontend/app/pages/dashboard/cdn/[id]/preview.vue b/frontend/app/pages/dashboard/cdn/[id]/preview.vue
index 933a7f09..f631ea81 100644
--- a/frontend/app/pages/dashboard/cdn/[id]/preview.vue
+++ b/frontend/app/pages/dashboard/cdn/[id]/preview.vue
@@ -8,22 +8,22 @@
<AppButton type="secondary" @click="copyLink">Copy link</AppButton>
</div>
</header>
- Name: <strong>{{ ressource.filename }}</strong>
+ Name: <strong>{{ ressource.name }}</strong>
<p>
- Type: <strong>{{ ressource.filetype }}</strong>
+ Type: <strong>{{ ressource.metadata?.filetype }}</strong>
</p>
<p>
- Size: <strong>{{ readableFileSize(ressource.filesize) }}</strong>
+ Size: <strong>{{ readableFileSize(ressource.size ?? 0) }}</strong>
</p>
<div class="preview">
<img
- v-if="ressource?.filetype.startsWith('image/')"
- :src="`${CDN}/${ressource!.author_id}/${ressource!.transformed_path || ressource!.original_path}`"
+ v-if="(ressource?.metadata?.filetype as string).startsWith('image/')"
+ :src="`${CDN}/${ressource!.user_id}/${ressource!.content_compiled || ressource!.content}`"
alt="Preview"
/>
<iframe
- v-else-if="ressource!.filetype.startsWith('application/pdf')"
- :src="`${CDN}/${ressource!.author_id}/${ressource!.transformed_path || ressource!.original_path}`"
+ v-else-if="(ressource?.metadata?.filetype as string).startsWith('application/pdf')"
+ :src="`${CDN}/${ressource!.user_id}/${ressource!.content_compiled || ressource!.content}`"
width="100%"
height="500px"
frameborder="0"
@@ -40,7 +40,7 @@ definePageMeta({ breadcrumb: 'Preview' });
const ressource = computed(() => useRessourcesStore().getById(useRoute().params.id as string));
const copyLink = () => {
- const link = `${CDN}/${ressource.value?.author_id}/${ressource.value?.transformed_path || ressource.value?.original_path}`;
+ const link = `${CDN}/${ressource.value?.user_id}/${ressource.value?.content_compiled || ressource.value?.content}`;
navigator.clipboard.writeText(link);
};
</script>
diff --git a/frontend/app/pages/dashboard/cdn/index.vue b/frontend/app/pages/dashboard/cdn/index.vue
index dcee086a..046dd4f2 100644
--- a/frontend/app/pages/dashboard/cdn/index.vue
+++ b/frontend/app/pages/dashboard/cdn/index.vue
@@ -16,18 +16,18 @@
<div v-if="ressourcesStore.ressources.length" class="ressources-list">
<DataTable v-if="view === 'table'" :headers="headers" :rows="rows">
<template #action="{ cell }">
- <NuxtLink :href="`/dashboard/cdn/${(cell?.data as DB_Ressource).id}/preview`" style="margin-right: 10px"><Icon name="view" /> </NuxtLink>
- <NuxtLink :to="`/dashboard/cdn/${(cell?.data as DB_Ressource).id}`"><Icon name="edit" style="margin-right: 10px" /></NuxtLink>
- <Icon name="delete" @click="() => deleteRessource((cell?.data as DB_Ressource).id)" />
+ <NuxtLink :href="`/dashboard/cdn/${(cell?.data as Node).id}/preview`" style="margin-right: 10px"><Icon name="view" /> </NuxtLink>
+ <NuxtLink :to="`/dashboard/cdn/${(cell?.data as Node).id}`"><Icon name="edit" style="margin-right: 10px" /></NuxtLink>
+ <Icon name="delete" @click="() => deleteRessource((cell?.data as Node).id)" />
</template>
</DataTable>
<div v-else>
<div class="images-grid">
<div v-for="image in ressourcesStore.ressources" :key="image.id" class="image-item" @click="router.push(`/dashboard/cdn/${image.id}/preview`)">
- <img :src="fileURL(image)" :alt="image.filename" class="image-preview" />
+ <img :src="fileURL(image)" :alt="image.name" class="image-preview" />
<div class="image-info">
- <span class="image-name">{{ image.filename }}</span>
- <span class="image-size">{{ readableFileSize(image.filesize) }}</span>
+ <span class="image-name">{{ image.name }}</span>
+ <span class="image-size">{{ readableFileSize(image.size ?? 0) }}</span>
</div>
</div>
</div>
@@ -39,7 +39,7 @@
<script setup lang="ts">
import type { Field } from '~/components/DataTable.vue';
import DeleteRessourceModal from './_modals/DeleteRessourceModal.vue';
-import type { DB_Ressource } from '~/stores';
+import type { Node } from '~/stores';
definePageMeta({ breadcrumb: 'Upload' });
const router = useRouter();
const ressourcesStore = useRessourcesStore();
@@ -60,13 +60,13 @@ const submitFile = async () => {
dropComponent.value.reset(); // Reset drop component
await ressourcesStore
.post(body)
- .then(r => (fileLink.value = `${CDN}/${(r as DB_Ressource).author_id}/${(r as DB_Ressource).transformed_path}`))
+ .then(r => (fileLink.value = `${CDN}/${(r as Node).user_id}/${(r as Node).content_compiled}`))
.catch(e => useNotifications().add({ type: 'error', title: 'Error', message: e }))
.finally(() => (isLoading.value = false));
};
-const fileURL = (ressource: DB_Ressource) => {
- if (ressource.filetype.includes('image/')) return `${CDN}/${ressource.author_id}/${ressource.transformed_path}`;
+const fileURL = (ressource: Node) => {
+ if ((ressource.metadata!.filetype as string).includes('image/')) return `${CDN}/${ressource.user_id}/${ressource.content_compiled}`;
return '/file_placeholder.png';
};
const headers = [
@@ -80,12 +80,12 @@ const headers = [
const color = (type: string) => (type.includes('image') ? 'green' : type.includes('video') ? 'blue' : type.includes('pdf') ? 'yellow' : 'red');
const rows: ComputedRef<Field[]> = computed(() =>
ressourcesStore.ressources.map(res => {
- const parent = res.parent_id ? useDocumentsStore().getById(res.parent_id) : null;
- const category = parent ? useCategoriesStore().getById(parent.category || '') : null;
+ const parent = res.parent_id ? useNodesStore().getById(res.parent_id) : null;
+ const category = parent ? useNodesStore().getById(parent.parent_id || '') : null;
return {
- name: { content: res.filename, type: 'text' },
- size: { content: readableFileSize(res.filesize), type: 'text' },
- type: { content: `<tag class="${color(res.filetype)}">${res.filetype}</tag>`, type: 'html' },
+ name: { content: res.name, type: 'text' },
+ size: { content: readableFileSize(res.size ?? 0), type: 'text' },
+ type: { content: `<tag class="${color(res.metadata!.filetype as string)}">${res.metadata!.filetype as string}</tag>`, type: 'html' },
parent: { content: category ? `<tag class="${getAppColor(category.color)}">${parent?.name}</tag>` : '', type: 'html' },
date: { content: new Date(res.created_timestamp).toLocaleDateString(), type: 'text' },
action: { type: 'slot', data: res },
diff --git a/frontend/app/pages/dashboard/docs/[id].vue b/frontend/app/pages/dashboard/docs/[id].vue
index df5b3e72..ca114471 100644
--- a/frontend/app/pages/dashboard/docs/[id].vue
+++ b/frontend/app/pages/dashboard/docs/[id].vue
@@ -10,7 +10,7 @@
ref="element"
:class="`${article.theme || preferencesStore.get('theme').value}-theme`"
style="max-width: 100%"
- v-html="article.content_html"
+ v-html="article.content_compiled"
/>
<DocumentSkeleton v-else />
<DocumentCardFooter :document="article" :next="next" :previous="previous" />
@@ -37,14 +37,14 @@ import DocumentCardHeader from './_components/DocumentCardHeader.vue';
import DocumentCardFooter from './_components/DocumentCardFooter.vue';
import DocumentSkeleton from './_components/DocumentSkeleton.vue';
-import type { Document } from '@/stores';
+import type { Node } from '@/stores';
const route = useRoute();
-const documentsStore = useDocumentsStore();
+const documentsStore = useNodesStore();
const preferencesStore = usePreferences();
const element = ref<HTMLElement>();
-const article = ref<Document | undefined>();
+const article = ref<Node | undefined>();
const error: Ref<false | string> = ref(false);
watchEffect(async () => {
@@ -68,8 +68,8 @@ watchEffect(async () => {
definePageMeta({
breadcrumb: () => {
- const doc = useDocumentsStore().getById(useRoute().params.id as string);
- return doc?.name || '';
+ //const doc = useNodesStore().getById(useRoute().params.id as string);
+ //return doc?.name || '';
},
});
diff --git a/frontend/app/pages/dashboard/docs/_components/DocumentCardFooter.vue b/frontend/app/pages/dashboard/docs/_components/DocumentCardFooter.vue
index 540988f6..0c95b938 100644
--- a/frontend/app/pages/dashboard/docs/_components/DocumentCardFooter.vue
+++ b/frontend/app/pages/dashboard/docs/_components/DocumentCardFooter.vue
@@ -18,8 +18,8 @@
</template>
<script lang="ts" setup>
-import type { Document } from '~/stores';
-defineProps<{ document?: Document; next?: Document; previous?: Document }>();
+import type { Node } from '~/stores';
+defineProps<{ document?: Node; next?: Node; previous?: Node }>();
</script>
<style scoped lang="scss">
diff --git a/frontend/app/pages/dashboard/docs/_components/DocumentCardHeader.vue b/frontend/app/pages/dashboard/docs/_components/DocumentCardHeader.vue
index cbfdd226..d0cdbcef 100644
--- a/frontend/app/pages/dashboard/docs/_components/DocumentCardHeader.vue
+++ b/frontend/app/pages/dashboard/docs/_components/DocumentCardHeader.vue
@@ -6,7 +6,7 @@
<!-- Real content -->
<template v-else>
<p v-if="!public" class="category">
- <NuxtLink :to="`/dashboard/categories/${category?.id}`">{{ category?.name }}</NuxtLink>
+ <NuxtLink :to="`/dashboard/categories/${category?.id}`">{{ category?.name || 'Uncategorized' }}</NuxtLink>
<DocumentCardHeaderActionRow :doc="doc" class="no-print" />
</p>
<h1 class="title" :class="{ public: public }">{{ doc?.name }}</h1>
@@ -26,12 +26,11 @@
import DocumentCardHeaderActionRow from './DocumentCardHeaderActionRow.vue';
import DocumentHeaderIllustration from './DocumentHeaderIllustration.vue';
import DocumentCardHeaderSkeleton from './DocumentCardHeaderSkeleton.vue';
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
-const categories_store = useCategoriesStore();
const preferences = usePreferences();
-const props = defineProps<{ doc?: Document; public?: boolean }>();
-const category = computed(() => categories_store.getById(props.doc?.category || ''));
+const props = defineProps<{ doc?: Node; public?: boolean }>();
+const category = computed(() => useSidebarTree().getCategoryFromNode(props.doc?.parent_id)?.data);
</script>
<style lang="scss" scoped>
diff --git a/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue b/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue
index 869981e8..f6be0fa0 100644
--- a/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue
+++ b/frontend/app/pages/dashboard/docs/_components/DocumentCardHeaderActionRow.vue
@@ -36,15 +36,15 @@
<script setup lang="ts">
import DeleteDocumentModal from '../_modals/DeleteDocumentModal.vue';
import DocumentMeta from '../_modals/DocumentMeta.vue';
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
-const props = defineProps<{ doc: Document }>();
+const props = defineProps<{ doc: Node }>();
const print = () => window.print();
const openDeleteModal = () => useModal().add(new Modal(shallowRef(DeleteDocumentModal), { props: { documentId: props.doc.id } }));
const openEditModal = () => useModal().add(new Modal(shallowRef(DocumentMeta), { props: { doc: props.doc }, size: 'small' }));
function exportMarkdown() {
- const blob = new Blob([props.doc.content_markdown || ''], { type: 'text/markdown' });
+ const blob = new Blob([props.doc.content || ''], { type: 'text/markdown' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
diff --git a/frontend/app/pages/dashboard/docs/_components/DocumentHeaderIllustration.vue b/frontend/app/pages/dashboard/docs/_components/DocumentHeaderIllustration.vue
index b0df41d0..3513c26c 100644
--- a/frontend/app/pages/dashboard/docs/_components/DocumentHeaderIllustration.vue
+++ b/frontend/app/pages/dashboard/docs/_components/DocumentHeaderIllustration.vue
@@ -171,9 +171,9 @@
</template>
<script setup lang="ts">
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
-defineProps<{ document?: Document }>();
+defineProps<{ document?: Node }>();
</script>
<style scoped>
diff --git a/frontend/app/pages/dashboard/docs/_components/table-of-content/TableOfContents.vue b/frontend/app/pages/dashboard/docs/_components/table-of-content/TableOfContents.vue
index 7148ed7c..be1879f4 100644
--- a/frontend/app/pages/dashboard/docs/_components/table-of-content/TableOfContents.vue
+++ b/frontend/app/pages/dashboard/docs/_components/table-of-content/TableOfContents.vue
@@ -20,10 +20,10 @@
</template>
<script lang="ts" setup>
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
import NodeTree from './NodeTree.vue';
-const props = defineProps<{ element?: HTMLElement; doc?: Document }>();
+const props = defineProps<{ element?: HTMLElement; doc?: Node }>();
const list = ref<HTMLElement>();
interface GroupedHeaders {
@@ -112,8 +112,8 @@ const childs = computed(
() =>
useSidebarTree()
.structure.value.childrenMap.get(props.doc?.id || '')
- ?.filter(c => c.data.type === 'document') || [],
-) as Ref<Item<Document>[]>;
+ ?.filter(c => c.data.role === 3) || [],
+) as Ref<Item<Node>[]>;
</script>
<style lang="scss" scoped>
diff --git a/frontend/app/pages/dashboard/docs/_modals/DeleteDocumentModal.vue b/frontend/app/pages/dashboard/docs/_modals/DeleteDocumentModal.vue
index 3643e675..ac08af63 100644
--- a/frontend/app/pages/dashboard/docs/_modals/DeleteDocumentModal.vue
+++ b/frontend/app/pages/dashboard/docs/_modals/DeleteDocumentModal.vue
@@ -14,7 +14,7 @@
<script setup lang="ts">
const props = defineProps<{ documentId: string }>();
const deleteDoc = () => {
- useDocumentsStore()
+ useNodesStore()
.delete(props.documentId)
.then(() => {
useNotifications().add({ type: 'success', title: 'Document deleted' });
diff --git a/frontend/app/pages/dashboard/docs/_modals/DocumentMeta.vue b/frontend/app/pages/dashboard/docs/_modals/DocumentMeta.vue
index 4c1da030..2d4df6a7 100644
--- a/frontend/app/pages/dashboard/docs/_modals/DocumentMeta.vue
+++ b/frontend/app/pages/dashboard/docs/_modals/DocumentMeta.vue
@@ -25,14 +25,14 @@
</div>
<div style="display: flex; align-items: center; gap: 10px">
<label for="pinned">Pinned</label>
- <AppToggle id="pinned" v-model="pinnedToggle" />
+ <!--<AppToggle id="pinned" v-model="pinnedToggle" />-->
</div>
<label for="parent">Parent Document</label>
<AppSelect
v-model="document.parent_id as string"
:items="documentsTree"
- :disabled="(i) => (i as Item).data?.type !== 'document'"
+ :disabled="(i) => (i as Item).data?.role !== 3"
placeholder="Select a document parent"
:nullable="true"
/>
@@ -45,17 +45,17 @@
</template>
<script setup lang="ts">
-import type { Document } from '@/stores';
+import type { Node } from '@/stores';
-const store = useDocumentsStore();
+const store = useNodesStore();
-const props = defineProps<{ doc: Document }>();
-const document = ref<Document>(props.doc);
-const pinnedToggle = ref(!!document.value.pinned);
+const props = defineProps<{ doc: Node }>();
+const document = ref<Node>(props.doc);
+//const pinnedToggle = ref(!!document.value.);
const link = computed(() => `${window.location.origin}/doc/${document.value.id}`);
const documentsTree = computed(() => useSidebarTree().groupedByWorkspace());
-watch(pinnedToggle, val => (document.value.pinned = val ? 1 : 0));
+//watch(pinnedToggle, val => (document.value.pinned = val ? 1 : 0));
watch(
document.value,
debounce(() => store.update(document.value), 500),
diff --git a/frontend/app/pages/dashboard/docs/edit/[id].vue b/frontend/app/pages/dashboard/docs/edit/[id].vue
index b33a5192..f4f70735 100644
--- a/frontend/app/pages/dashboard/docs/edit/[id].vue
+++ b/frontend/app/pages/dashboard/docs/edit/[id].vue
@@ -2,15 +2,15 @@
<MarkdownEditor v-if="document" ref="editor" :doc="document" @save="data => save(data)" @auto-save="data => autoSave(data)" @exit="exit" />
</template>
<script lang="ts" setup>
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
import MarkdownEditor from '~/components/MarkdownEditor/LazyMarkdownEditor.vue';
-const store = useDocumentsStore();
+const store = useNodesStore();
const route = useRoute();
const editor = ref();
const doc_id = route.params.id as string;
-const document = ref<Document | undefined>(undefined);
+const document = ref<Node | undefined>(undefined);
const notifications = useNotifications();
watchEffect(async () => {
@@ -26,14 +26,14 @@ watchEffect(async () => {
definePageMeta({ breadcrumb: 'Edit' });
-function save(doc: Document) {
+function save(doc: Node) {
store
.update(doc)
.then(() => notifications.add({ type: 'success', title: 'Document successfully updated' }))
.catch(e => notifications.add({ type: 'error', title: 'Error', message: e }));
}
-function autoSave(doc: Document) {
+function autoSave(doc: Node) {
store.update(doc);
}
diff --git a/frontend/app/pages/dashboard/docs/index.vue b/frontend/app/pages/dashboard/docs/index.vue
index f9a80833..60bd2857 100644
--- a/frontend/app/pages/dashboard/docs/index.vue
+++ b/frontend/app/pages/dashboard/docs/index.vue
@@ -17,14 +17,14 @@
</template>
<script setup lang="ts">
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
const view: Ref<'table' | 'list'> = ref('list');
const documents = computed(() => {
- const result: Document[] = [];
+ const result: Node[] = [];
const getDocs = (items: Item[]) => {
for (const item of items) {
- if (item.data.type == 'document') result.push(item.data);
+ if (item.data.role == 3) result.push(item.data);
if (item.childrens) getDocs(item.childrens);
}
};
diff --git a/frontend/app/pages/dashboard/docs/new.vue b/frontend/app/pages/dashboard/docs/new.vue
index 1d4593f8..f00c2bad 100644
--- a/frontend/app/pages/dashboard/docs/new.vue
+++ b/frontend/app/pages/dashboard/docs/new.vue
@@ -3,18 +3,18 @@
</template>
<script lang="ts" setup>
import MarkdownEditor from '~/components/MarkdownEditor/LazyMarkdownEditor.vue';
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
-const store = useDocumentsStore();
-const document = ref<Partial<Document>>({
- category: (useRoute().query.cat as string | undefined) || useSidebar().workspaceId.value || undefined,
+const store = useNodesStore();
+const document = ref<Partial<Node>>({
+ parent_id: (useRoute().query.cat as string | undefined) || useSidebar().workspaceId.value || undefined,
accessibility: 1,
});
const notifications = useNotifications();
definePageMeta({ breadcrumb: 'New' });
-function save(doc: Document) {
+function save(doc: Node) {
store
.post(doc)
.then(d => {
diff --git a/frontend/app/pages/dashboard/home.vue b/frontend/app/pages/dashboard/home.vue
index 206a7608..d4c230d1 100644
--- a/frontend/app/pages/dashboard/home.vue
+++ b/frontend/app/pages/dashboard/home.vue
@@ -12,8 +12,8 @@
<div v-if="results.length" class="results">
<NuxtLink v-for="result in results" :key="result.id" class="result" :to="`/dashboard/docs/${result.id}`">
<Icon
- :name="category(result.category)?.icon || 'files'"
- :class="`category-icon ${getAppColor(category(result.category)?.color as number, true)}`"
+ :name="category(result.parent_id)?.icon || 'files'"
+ :class="`category-icon ${getAppColor(category(result.parent_id)?.color as number, true)}`"
/>{{ result.name }}</NuxtLink
>
</div>
@@ -46,30 +46,29 @@
</template>
<script setup lang="ts">
-import type { Document } from '~/stores';
+import type { Node } from '~/stores';
const colorMode = useColorMode();
const searchQuery = ref('');
-const documentsStore = useDocumentsStore();
-const categoryStore = useCategoriesStore();
+const nodesStore = useNodesStore();
function tokenize(text: string) {
return text.trim().toLowerCase().split(/\s+/).filter(Boolean);
}
const results = computed(() => {
const tokens = tokenize(searchQuery.value);
if (!tokens.length) return [];
- return documentsStore.getAll
- .filter((doc: Document) => {
+ return nodesStore.getAll
+ .filter((doc: Node) => {
const name = String(doc.name || '');
const tags = Array.isArray(doc.tags) ? doc.tags.join(' ') : String(doc.tags || '');
return tokens.every(t => name.toLowerCase().includes(t) || tags.toLowerCase().includes(t));
})
.slice(0, 5);
});
-const category = (id?: string) => categoryStore.getById(id || '');
+const category = (id?: string) => nodesStore.getById(id || '');
const recentDocuments = computed(() => {
- return documentsStore.getAll
+ return nodesStore.getAll
.toSorted((a, b) => {
return parseInt(b.updated_timestamp) - parseInt(a.updated_timestamp);
})
diff --git a/frontend/app/pages/dashboard/import.vue b/frontend/app/pages/dashboard/import.vue
index 949c1264..5b659835 100644
--- a/frontend/app/pages/dashboard/import.vue
+++ b/frontend/app/pages/dashboard/import.vue
@@ -3,7 +3,10 @@
<header>
<h1 style="font-size: 20px">Import documents <tag class="yellow">Beta</tag></h1>
</header>
- <p>You can import documents from a previous export. If you don't have export, you can create a new one from the <NuxtLink to="/dashboard/settings?p=backup" style="color: var(--primary)">settings</NuxtLink> page.</p>
+ <p>
+ You can import documents from a previous export. If you don't have export, you can create a new one from the
+ <NuxtLink to="/dashboard/settings?p=backup" style="color: var(--primary)">settings</NuxtLink> page.
+ </p>
<AppDrop ref="dropComponent" @select="handleFileSelect" />
<div class="submit">
<AppButton type="primary" :disabled="!selectedFile" @click="submit">Analyse file</AppButton>
@@ -31,14 +34,14 @@
<script setup lang="ts">
import { analyseFile, validateFileStructure, compareDocumentsAndLocal, prepareNewDocuments, uploadDocument, uploadDocuments } from '~/helpers/importations';
-import type { DB_Document } from '~/stores';
+import type { DB_Node } from '~/stores';
definePageMeta({ breadcrumb: 'Importations' });
const selectedFile: Ref<File | undefined> = ref();
const handleFileSelect = (file?: File) => (selectedFile.value = file);
const dropComponent = ref();
-const files_to_import = ref<DB_Document[]>([]);
+const files_to_import = ref<DB_Node[]>([]);
async function submit() {
try {
if (!selectedFile.value) return;
@@ -55,7 +58,7 @@ async function submit() {
selectedFile.value = undefined; // Reset selected file after processing
}
}
-function importDoc(file: DB_Document) {
+function importDoc(file: DB_Node) {
const fileContent = files_to_import.value.find(i => i.id === file.id);
if (!fileContent) return useNotifications().add({ type: 'error', title: 'File not found' });
prepareNewDocuments([fileContent]);
diff --git a/frontend/app/pages/dashboard/settings/_views/profile.vue b/frontend/app/pages/dashboard/settings/_views/profile.vue
index b27a41ea..9596946a 100644
--- a/frontend/app/pages/dashboard/settings/_views/profile.vue
+++ b/frontend/app/pages/dashboard/settings/_views/profile.vue
@@ -47,7 +47,7 @@ const uploadAvatar = async () => {
const body = new FormData();
body.append('file', file);
const r = await ressourcesStore.postAvatar(body);
- return r.transformed_path || r.original_path;
+ return r.content_compiled || r.original_path;
};
const previewAvatar = (event: Event) => {
if (!userStore.user) return;
diff --git a/frontend/app/stores/admin.store.ts b/frontend/app/stores/admin.store.ts
index f316c135..4d3973b0 100644
--- a/frontend/app/stores/admin.store.ts
+++ b/frontend/app/stores/admin.store.ts
@@ -1,10 +1,8 @@
import { makeRequest } from './_utils';
-import type { User, Document, Category, Ressource } from './db_strustures';
+import type { User, Node } from './db_strustures';
interface UserData extends User {
- documents?: Document[];
- categories?: Category[];
- files?: Ressource[];
+ nodes?: Node[];
}
export const useAdminStore = defineStore('admin', {
@@ -35,17 +33,17 @@ export const useAdminStore = defineStore('admin', {
return request.result;
} else throw request.message;
},
- async fetchUserDocuments(userId: string): Promise<Document[] | undefined> {
+ async fetchUserDocuments(userId: string): Promise<Node[] | undefined> {
const cachedUser = this.users?.find(user => user.id === userId);
- if (cachedUser && cachedUser.documents) return cachedUser.documents;
- const responce = await makeRequest<Document[]>(`documents/${userId}`, 'GET', {});
+ if (cachedUser && cachedUser.nodes) return cachedUser.nodes;
+ const responce = await makeRequest<Node[]>(`nodes/${userId}`, 'GET', {});
if (responce.status === 'success') {
- if (cachedUser) cachedUser.documents = responce.result;
+ if (cachedUser) cachedUser.nodes = responce.result;
return responce.result;
} else throw responce.message;
},
- async fetchUserDocument(userId: string, docId: string): Promise<Document | undefined> {
- const responce = await makeRequest<Document>(`documents/${userId}/${docId}`, 'GET', {});
+ async fetchUserDocument(userId: string, docId: string): Promise<Node | undefined> {
+ const responce = await makeRequest<Node>(`nodes/${userId}/${docId}`, 'GET', {});
if (responce.status === 'success') {
return responce.result;
} else throw responce.message;
diff --git a/frontend/app/stores/categories.store.ts b/frontend/app/stores/categories.store.ts
deleted file mode 100644
index 1c3e75db..00000000
--- a/frontend/app/stores/categories.store.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { makeRequest, type FetchOptions } from './_utils';
-import type { Category, DB_Category } from './db_strustures';
-
-export const useCategoriesStore = defineStore('categories', {
- state: () => ({
- categories: [] as Category[],
- isFetching: false,
- }),
- getters: {
- getAll: state => state.categories,
- getById: state => (id: string) => state.categories.find((c: Category) => c.id == id),
- getParents: state => state.categories.filter(c => !c.parent_id),
- getChilds: state => (id: string) => state.categories.filter(c => c.parent_id == id),
- },
- actions: {
- async fetch(opts?: FetchOptions) {
- this.isFetching = true;
- const request = await makeRequest(`categories/@me/${opts?.id || ''}`, 'GET', {});
- this.isFetching = false;
- if (request.status == 'success') {
- if (opts?.id) {
- // replace the document with the new one
- const index = this.categories.findIndex(d => d.id == opts?.id);
- if (index == -1) this.categories.push({ ...(request.result as DB_Category), type: 'category' });
- else this.categories[index] = { ...(request.result as DB_Category), type: 'category' };
- } else this.categories = (request.result as DB_Category[]).map((d: DB_Category) => ({ ...d, type: 'category' }));
- return this.categories;
- } else throw request.message;
- },
- async post(category: Partial<Category>): Promise<string | number> {
- const response = await makeRequest(`categories`, 'POST', category);
- if (response.status == 'success') return this.categories.push({ ...(response.result as DB_Category), type: 'category' });
- else throw response.message;
- },
- async update(category: Category) {
- const request = await makeRequest(`categories/${category.id}`, 'PUT', category);
- if (request.status == 'success') {
- this.categories = this.categories.map(c => {
- if (c.id == category.id) return category;
- return c;
- });
- return category;
- } else throw request.message;
- },
-
- async delete(id: string) {
- const request = await makeRequest(`categories/${id}`, 'DELETE', {});
- if (request.status == 'success') return (this.categories = this.categories.filter(c => c.id != id));
- else throw request.message;
- },
- },
-});
diff --git a/frontend/app/stores/db_strustures.d.ts b/frontend/app/stores/db_strustures.d.ts
index b2ec11ba..214936ad 100644
--- a/frontend/app/stores/db_strustures.d.ts
+++ b/frontend/app/stores/db_strustures.d.ts
@@ -1,38 +1,28 @@
-export interface DB_Document {
+export interface DB_Node {
id: string;
+ user_id: string;
+ parent_id?: string;
name: string;
description?: string;
tags?: string;
- pinned: number; // 0: Not pinned; 1: Pinned; 2: Favorite;
+ role: 1 | 2 | 3 | 4; // 1: Workspace; 2: Category; 3: Document; 4: Ressource
+ color?: number; // -1: Default; 0: None; 1-7: App colors
+ icon?: string;
thumbnail?: string;
theme?: string;
- icon?: string;
- color?: number; // -1: Default; 0: None; 1-7: App colors
- category?: string;
- parent_id?: string | null;
- accessibility: number; // 1 Visible; 2 Draft; 3 Archived;
- content_markdown?: string;
- content_html?: string;
- author_id: string;
+ accessibility?: number; // 1 Visible; 2 Draft; 3 Archived;
+ display?: number; // 1 List; 2 Grid;
+ order?: number; // -1 for pinned and -2 for bookmark
+ content?: string;
+ content_compiled?: string;
+ size?: number; // in bytes
+ metadata?: Record<string, unknown>;
created_timestamp: string;
updated_timestamp: string;
}
-export interface Document extends DB_Document {
+
+export interface Node extends DB_Node {
partial?: boolean;
- type: 'document';
-}
-export interface DB_Category {
- id: string;
- name: string;
- icon?: string;
- color?: number;
- order?: number;
- role: number; // 1 Category; 2 Workspace
- workspace_id?: string;
- parent_id?: string;
-}
-export interface Category extends DB_Category {
- type: 'category';
}
export interface User {
@@ -57,18 +47,3 @@ export interface ConnectionLog {
type: string;
timestamp: string; // BIGINT converted to string
}
-export interface DB_Ressource {
- id: string;
- filename: string;
- filesize: number;
- filetype: string;
- original_path: string;
- transformed_path: string;
- parent_id?: string;
- author_id: string;
- created_timestamp: string;
-}
-
-export interface Ressource extends DB_Ressource {
- type: 'ressource';
-}
diff --git a/frontend/app/stores/documents.store.ts b/frontend/app/stores/documents.store.ts
index 5acad9b2..4bde6c24 100644
--- a/frontend/app/stores/documents.store.ts
+++ b/frontend/app/stores/documents.store.ts
@@ -1,5 +1,5 @@
import { makeRequest, type FetchOptions } from './_utils';
-import type { DB_Document, Document } from './db_strustures';
+import type { DB_Node, Node } from './db_strustures';
interface SearchOptions {
query?: string;
@@ -10,80 +10,82 @@ interface SearchOptions {
category?: string;
}
-export const useDocumentsStore = defineStore('documents', {
+export const useNodesStore = defineStore('nodes', {
state: () => ({
- documents: [] as Document[],
- public_documents: [] as Document[],
+ nodes: [] as Array<Node | Node>,
+ public_nodes: [] as Node[],
allTags: [] as string[],
isFetching: false,
}),
getters: {
- getAll: state => state.documents,
+ getAll: state => state.nodes,
getAllTags: state => state.allTags,
- getById: state => (id: string) => state.documents.find((d: Document) => d.id == id),
- getByCategories: state => (category: string) => state.documents.filter(d => d.category == category),
+ getById: state => (id: string) => state.nodes.find((d: Node) => d.id == id),
+ getByCategories: state => (category: string) => state.nodes.filter(d => d.parent_id == category),
+ getParents: state => state.nodes.filter(c => !c.parent_id),
+ getChilds: state => (id: string) => state.nodes.filter(c => c.parent_id == id),
- getNext: state => (doc?: Document) => {
- const cdocs = state.documents.filter(d => d.category == doc?.category);
- const index = cdocs.findIndex(d => d.id == doc?.id);
+ getNext: state => (node?: Node) => {
+ const cnodes = state.nodes.filter(d => d.parent_id == node?.parent_id);
+ const index = cnodes.findIndex(d => d.id == node?.id);
if (index == -1) return;
- return cdocs[index + 1];
+ return cnodes[index + 1];
},
- getPrevious: state => (doc?: Document) => {
- const cdocs = state.documents.filter(d => d.category == doc?.category);
- const index = cdocs.findIndex(d => d.id == doc?.id);
+ getPrevious: state => (node?: Node) => {
+ const cnodes = state.nodes.filter(d => d.parent_id == node?.parent_id);
+ const index = cnodes.findIndex(d => d.id == node?.id);
if (index == -1) return;
- return cdocs[index - 1];
+ return cnodes[index - 1];
},
getAllChildrensIds: state => (id: string) => {
const childrens: string[] = [id];
- const getChildrens = (parent: Document) => {
- state.documents.forEach(doc => {
- if (doc.parent_id == parent.id) {
- childrens.push(doc.id);
- getChildrens(doc);
+ const getChildrens = (parent: Node) => {
+ state.nodes.forEach(node => {
+ if (node.parent_id == parent.id) {
+ childrens.push(node.id);
+ getChildrens(node);
}
});
};
- const parent = state.documents.find(d => d.id == id);
+ const parent = state.nodes.find(d => d.id == id);
if (parent) getChildrens(parent);
return childrens;
},
search: state => (options: SearchOptions) => {
const { query, fromDate, toDate, dateType, tags, category } = options;
- let filtered = [...state.documents];
+ let filtered = [...state.nodes];
if (query) {
- filtered = filtered.filter(doc => {
- const docContent = `${doc.name} ${doc.description} ${doc.tags}`.toLowerCase();
- return docContent.includes(query.toLowerCase());
+ filtered = filtered.filter(node => {
+ const nodeContent = `${node.name} ${node.description} ${node.tags}`.toLowerCase();
+ return nodeContent.includes(query.toLowerCase());
});
}
if (fromDate) {
- filtered = filtered.filter(doc => {
- const docDate = new Date(doc[dateType === 'created' ? 'created_timestamp' : 'updated_timestamp']);
- return docDate >= fromDate;
+ filtered = filtered.filter(node => {
+ const nodeDate = new Date(node[dateType === 'created' ? 'created_timestamp' : 'updated_timestamp']);
+ return nodeDate >= fromDate;
});
}
if (toDate) {
- filtered = filtered.filter(doc => {
- const docDate = new Date(doc[dateType === 'created' ? 'created_timestamp' : 'updated_timestamp']);
- return docDate <= toDate;
+ filtered = filtered.filter(node => {
+ const nodeDate = new Date(node[dateType === 'created' ? 'created_timestamp' : 'updated_timestamp']);
+ return nodeDate <= toDate;
});
}
if (tags && tags.length > 0) {
- filtered = filtered.filter(doc => {
- if (!doc.tags) return false;
- const docTags = parseTags(doc.tags);
- return tags.some(tag => docTags.includes(tag));
+ filtered = filtered.filter(node => {
+ if (!node.tags) return false;
+ const nodeTags = parseTags(node.tags);
+ return tags.some(tag => nodeTags.includes(tag));
});
}
if (category) {
- filtered = filtered.filter(doc => doc.category === category);
+ filtered = filtered.filter(node => node.parent_id === category);
}
return filtered;
@@ -92,64 +94,65 @@ export const useDocumentsStore = defineStore('documents', {
actions: {
recomputeTags() {
const tags = new Set<string>();
- this.documents.forEach(doc => {
- if (doc.tags) {
- parseTags(doc.tags).forEach(tag => tags.add(tag));
+ this.nodes.forEach(node => {
+ if (node.tags) {
+ parseTags(node.tags).forEach(tag => tags.add(tag));
}
});
this.allTags = Array.from(tags).sort();
},
- async fetch<T extends FetchOptions>(opts?: T): Promise<'id' extends keyof T ? Document : Document[]> {
- console.log(`[store/documents] Fetching documents with options: ${JSON.stringify(opts)}`);
- if (!this.documents.length) this.isFetching = true;
- const request = await makeRequest(`documents/@me/${opts?.id || ''}`, 'GET', {});
+ async fetch<T extends FetchOptions>(opts?: T): Promise<'id' extends keyof T ? Node : Node[]> {
+ console.log(`[store/nodes] Fetching nodes with options: ${JSON.stringify(opts)}`);
+ if (!this.nodes.length) this.isFetching = true;
+ const request = await makeRequest(`nodes/@me/${opts?.id || ''}`, 'GET', {});
this.isFetching = false;
if (request.status == 'success') {
if (opts?.id) {
- const index = this.documents.findIndex(d => d.id == opts?.id);
- const updatedDocument: Document = { ...(request.result as DB_Document), partial: false, type: 'document' };
- if (index == -1) this.documents.push(updatedDocument);
- else this.documents[index] = updatedDocument;
- return updatedDocument as 'id' extends keyof T ? Document : Document[];
+ const index = this.nodes.findIndex(d => d.id == opts?.id);
+ const updatedNode: Node = { ...(request.result as DB_Node), partial: false };
+ if (index == -1) this.nodes.push(updatedNode);
+ else this.nodes[index] = updatedNode;
+ return updatedNode as 'id' extends keyof T ? Node : Node[];
} else {
- this.documents = (request.result as DB_Document[]).map((d: DB_Document) => ({ ...d, partial: true, type: 'document' }));
+ this.nodes = (request.result as DB_Node[]).map((d: DB_Node) => ({ ...d, partial: true }));
this.recomputeTags();
- return this.documents as 'id' extends keyof T ? Document : Document[];
+ return this.nodes as 'id' extends keyof T ? Node : Node[];
}
} else throw request;
},
- async fetchPublic(id: string): Promise<Document | undefined> {
- console.log(`[store/documents] Fetching public document with id: ${id}`);
- const existingDoc = this.public_documents.find(d => d.id === id);
+ async fetchPublic(id: string): Promise<Node | undefined> {
+ console.log(`[store/nodes] Fetching public nodeument with id: ${id}`);
+ const existingDoc = this.public_nodes.find(d => d.id === id);
if (existingDoc) return existingDoc;
- const request = await makeRequest(`documents/public/${id}`, 'GET', {});
+ const request = await makeRequest(`nodes/public/${id}`, 'GET', {});
if (request.status === 'success') {
- const fetchedDoc: Document = { ...(request.result as DB_Document), partial: false, type: 'document' };
- this.public_documents.push(fetchedDoc);
+ const fetchedDoc: Node = { ...(request.result as DB_Node), partial: false };
+ this.public_nodes.push(fetchedDoc);
return fetchedDoc;
} else return undefined;
},
- async post(doc: Document): Promise<DB_Document> {
- const request = await makeRequest('documents', 'POST', doc);
+ async post(node: Partial<Node>): Promise<DB_Node> {
+ const request = await makeRequest('nodes', 'POST', node);
if (request.status == 'success') {
- this.documents.push({ ...(request.result as DB_Document), type: 'document', partial: false });
- return request.result as DB_Document;
+ this.nodes.push({ ...(request.result as DB_Node), partial: false });
+ return request.result as DB_Node;
} else throw request.message;
},
- async update(doc: Document) {
- if (doc.partial) {
- console.log('[store/documents] Document is partial, cannot update it directly.');
- const fullDoc = await this.fetch({ id: doc.id });
- if (!fullDoc) throw 'Document not found';
- doc = { ...doc, content_markdown: fullDoc.content_markdown, content_html: fullDoc.content_html, partial: false }; // Merge with full document data
+
+ async update(node: Node) {
+ if (node.partial) {
+ console.log('[store/nodes] Node is partial, cannot update it directly.');
+ const fullDoc = await this.fetch({ id: node.id });
+ if (!fullDoc) throw 'Node not found';
+ node = { ...fullDoc, ...node, partial: false }; // Merge with full nodeument data
}
- const request = await makeRequest(`documents/${doc.id}`, 'PUT', doc);
- if (request.status == 'success') return (this.documents = this.documents.map(d => (d.id == doc.id ? doc : d)));
+ const request = await makeRequest(`nodes/${node.id}`, 'PUT', node);
+ if (request.status == 'success') return (this.nodes = this.nodes.map(d => (d.id == node.id ? node : d)));
else throw request.message;
},
async delete(id: string) {
- const request = await makeRequest(`documents/${id}`, 'DELETE', {});
- if (request.status == 'success') return (this.documents = this.documents.filter(d => d.id != id));
+ const request = await makeRequest(`nodes/${id}`, 'DELETE', {});
+ if (request.status == 'success') return (this.nodes = this.nodes.filter(d => d.id != id));
else throw request.message;
},
},
diff --git a/frontend/app/stores/index.ts b/frontend/app/stores/index.ts
index a15080c6..a1b96c46 100644
--- a/frontend/app/stores/index.ts
+++ b/frontend/app/stores/index.ts
@@ -1,5 +1,4 @@
export * from './documents.store';
-export * from './categories.store';
-export * from './ressources.store';
export * from './user.store';
+export * from './resources.store';
export type * from './db_strustures';
diff --git a/frontend/app/stores/ressources.store.ts b/frontend/app/stores/resources.store.ts
similarity index 52%
rename from frontend/app/stores/ressources.store.ts
rename to frontend/app/stores/resources.store.ts
index d1fc9811..fc89739f 100644
--- a/frontend/app/stores/ressources.store.ts
+++ b/frontend/app/stores/resources.store.ts
@@ -1,9 +1,8 @@
import { makeRequest } from './_utils';
-import type { DB_Ressource, Ressource } from './db_strustures';
-
+import type { Node } from './db_strustures';
export const useRessourcesStore = defineStore('ressources', {
state: () => ({
- ressources: [] as Ressource[],
+ ressources: [] as Node[],
isFetching: false,
}),
getters: {
@@ -11,35 +10,25 @@ export const useRessourcesStore = defineStore('ressources', {
getById: state => (id: string) => state.ressources.find(c => c.id == id),
},
actions: {
- async fetch(): Promise<Ressource[]> {
- if (this.ressources.length > 0) return this.ressources;
- this.isFetching = true;
- const request = await makeRequest(`ressources/@me`, 'GET', {});
- this.isFetching = false;
- if (request.status == 'success') {
- this.ressources = (request.result as DB_Ressource[]).map((d: DB_Ressource) => ({ ...d, type: 'ressource' })) as Ressource[];
- return this.ressources;
- } else throw request.message;
- },
- async post(ressource: FormData): Promise<Ressource | string> {
+ async post(ressource: FormData): Promise<Node> {
const request = await makeRequest(`ressources`, 'POST', ressource);
if (request.status == 'success') {
- this.ressources.unshift(request.result as Ressource);
- return request.result as Ressource;
+ this.ressources.push(request.result as Node);
+ return request.result as Node;
} else throw request.message;
},
- async postAvatar(ressource: FormData): Promise<{ original_path: string; transformed_path: string }> {
+ async postAvatar(ressource: FormData): Promise<{ original_path: string; content_compiled: string }> {
const request = await makeRequest(`ressources/avatar`, 'POST', ressource);
if (request.status == 'success') {
- return request.result as { original_path: string; transformed_path: string };
+ return request.result as { original_path: string; content_compiled: string };
} else throw request.message;
},
- async update(ressource: Ressource): Promise<Ressource | string> {
+ async update(ressource: Node): Promise<Node | string> {
const request = await makeRequest(`ressources/${ressource.id}`, 'PUT', ressource);
if (request.status == 'success') {
const index = this.ressources.findIndex(c => c.id == ressource.id);
- if (index != -1) this.ressources[index] = ressource as Ressource;
- return request.result as Ressource;
+ if (index != -1) this.ressources[index] = ressource as Node;
+ return request.result as Node;
} else throw request.message;
},
async delete(id: string) {
diff --git a/frontend/app/styles/components.scss b/frontend/app/styles/components.scss
index 1352488a..0f36037a 100644
--- a/frontend/app/styles/components.scss
+++ b/frontend/app/styles/components.scss
@@ -71,4 +71,28 @@ tag {
font-size: medium !important;
padding: 0;
margin: 0 0 1rem 0 !important;
+}
+
+.hint-wrapper {
+ position: relative;
+ display: inline-block;
+ margin-left: 0.25rem;
+}
+
+.hint-tooltip {
+ position: absolute;
+ top: 100%;
+ left: 50%;
+ z-index: 100;
+ display: none;
+ padding: 0.4rem 0.6rem;
+ border-radius: 0.4rem;
+ font-size: 0.75rem;
+ color: white;
+ background-color: #1f2937;
+ box-shadow: 0 2px 8px var(--shadow);
+ margin-top: 0.4rem;
+ text-transform: capitalize;
+ transform: translateX(-50%);
+ white-space: nowrap;
}
\ No newline at end of file