Compare commits

..

38 Commits

Author SHA1 Message Date
57a3d5697d change mobile breadcrumb icon 2025-04-22 20:36:50 +01:00
660555068b Merge branch 'main' into feat/sharing 2025-04-22 20:28:43 +01:00
6cfddead24 * add /p/ segment to share urls
* minore fixes
2025-04-22 20:24:55 +01:00
7cd2c18b12 fix 2025-04-22 19:53:58 +01:00
33738fba03 Merge branch 'main' into feat/sharing 2025-04-22 19:38:19 +01:00
dfb5e0dd59 Merge branch 'main' into feat/sharing 2025-04-22 15:53:18 +01:00
07ed1a6a78 make shares/info endpoint public 2025-04-22 15:13:33 +01:00
f74688663d WIP 2025-04-22 15:10:05 +01:00
a66fb875ac add twitter tags 2025-04-22 14:43:44 +01:00
e8082a0680 add meta og:title 2025-04-22 14:28:36 +01:00
deb6c9c09b open link button 2025-04-22 14:23:14 +01:00
cf7f5bbd19 add link ref 2025-04-22 13:51:22 +01:00
3e195e7fa1 Change copy 2025-04-22 13:47:51 +01:00
86e8795c1f refactor page breadcrumbs 2025-04-22 13:31:15 +01:00
644cbd62de Store share key in lowercase 2025-04-22 12:22:24 +01:00
b5b48378ab update copy 2025-04-21 20:33:49 +01:00
a207ca7855 defaults 2025-04-21 20:33:39 +01:00
9ce708bb7d close sidebar 2025-04-21 20:11:55 +01:00
f029381952 close sidebar on click 2025-04-21 20:06:58 +01:00
3efb62dec3 Merge branch 'main' into feat/sharing 2025-04-21 19:26:57 +01:00
6f80ea56df fix 2025-04-21 19:26:24 +01:00
0ff41d06fa WIP 2025-04-21 16:01:45 +01:00
410dce9ea9 update shared page spaceId 2025-04-21 16:01:21 +01:00
9e5339c86b Close Navbar on outside click on mobile 2025-04-21 15:46:23 +01:00
c93a96ef55 disable user select 2025-04-20 20:18:27 +01:00
56b97f306b Merge branch 'main' into feat/sharing 2025-04-19 19:47:41 +01:00
fa6c10b07f Server render shared page meta tags 2025-04-19 14:59:52 +01:00
5ccea524c7 WIP 2025-04-18 20:46:55 +01:00
c20931bd95 include userRole in space object 2025-04-18 17:29:23 +01:00
6543ef16f8 Merge branch 'main' into feat/sharing 2025-04-16 23:30:52 +01:00
99540141ea WIP 2025-04-16 23:23:27 +01:00
5bdefda9c7 WIP 2025-04-16 20:19:16 +01:00
418e61614c Share - WIP 2025-04-15 12:45:26 +01:00
8dff3e2240 WIP 2025-04-12 17:59:00 +01:00
16a253ec40 WIP 2025-04-10 23:47:26 +01:00
4f52d32bef - public attachment links
- WIP
2025-04-10 17:57:02 +01:00
b5c90ec775 Merge branch 'main' into feat/sharing 2025-04-09 20:22:44 +01:00
18e8c4cbaf Share - WIP 2025-04-09 13:26:50 +01:00
113 changed files with 281 additions and 3267 deletions

View File

@ -1,7 +1,7 @@
{ {
"name": "client", "name": "client",
"private": true, "private": true,
"version": "0.20.4", "version": "0.10.2",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc && vite build",
@ -29,7 +29,6 @@
"clsx": "^2.1.1", "clsx": "^2.1.1",
"emoji-mart": "^5.6.0", "emoji-mart": "^5.6.0",
"file-saver": "^2.0.5", "file-saver": "^2.0.5",
"highlightjs-sap-abap": "^0.3.0",
"i18next": "^23.14.0", "i18next": "^23.14.0",
"i18next-http-backend": "^2.6.1", "i18next-http-backend": "^2.6.1",
"jotai": "^2.12.1", "jotai": "^2.12.1",

View File

@ -362,26 +362,5 @@
"Move page to a different space.": "Seite in einen anderen Bereich verschieben.", "Move page to a different space.": "Seite in einen anderen Bereich verschieben.",
"Real-time editor connection lost. Retrying...": "Echtzeit-Editor-Verbindung verloren. Wiederholen...", "Real-time editor connection lost. Retrying...": "Echtzeit-Editor-Verbindung verloren. Wiederholen...",
"Table of contents": "Inhaltsverzeichnis", "Table of contents": "Inhaltsverzeichnis",
"Add headings (H1, H2, H3) to generate a table of contents.": "Fügen Sie Überschriften (H1, H2, H3) hinzu, um ein Inhaltsverzeichnis zu erstellen.", "Add headings (H1, H2, H3) to generate a table of contents.": "Fügen Sie Überschriften (H1, H2, H3) hinzu, um ein Inhaltsverzeichnis zu erstellen."
"Share": "Teilen",
"Public sharing": "Öffentliches Teilen",
"Shared by": "Geteilt von",
"Shared at": "Geteilt am",
"Inherits public sharing from": "Erbt das öffentliche Teilen von",
"Share to web": "Im Web teilen",
"Shared to web": "Im Web geteilt",
"Anyone with the link can view this page": "Jeder mit dem Link kann diese Seite ansehen",
"Make this page publicly accessible": "Diese Seite öffentlich zugänglich machen",
"Include sub-pages": "Unterseiten einbeziehen",
"Make sub-pages public too": "Unterseiten auch öffentlich machen",
"Allow search engines to index page": "Suchmaschinen erlauben, die Seite zu indexieren",
"Open page": "Seite öffnen",
"Page": "Seite",
"Delete public share link": "Öffentlichen Freigabelink löschen",
"Delete share": "Freigabe löschen",
"Are you sure you want to delete this shared link?": "Möchten Sie diesen Freigabelink wirklich löschen?",
"Publicly shared pages from spaces you are a member of will appear here": "Öffentlich geteilte Seiten aus Bereichen, in denen Sie Mitglied sind, erscheinen hier",
"Share deleted successfully": "Freigabe erfolgreich gelöscht",
"Share not found": "Freigabe nicht gefunden",
"Failed to share page": "Fehler beim Teilen der Seite"
} }

View File

@ -383,8 +383,5 @@
"Publicly shared pages from spaces you are a member of will appear here": "Publicly shared pages from spaces you are a member of will appear here", "Publicly shared pages from spaces you are a member of will appear here": "Publicly shared pages from spaces you are a member of will appear here",
"Share deleted successfully": "Share deleted successfully", "Share deleted successfully": "Share deleted successfully",
"Share not found": "Share not found", "Share not found": "Share not found",
"Failed to share page": "Failed to share page", "Failed to share page": "Failed to share page"
"Copy page": "Copy page",
"Copy page to a different space.": "Copy page to a different space.",
"Page copied successfully": "Page copied successfully"
} }

View File

@ -94,7 +94,7 @@
"Invited members will be granted access to spaces the groups can access": "Los miembros invitados recibirán acceso a los espacios a los que los grupos pueden acceder", "Invited members will be granted access to spaces the groups can access": "Los miembros invitados recibirán acceso a los espacios a los que los grupos pueden acceder",
"Join the workspace": "Unirse al espacio de trabajo", "Join the workspace": "Unirse al espacio de trabajo",
"Language": "Idioma", "Language": "Idioma",
"Light": "Claro", "Light": "Ligero",
"Link copied": "Enlace copiado", "Link copied": "Enlace copiado",
"Login": "Iniciar sesión", "Login": "Iniciar sesión",
"Logout": "Cerrar sesión", "Logout": "Cerrar sesión",
@ -362,26 +362,5 @@
"Move page to a different space.": "Mover página a un espacio diferente.", "Move page to a different space.": "Mover página a un espacio diferente.",
"Real-time editor connection lost. Retrying...": "Conexión del editor en tiempo real perdida. Reintentando...", "Real-time editor connection lost. Retrying...": "Conexión del editor en tiempo real perdida. Reintentando...",
"Table of contents": "Índice de contenidos", "Table of contents": "Índice de contenidos",
"Add headings (H1, H2, H3) to generate a table of contents.": "Añadir encabezados (H1, H2, H3) para generar un índice de contenidos.", "Add headings (H1, H2, H3) to generate a table of contents.": "Añadir encabezados (H1, H2, H3) para generar un índice de contenidos."
"Share": "Compartir",
"Public sharing": "Compartición pública",
"Shared by": "Compartido por",
"Shared at": "Compartido en",
"Inherits public sharing from": "Hereda la compartición pública de",
"Share to web": "Compartir en la web",
"Shared to web": "Compartido en la web",
"Anyone with the link can view this page": "Cualquiera con el enlace puede ver esta página",
"Make this page publicly accessible": "Hacer esta página accesible públicamente",
"Include sub-pages": "Incluir subpáginas",
"Make sub-pages public too": "Hacer públicas también las subpáginas",
"Allow search engines to index page": "Permitir a los motores de búsqueda indexar la página",
"Open page": "Abrir página",
"Page": "Página",
"Delete public share link": "Eliminar enlace de compartición pública",
"Delete share": "Eliminar compartición",
"Are you sure you want to delete this shared link?": "¿Está seguro de que desea eliminar este enlace compartido?",
"Publicly shared pages from spaces you are a member of will appear here": "Las páginas compartidas públicamente de los espacios a los que pertenece aparecerán aquí",
"Share deleted successfully": "Compartición eliminada con éxito",
"Share not found": "Compartición no encontrada",
"Failed to share page": "Error al compartir la página"
} }

View File

@ -362,26 +362,5 @@
"Move page to a different space.": "Déplacer la page vers un autre espace.", "Move page to a different space.": "Déplacer la page vers un autre espace.",
"Real-time editor connection lost. Retrying...": "Connexion avec l'éditeur en temps réel perdue. Nouvelle tentative...", "Real-time editor connection lost. Retrying...": "Connexion avec l'éditeur en temps réel perdue. Nouvelle tentative...",
"Table of contents": "", "Table of contents": "",
"Add headings (H1, H2, H3) to generate a table of contents.": "Ajoutez des titres (H1, H2, H3) pour générer une table des matières.", "Add headings (H1, H2, H3) to generate a table of contents.": "Ajoutez des titres (H1, H2, H3) pour générer une table des matières."
"Share": "Partager",
"Public sharing": "Partage public",
"Shared by": "Partagé par",
"Shared at": "Partagé à",
"Inherits public sharing from": "Hérite du partage public de",
"Share to web": "Partager sur le web",
"Shared to web": "Partagé sur le web",
"Anyone with the link can view this page": "Toute personne avec le lien peut voir cette page",
"Make this page publicly accessible": "Rendre cette page accessible au public",
"Include sub-pages": "Inclure les sous-pages",
"Make sub-pages public too": "Rendre également les sous-pages publiques",
"Allow search engines to index page": "Autoriser les moteurs de recherche à indexer la page",
"Open page": "Ouvrir la page",
"Page": "Page",
"Delete public share link": "Supprimer le lien de partage public",
"Delete share": "Supprimer le partage",
"Are you sure you want to delete this shared link?": "Êtes-vous sûr de vouloir supprimer ce lien partagé ?",
"Publicly shared pages from spaces you are a member of will appear here": "Les pages partagées publiquement des espaces dont vous êtes membre apparaîtront ici",
"Share deleted successfully": "Partage supprimé avec succès",
"Share not found": "Partage non trouvé",
"Failed to share page": "Échec du partage de la page"
} }

View File

@ -362,26 +362,5 @@
"Move page to a different space.": "Sposta la pagina in un altro spazio.", "Move page to a different space.": "Sposta la pagina in un altro spazio.",
"Real-time editor connection lost. Retrying...": "Connessione all'editor in tempo reale persa. Riprovo...", "Real-time editor connection lost. Retrying...": "Connessione all'editor in tempo reale persa. Riprovo...",
"Table of contents": "Indice dei contenuti", "Table of contents": "Indice dei contenuti",
"Add headings (H1, H2, H3) to generate a table of contents.": "Aggiungi intestazioni (H1, H2, H3) per generare un sommario.", "Add headings (H1, H2, H3) to generate a table of contents.": "Aggiungi intestazioni (H1, H2, H3) per generare un sommario."
"Share": "Condividi",
"Public sharing": "Condivisione pubblica",
"Shared by": "Condiviso da",
"Shared at": "Condiviso il",
"Inherits public sharing from": "Eredita la condivisione pubblica da",
"Share to web": "Condividi su web",
"Shared to web": "Condiviso su web",
"Anyone with the link can view this page": "Chiunque abbia il link può visualizzare questa pagina",
"Make this page publicly accessible": "Rendi questa pagina accessibile pubblicamente",
"Include sub-pages": "Includi sotto-pagine",
"Make sub-pages public too": "Rendi pubbliche anche le sotto-pagine",
"Allow search engines to index page": "Permetti ai motori di ricerca di indicizzare la pagina",
"Open page": "Apri pagina",
"Page": "Pagina",
"Delete public share link": "Elimina il link di condivisione pubblica",
"Delete share": "Elimina condivisione",
"Are you sure you want to delete this shared link?": "Sei sicuro di voler eliminare questo link condiviso?",
"Publicly shared pages from spaces you are a member of will appear here": "Le pagine condivise pubblicamente dagli spazi di cui sei membro appariranno qui",
"Share deleted successfully": "Condivisione eliminata con successo",
"Share not found": "Condivisione non trovata",
"Failed to share page": "Condivisione della pagina fallita"
} }

View File

@ -362,26 +362,5 @@
"Move page to a different space.": "ページを別のスペースに移動します。", "Move page to a different space.": "ページを別のスペースに移動します。",
"Real-time editor connection lost. Retrying...": "リアルタイムエディターの接続が失われました。再試行しています…", "Real-time editor connection lost. Retrying...": "リアルタイムエディターの接続が失われました。再試行しています…",
"Table of contents": "目次", "Table of contents": "目次",
"Add headings (H1, H2, H3) to generate a table of contents.": "見出しH1、H2、H3を追加して目次を生成します。", "Add headings (H1, H2, H3) to generate a table of contents.": "見出しH1、H2、H3を追加して目次を生成します。"
"Share": "共有",
"Public sharing": "公開共有",
"Shared by": "共有者",
"Shared at": "共有日時",
"Inherits public sharing from": "から公開共有を継承する",
"Share to web": "ウェブで共有",
"Shared to web": "ウェブに共有済み",
"Anyone with the link can view this page": "リンクを持っている人はこのページを閲覧できます",
"Make this page publicly accessible": "このページを公開します",
"Include sub-pages": "サブページを含む",
"Make sub-pages public too": "サブページも公開する",
"Allow search engines to index page": "検索エンジンにページのインデックス作成を許可する",
"Open page": "ページを開く",
"Page": "ページ",
"Delete public share link": "公開リンクを削除",
"Delete share": "共有を削除",
"Are you sure you want to delete this shared link?": "この共有リンクを削除してもよろしいですか?",
"Publicly shared pages from spaces you are a member of will appear here": "メンバーであるスペースからの公開ページがここに表示されます",
"Share deleted successfully": "共有が正常に削除されました",
"Share not found": "共有が見つかりません",
"Failed to share page": "ページの共有に失敗しました"
} }

View File

@ -362,26 +362,5 @@
"Move page to a different space.": "페이지를 다른 공간으로 이동합니다.", "Move page to a different space.": "페이지를 다른 공간으로 이동합니다.",
"Real-time editor connection lost. Retrying...": "실시간 편집기 연결이 끊어졌습니다. 재시도 중...", "Real-time editor connection lost. Retrying...": "실시간 편집기 연결이 끊어졌습니다. 재시도 중...",
"Table of contents": "목차", "Table of contents": "목차",
"Add headings (H1, H2, H3) to generate a table of contents.": "목차를 생성하려면 제목 (H1, H2, H3)을 추가하세요.", "Add headings (H1, H2, H3) to generate a table of contents.": "목차를 생성하려면 제목 (H1, H2, H3)을 추가하세요."
"Share": "공유",
"Public sharing": "공개 공유",
"Shared by": "공유자",
"Shared at": "공유 시간",
"Inherits public sharing from": "로부터 공개 공유를 상속함",
"Share to web": "웹에 공유",
"Shared to web": "웹에 공유됨",
"Anyone with the link can view this page": "링크가 있는 사람은 이 페이지를 볼 수 있습니다",
"Make this page publicly accessible": "이 페이지를 공개적으로 접근 가능하게 만들기",
"Include sub-pages": "하위 페이지 포함",
"Make sub-pages public too": "하위 페이지도 공개로 설정",
"Allow search engines to index page": "검색 엔진이 페이지를 색인할 수 있도록 허용",
"Open page": "페이지 열기",
"Page": "페이지",
"Delete public share link": "공유 링크 삭제",
"Delete share": "공유 삭제",
"Are you sure you want to delete this shared link?": "이 공유 링크를 삭제하시겠습니까?",
"Publicly shared pages from spaces you are a member of will appear here": "회원인 공간의 공개 공유된 페이지가 여기에 표시됩니다",
"Share deleted successfully": "공유가 성공적으로 삭제되었습니다",
"Share not found": "공유를 찾을 수 없습니다",
"Failed to share page": "페이지 공유에 실패했습니다"
} }

View File

@ -362,26 +362,5 @@
"Move page to a different space.": "Verplaats pagina naar een andere ruimte.", "Move page to a different space.": "Verplaats pagina naar een andere ruimte.",
"Real-time editor connection lost. Retrying...": "Realtime editorverbinding verloren. Opnieuw proberen...", "Real-time editor connection lost. Retrying...": "Realtime editorverbinding verloren. Opnieuw proberen...",
"Table of contents": "Inhoudsopgave", "Table of contents": "Inhoudsopgave",
"Add headings (H1, H2, H3) to generate a table of contents.": "Voeg koppen (H1, H2, H3) toe om een inhoudsopgave te genereren.", "Add headings (H1, H2, H3) to generate a table of contents.": "Voeg koppen (H1, H2, H3) toe om een inhoudsopgave te genereren."
"Share": "Delen",
"Public sharing": "Openbaar delen",
"Shared by": "Gedeeld door",
"Shared at": "Gedeeld op",
"Inherits public sharing from": "Erft openbaar delen van",
"Share to web": "Delen naar web",
"Shared to web": "Gedeeld naar web",
"Anyone with the link can view this page": "Iedereen met de link kan deze pagina bekijken",
"Make this page publicly accessible": "Maak deze pagina openbaar toegankelijk",
"Include sub-pages": "Inclusief subpagina's",
"Make sub-pages public too": "Maak subpagina's ook openbaar",
"Allow search engines to index page": "Sta zoekmachines toe om pagina te indexeren",
"Open page": "Pagina openen",
"Page": "Pagina",
"Delete public share link": "Verwijder openbare deel-link",
"Delete share": "Verwijder deel",
"Are you sure you want to delete this shared link?": "Weet u zeker dat u deze gedeelde link wilt verwijderen?",
"Publicly shared pages from spaces you are a member of will appear here": "Openbaar gedeelde pagina's van ruimtes waarvan u lid bent, verschijnen hier",
"Share deleted successfully": "Delen succesvol verwijderd",
"Share not found": "Delen niet gevonden",
"Failed to share page": "Pagina delen mislukt"
} }

View File

@ -362,26 +362,5 @@
"Move page to a different space.": "Mover página para um espaço diferente.", "Move page to a different space.": "Mover página para um espaço diferente.",
"Real-time editor connection lost. Retrying...": "Conexão do editor em tempo real perdida. Tentando novamente...", "Real-time editor connection lost. Retrying...": "Conexão do editor em tempo real perdida. Tentando novamente...",
"Table of contents": "Tabela de conteúdos", "Table of contents": "Tabela de conteúdos",
"Add headings (H1, H2, H3) to generate a table of contents.": "Adicionar títulos (H1, H2, H3) para gerar uma tabela de conteúdo.", "Add headings (H1, H2, H3) to generate a table of contents.": "Adicionar títulos (H1, H2, H3) para gerar uma tabela de conteúdo."
"Share": "Compartilhar",
"Public sharing": "Compartilhamento público",
"Shared by": "Compartilhado por",
"Shared at": "Compartilhado em",
"Inherits public sharing from": "Herdado do compartilhamento público de",
"Share to web": "Compartilhar na web",
"Shared to web": "Compartilhado na web",
"Anyone with the link can view this page": "Qualquer um com o link pode ver esta página",
"Make this page publicly accessible": "Tornar esta página publicamente acessível",
"Include sub-pages": "Incluir sub-páginas",
"Make sub-pages public too": "Tornar as sub-páginas públicas também",
"Allow search engines to index page": "Permitir que mecanismos de busca indexem a página",
"Open page": "Abrir página",
"Page": "Página",
"Delete public share link": "Excluir o link público compartilhado",
"Delete share": "Excluir compartilhamento",
"Are you sure you want to delete this shared link?": "Tem certeza de que deseja excluir este link compartilhado?",
"Publicly shared pages from spaces you are a member of will appear here": "Páginas compartilhadas publicamente de espaços que você é membro aparecerão aqui",
"Share deleted successfully": "Compartilhamento excluído com sucesso",
"Share not found": "Compartilhamento não encontrado",
"Failed to share page": "Falha ao compartilhar página"
} }

View File

@ -13,11 +13,11 @@
"Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "Вы уверены, что хотите удалить этого пользователя из группы? Пользователь потеряет доступ к материалам, к которым у этой группы есть доступ.", "Are you sure you want to remove this user from the group? The user will lose access to resources this group has access to.": "Вы уверены, что хотите удалить этого пользователя из группы? Пользователь потеряет доступ к материалам, к которым у этой группы есть доступ.",
"Are you sure you want to remove this user from the space? The user will lose all access to this space.": "Вы уверены, что хотите удалить этого пользователя из пространства? Пользователь потеряет весь доступ к этому пространству.", "Are you sure you want to remove this user from the space? The user will lose all access to this space.": "Вы уверены, что хотите удалить этого пользователя из пространства? Пользователь потеряет весь доступ к этому пространству.",
"Are you sure you want to restore this version? Any changes not versioned will be lost.": "Вы уверены, что хотите восстановить эту версию? Все не зафиксированные изменения будут потеряны.", "Are you sure you want to restore this version? Any changes not versioned will be lost.": "Вы уверены, что хотите восстановить эту версию? Все не зафиксированные изменения будут потеряны.",
"Can become members of groups and spaces in workspace": "Могут становиться участниками групп и пространств в рабочей области", "Can become members of groups and spaces in workspace": "Могут становиться участниками групп и пространств в рабочем пространстве",
"Can create and edit pages in space.": "Может создавать и редактировать страницы в пространстве.", "Can create and edit pages in space.": "Может создавать и редактировать страницы в пространстве.",
"Can edit": "Может изменять", "Can edit": "Может изменять",
"Can manage workspace": "Может управлять рабочей областью", "Can manage workspace": "Может управлять рабочим пространством",
"Can manage workspace but cannot delete it": "Может управлять рабочей областью, но не может ее удалить", "Can manage workspace but cannot delete it": "Может управлять рабочим пространством, но не может его удалить",
"Can view": "Может просматривать", "Can view": "Может просматривать",
"Can view pages in space but not edit.": "Может просматривать страницы в пространстве, но не может их редактировать.", "Can view pages in space but not edit.": "Может просматривать страницы в пространстве, но не может их редактировать.",
"Cancel": "Отменить", "Cancel": "Отменить",
@ -34,7 +34,7 @@
"Create group": "Создать группу", "Create group": "Создать группу",
"Create page": "Создать страницу", "Create page": "Создать страницу",
"Create space": "Создать пространство", "Create space": "Создать пространство",
"Create workspace": "Создать рабочую область", "Create workspace": "Создать рабочее пространство",
"Current password": "Текущий пароль", "Current password": "Текущий пароль",
"Dark": "Темная", "Dark": "Темная",
"Date": "Дата", "Date": "Дата",
@ -92,7 +92,7 @@
"Invite new members": "Пригласить новых участников", "Invite new members": "Пригласить новых участников",
"Invited members who are yet to accept their invitation will appear here.": "Приглашённые участники, которые ещё не приняли приглашение, появятся здесь.", "Invited members who are yet to accept their invitation will appear here.": "Приглашённые участники, которые ещё не приняли приглашение, появятся здесь.",
"Invited members will be granted access to spaces the groups can access": "Приглашённые участники получат доступ к пространствам, доступ к которым есть у группы", "Invited members will be granted access to spaces the groups can access": "Приглашённые участники получат доступ к пространствам, доступ к которым есть у группы",
"Join the workspace": "Присоединиться к рабочей области", "Join the workspace": "Присоединиться к рабочему пространству",
"Language": "Язык", "Language": "Язык",
"Light": "Светлая", "Light": "Светлая",
"Link copied": "Ссылка скопирована", "Link copied": "Ссылка скопирована",
@ -150,7 +150,7 @@
"Send invitation": "Отправить приглашение", "Send invitation": "Отправить приглашение",
"Invitation sent": "Приглашение отправлено", "Invitation sent": "Приглашение отправлено",
"Settings": "Настройки", "Settings": "Настройки",
"Setup workspace": "Настроить рабочую область", "Setup workspace": "Настроить рабочее пространство",
"Sign In": "Вход", "Sign In": "Вход",
"Sign Up": "Регистрация", "Sign Up": "Регистрация",
"Slug": "Slug", "Slug": "Slug",
@ -177,9 +177,9 @@
"Untitled": "Без названия", "Untitled": "Без названия",
"Updated successfully": "Обновлено успешно", "Updated successfully": "Обновлено успешно",
"User": "Пользователь", "User": "Пользователь",
"Workspace": "Рабочая область", "Workspace": "Рабочее пространство",
"Workspace Name": "Имя рабочей области", "Workspace Name": "Имя рабочего пространства",
"Workspace settings": "Настройки рабочей области", "Workspace settings": "Настройки рабочего пространства",
"You can change your password here.": "Вы можете изменить свой пароль здесь.", "You can change your password here.": "Вы можете изменить свой пароль здесь.",
"Your Email": "Ваш адрес электронной почты", "Your Email": "Ваш адрес электронной почты",
"Your import is complete.": "Ваш импорт завершен.", "Your import is complete.": "Ваш импорт завершен.",
@ -217,9 +217,9 @@
"Revoke invitation": "Отозвать приглашение", "Revoke invitation": "Отозвать приглашение",
"Revoke": "Отозвать", "Revoke": "Отозвать",
"Don't": "Нет", "Don't": "Нет",
"Are you sure you want to revoke this invitation? The user will not be able to join the workspace.": "Вы уверены, что хотите отозвать это приглашение? Пользователь не сможет присоединиться к рабочей области.", "Are you sure you want to revoke this invitation? The user will not be able to join the workspace.": "Вы уверены, что хотите отозвать это приглашение? Пользователь не сможет присоединиться к рабочему пространству.",
"Resend invitation": "Отправить приглашение повторно", "Resend invitation": "Отправить приглашение повторно",
"Anyone with this link can join this workspace.": "Любой, у кого есть данная ссылка, может присоединиться к этой рабочей области.", "Anyone with this link can join this workspace.": "Любой, у кого есть эта ссылка, может присоединиться к этому рабочему пространству.",
"Invite link": "Ссылка для приглашения", "Invite link": "Ссылка для приглашения",
"Copy": "Копировать", "Copy": "Копировать",
"Copied": "Скопировано", "Copied": "Скопировано",
@ -362,26 +362,5 @@
"Move page to a different space.": "Переместите страницу в другое пространство.", "Move page to a different space.": "Переместите страницу в другое пространство.",
"Real-time editor connection lost. Retrying...": "Соединение с редактором в реальном времени потеряно. Повторная попытка...", "Real-time editor connection lost. Retrying...": "Соединение с редактором в реальном времени потеряно. Повторная попытка...",
"Table of contents": "Содержание", "Table of contents": "Содержание",
"Add headings (H1, H2, H3) to generate a table of contents.": "Добавьте заголовки (H1, H2, H3), чтобы создать оглавление.", "Add headings (H1, H2, H3) to generate a table of contents.": "Добавьте заголовки (H1, H2, H3), чтобы создать оглавление."
"Share": "Поделиться",
"Public sharing": "Общий доступ",
"Shared by": "Поделился",
"Shared at": "Поделился в",
"Inherits public sharing from": "Наследует общий доступ от",
"Share to web": "Поделиться в интернете",
"Shared to web": "Размещено в интернете",
"Anyone with the link can view this page": "Любой, у кого есть ссылка, может просмотреть эту страницу",
"Make this page publicly accessible": "Сделать эту страницу общедоступной",
"Include sub-pages": "Включить подстраницы",
"Make sub-pages public too": "Сделать подстраницы также общедоступными",
"Allow search engines to index page": "Разрешить поисковым системам индексировать страницу",
"Open page": "Открыть страницу",
"Page": "Страница",
"Delete public share link": "Удалить ссылку на общий доступ",
"Delete share": "Удалить общий доступ",
"Are you sure you want to delete this shared link?": "Вы уверены, что хотите удалить эту ссылку общего доступа?",
"Publicly shared pages from spaces you are a member of will appear here": "Общие страницы из пространств, участником которых вы являетесь, появятся здесь",
"Share deleted successfully": "Общий доступ успешно удален",
"Share not found": "Общий доступ не найден",
"Failed to share page": "Не удалось поделиться страницей"
} }

View File

@ -298,7 +298,7 @@
"Heading 2": "2 级标题", "Heading 2": "2 级标题",
"Heading 3": "3 级标题", "Heading 3": "3 级标题",
"To-do List": "代办列表", "To-do List": "代办列表",
"Bullet List": "无列表", "Bullet List": "无列表",
"Numbered List": "有序列表", "Numbered List": "有序列表",
"Blockquote": "引用块", "Blockquote": "引用块",
"Just start typing with plain text.": "只需开始键入纯文本", "Just start typing with plain text.": "只需开始键入纯文本",
@ -362,26 +362,5 @@
"Move page to a different space.": "将页面移动到不同的空间。", "Move page to a different space.": "将页面移动到不同的空间。",
"Real-time editor connection lost. Retrying...": "实时编辑器连接丢失。重试中……", "Real-time editor connection lost. Retrying...": "实时编辑器连接丢失。重试中……",
"Table of contents": "目录", "Table of contents": "目录",
"Add headings (H1, H2, H3) to generate a table of contents.": "添加标题H1H2H3以生成目录。", "Add headings (H1, H2, H3) to generate a table of contents.": "添加标题H1H2H3以生成目录。"
"Share": "分享",
"Public sharing": "公开分享",
"Shared by": "分享者",
"Shared at": "分享时间",
"Inherits public sharing from": "继承自的公开分享",
"Share to web": "分享到网页",
"Shared to web": "已分享到网页",
"Anyone with the link can view this page": "任何有链接的人都可以查看此页面",
"Make this page publicly accessible": "使此页面可公开访问",
"Include sub-pages": "包括子页面",
"Make sub-pages public too": "将子页面也设为公开",
"Allow search engines to index page": "允许搜索引擎索引页面",
"Open page": "打开页面",
"Page": "页面",
"Delete public share link": "删除公开分享链接",
"Delete share": "删除分享",
"Are you sure you want to delete this shared link?": "您确定要删除此分享链接吗?",
"Publicly shared pages from spaces you are a member of will appear here": "您所在空间的公开共享页面会显示在此处",
"Share deleted successfully": "分享已成功删除",
"Share not found": "未找到分享",
"Failed to share page": "页面分享失败"
} }

View File

@ -30,12 +30,10 @@ import SharedPage from "@/pages/share/shared-page.tsx";
import Shares from "@/pages/settings/shares/shares.tsx"; import Shares from "@/pages/settings/shares/shares.tsx";
import ShareLayout from "@/features/share/components/share-layout.tsx"; import ShareLayout from "@/features/share/components/share-layout.tsx";
import ShareRedirect from '@/pages/share/share-redirect.tsx'; import ShareRedirect from '@/pages/share/share-redirect.tsx';
import { useTrackOrigin } from "@/hooks/use-track-origin";
export default function App() { export default function App() {
const { t } = useTranslation(); const { t } = useTranslation();
useRedirectToCloudSelect(); useRedirectToCloudSelect();
useTrackOrigin();
return ( return (
<> <>

View File

@ -14,6 +14,7 @@ import { AppHeader } from "@/components/layouts/global/app-header.tsx";
import Aside from "@/components/layouts/global/aside.tsx"; import Aside from "@/components/layouts/global/aside.tsx";
import classes from "./app-shell.module.css"; import classes from "./app-shell.module.css";
import { useTrialEndAction } from "@/ee/hooks/use-trial-end-action.tsx"; import { useTrialEndAction } from "@/ee/hooks/use-trial-end-action.tsx";
import { useClickOutside, useMergedRef } from "@mantine/hooks";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts"; import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
export default function GlobalAppShell({ export default function GlobalAppShell({
@ -29,6 +30,13 @@ export default function GlobalAppShell({
const [sidebarWidth, setSidebarWidth] = useAtom(sidebarWidthAtom); const [sidebarWidth, setSidebarWidth] = useAtom(sidebarWidthAtom);
const [isResizing, setIsResizing] = useState(false); const [isResizing, setIsResizing] = useState(false);
const sidebarRef = useRef(null); const sidebarRef = useRef(null);
const navbarOutsideRef = useClickOutside(() => {
if (mobileOpened) {
toggleMobile();
}
});
const mergedRef = useMergedRef(sidebarRef, navbarOutsideRef);
const startResizing = React.useCallback((mouseDownEvent) => { const startResizing = React.useCallback((mouseDownEvent) => {
mouseDownEvent.preventDefault(); mouseDownEvent.preventDefault();
@ -104,7 +112,7 @@ export default function GlobalAppShell({
<AppShell.Navbar <AppShell.Navbar
className={classes.navbar} className={classes.navbar}
withBorder={false} withBorder={false}
ref={sidebarRef} ref={mergedRef}
> >
<div className={classes.resizeHandle} onMouseDown={startResizing} /> <div className={classes.resizeHandle} onMouseDown={startResizing} />
{isSpaceRoute && <SpaceSidebar />} {isSpaceRoute && <SpaceSidebar />}

View File

@ -1,10 +0,0 @@
import { atom, WritableAtom } from "jotai";
export const settingsOriginAtom: WritableAtom<string | null, [string | null], void> = atom(
null,
(get, set, newValue) => {
if (get(settingsOriginAtom) !== newValue) {
set(settingsOriginAtom, newValue);
}
}
);

View File

@ -13,7 +13,7 @@ import {
IconKey, IconKey,
IconWorld, IconWorld,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { Link, useLocation } from "react-router-dom"; import { Link, useLocation, useNavigate } from "react-router-dom";
import classes from "./settings.module.css"; import classes from "./settings.module.css";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { isCloud } from "@/lib/config.ts"; import { isCloud } from "@/lib/config.ts";
@ -32,7 +32,6 @@ import {
import AppVersion from "@/components/settings/app-version.tsx"; import AppVersion from "@/components/settings/app-version.tsx";
import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts"; import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts"; import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
import { useSettingsNavigation } from "@/hooks/use-settings-navigation";
interface DataItem { interface DataItem {
label: string; label: string;
@ -106,7 +105,7 @@ export default function SettingsSidebar() {
const { t } = useTranslation(); const { t } = useTranslation();
const location = useLocation(); const location = useLocation();
const [active, setActive] = useState(location.pathname); const [active, setActive] = useState(location.pathname);
const { goBack } = useSettingsNavigation(); const navigate = useNavigate();
const { isAdmin } = useUserRole(); const { isAdmin } = useUserRole();
const [workspace] = useAtom(workspaceAtom); const [workspace] = useAtom(workspaceAtom);
const [mobileSidebarOpened] = useAtom(mobileSidebarAtom); const [mobileSidebarOpened] = useAtom(mobileSidebarAtom);
@ -211,12 +210,7 @@ export default function SettingsSidebar() {
<div className={classes.navbar}> <div className={classes.navbar}>
<Group className={classes.title} justify="flex-start"> <Group className={classes.title} justify="flex-start">
<ActionIcon <ActionIcon
onClick={() => { onClick={() => navigate(-1)}
goBack();
if (mobileSidebarOpened) {
toggleMobileSidebar();
}
}}
variant="transparent" variant="transparent"
c="gray" c="gray"
aria-label="Back" aria-label="Back"

View File

@ -1,7 +1,6 @@
import { Alert } from "@mantine/core"; import { Alert } from "@mantine/core";
import { useBillingQuery } from "@/ee/billing/queries/billing-query.ts"; import { useBillingQuery } from "@/ee/billing/queries/billing-query.ts";
import useTrial from "@/ee/hooks/use-trial.tsx"; import useTrial from "@/ee/hooks/use-trial.tsx";
import { getBillingTrialDays } from '@/lib/config.ts';
export default function BillingTrial() { export default function BillingTrial() {
const { data: billing, isLoading } = useBillingQuery(); const { data: billing, isLoading } = useBillingQuery();
@ -16,14 +15,14 @@ export default function BillingTrial() {
{trialDaysLeft > 0 && !billing && ( {trialDaysLeft > 0 && !billing && (
<Alert title="Your Trial is Active 🎉" color="blue" radius="md"> <Alert title="Your Trial is Active 🎉" color="blue" radius="md">
You have {trialDaysLeft} {trialDaysLeft === 1 ? "day" : "days"} left You have {trialDaysLeft} {trialDaysLeft === 1 ? "day" : "days"} left
in your {getBillingTrialDays()}-day free trial. Please subscribe to a paid plan before your trial in your 7-day trial. Please subscribe to a plan before your trial
ends. ends.
</Alert> </Alert>
)} )}
{trialDaysLeft === 0 && ( {trialDaysLeft === 0 && (
<Alert title="Your Trial has ended" color="red" radius="md"> <Alert title="Your Trial has ended" color="red" radius="md">
Your {getBillingTrialDays()}-day free trial has come to an end. Please subscribe to a paid plan to Your 7-day trial has come to an end. Please subscribe to a plan to
continue using this service. continue using this service.
</Alert> </Alert>
)} )}

View File

@ -1,6 +1,5 @@
export enum BillingPlan { export enum BillingPlan {
STANDARD = "standard", STANDARD = "standard",
BUSINESS = "business",
} }
export interface IBilling { export interface IBilling {

View File

@ -2,18 +2,14 @@ import { useAtom } from "jotai";
import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts"; import { workspaceAtom } from "@/features/user/atoms/current-user-atom.ts";
import { BillingPlan } from "@/ee/billing/types/billing.types.ts"; import { BillingPlan } from "@/ee/billing/types/billing.types.ts";
const usePlan = () => { export const usePlan = () => {
const [workspace] = useAtom(workspaceAtom); const [workspace] = useAtom(workspaceAtom);
const isStandard = const isStandard =
typeof workspace?.plan === "string" && typeof workspace?.plan === "string" &&
workspace?.plan.toLowerCase() === BillingPlan.STANDARD.toLowerCase(); workspace?.plan.toLowerCase() === BillingPlan.STANDARD.toLowerCase();
const isBusiness = return { isStandard };
typeof workspace?.plan === "string" &&
workspace?.plan.toLowerCase() === BillingPlan.BUSINESS.toLowerCase();
return { isStandard, isBusiness };
}; };
export default usePlan; export default usePlan;

View File

@ -1,6 +1,6 @@
import { useEffect } from "react"; import { useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom"; import { useLocation, useNavigate } from "react-router-dom";
import { getBillingTrialDays, isCloud } from "@/lib/config.ts"; import { isCloud } from "@/lib/config.ts";
import APP_ROUTE from "@/lib/app-route.ts"; import APP_ROUTE from "@/lib/app-route.ts";
import useUserRole from "@/hooks/use-user-role.tsx"; import useUserRole from "@/hooks/use-user-role.tsx";
import { notifications } from "@mantine/notifications"; import { notifications } from "@mantine/notifications";
@ -18,7 +18,7 @@ export const useTrialEndAction = () => {
notifications.show({ notifications.show({
position: "top-right", position: "top-right",
color: "red", color: "red",
title: `Your ${getBillingTrialDays()}-day trial has ended`, title: "Your 7-day trial has ended",
message: message:
"Please upgrade to a paid plan or contact your workspace admin.", "Please upgrade to a paid plan or contact your workspace admin.",
autoClose: false, autoClose: false,

View File

@ -15,7 +15,7 @@ export default function EnforceSso() {
<Text size="md">{t("Enforce SSO")}</Text> <Text size="md">{t("Enforce SSO")}</Text>
<Text size="sm" c="dimmed"> <Text size="sm" c="dimmed">
{t( {t(
"Once enforced, members will not be able to login with email and password.", "Once enforced, members will not able able to login with email and password.",
)} )}
</Text> </Text>
</div> </div>

View File

@ -10,13 +10,11 @@ import EnforceSso from "@/ee/security/components/enforce-sso.tsx";
import AllowedDomains from "@/ee/security/components/allowed-domains.tsx"; import AllowedDomains from "@/ee/security/components/allowed-domains.tsx";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import useLicense from "@/ee/hooks/use-license.tsx"; import useLicense from "@/ee/hooks/use-license.tsx";
import usePlan from "@/ee/hooks/use-plan.tsx";
export default function Security() { export default function Security() {
const { t } = useTranslation(); const { t } = useTranslation();
const { isAdmin } = useUserRole(); const { isAdmin } = useUserRole();
const { hasLicenseKey } = useLicense(); const { hasLicenseKey } = useLicense();
const { isBusiness } = usePlan();
if (!isAdmin) { if (!isAdmin) {
return null; return null;
@ -37,7 +35,8 @@ export default function Security() {
Single sign-on (SSO) Single sign-on (SSO)
</Title> </Title>
{(isCloud() && isBusiness) || (!isCloud() && hasLicenseKey) ? ( {/*TODO: revisit when we add a second plan */}
{!isCloud() && hasLicenseKey ? (
<> <>
<EnforceSso /> <EnforceSso />
<Divider my="lg" /> <Divider my="lg" />

View File

@ -1,4 +1,4 @@
import { Button, Group, Tooltip } from "@mantine/core"; import { Button, Group } from "@mantine/core";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
type CommentActionsProps = { type CommentActionsProps = {

View File

@ -15,7 +15,6 @@ import { asideStateAtom } from "@/components/layouts/global/hooks/atoms/sidebar-
import { useEditor } from "@tiptap/react"; import { useEditor } from "@tiptap/react";
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx"; import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useQueryEmit } from "@/features/websocket/use-query-emit";
interface CommentDialogProps { interface CommentDialogProps {
editor: ReturnType<typeof useEditor>; editor: ReturnType<typeof useEditor>;
@ -36,8 +35,6 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
const createCommentMutation = useCreateCommentMutation(); const createCommentMutation = useCreateCommentMutation();
const { isPending } = createCommentMutation; const { isPending } = createCommentMutation;
const emit = useQueryEmit();
const handleDialogClose = () => { const handleDialogClose = () => {
setShowCommentPopup(false); setShowCommentPopup(false);
editor.chain().focus().unsetCommentDecoration().run(); editor.chain().focus().unsetCommentDecoration().run();
@ -66,23 +63,11 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
.run(); .run();
setActiveCommentId(createdComment.id); setActiveCommentId(createdComment.id);
//unselect text to close bubble menu
editor.commands.setTextSelection({ from: editor.view.state.selection.from, to: editor.view.state.selection.from });
setAsideState({ tab: "comments", isAsideOpen: true }); setAsideState({ tab: "comments", isAsideOpen: true });
setTimeout(() => { setTimeout(() => {
const selector = `div[data-comment-id="${createdComment.id}"]`; const selector = `div[data-comment-id="${createdComment.id}"]`;
const commentElement = document.querySelector(selector); const commentElement = document.querySelector(selector);
commentElement?.scrollIntoView({ behavior: "smooth", block: "center" }); commentElement?.scrollIntoView();
editor.view.dispatch(
editor.state.tr.scrollIntoView()
);
}, 400);
emit({
operation: "invalidateComment",
pageId: pageId,
}); });
} finally { } finally {
setShowCommentPopup(false); setShowCommentPopup(false);
@ -124,7 +109,6 @@ function CommentDialog({ editor, pageId }: CommentDialogProps) {
<CommentEditor <CommentEditor
onUpdate={handleCommentEditorChange} onUpdate={handleCommentEditorChange}
onSave={handleAddComment}
placeholder={t("Write a comment")} placeholder={t("Write a comment")}
editable={true} editable={true}
autofocus={true} autofocus={true}

View File

@ -8,12 +8,10 @@ import { useFocusWithin } from "@mantine/hooks";
import clsx from "clsx"; import clsx from "clsx";
import { forwardRef, useEffect, useImperativeHandle } from "react"; import { forwardRef, useEffect, useImperativeHandle } from "react";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import EmojiCommand from "@/features/editor/extensions/emoji-command";
interface CommentEditorProps { interface CommentEditorProps {
defaultContent?: any; defaultContent?: any;
onUpdate?: any; onUpdate?: any;
onSave?: any;
editable: boolean; editable: boolean;
placeholder?: string; placeholder?: string;
autofocus?: boolean; autofocus?: boolean;
@ -24,7 +22,6 @@ const CommentEditor = forwardRef(
{ {
defaultContent, defaultContent,
onUpdate, onUpdate,
onSave,
editable, editable,
placeholder, placeholder,
autofocus, autofocus,
@ -45,35 +42,7 @@ const CommentEditor = forwardRef(
}), }),
Underline, Underline,
Link, Link,
EmojiCommand,
], ],
editorProps: {
handleDOMEvents: {
keydown: (_view, event) => {
if (
[
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"Enter",
].includes(event.key)
) {
const emojiCommand = document.querySelector("#emoji-command");
if (emojiCommand) {
return true;
}
}
if ((event.ctrlKey || event.metaKey) && event.key === "Enter") {
event.preventDefault();
if (onSave) onSave();
return true;
}
},
},
},
onUpdate({ editor }) { onUpdate({ editor }) {
if (onUpdate) onUpdate(editor.getJSON()); if (onUpdate) onUpdate(editor.getJSON());
}, },
@ -84,10 +53,6 @@ const CommentEditor = forwardRef(
autofocus: (autofocus && "end") || false, autofocus: (autofocus && "end") || false,
}); });
useEffect(() => {
commentEditor.commands.setContent(defaultContent);
}, [defaultContent]);
useEffect(() => { useEffect(() => {
setTimeout(() => { setTimeout(() => {
if (autofocus) { if (autofocus) {

View File

@ -1,5 +1,5 @@
import { Group, Text, Box } from "@mantine/core"; import { Group, Text, Box } from "@mantine/core";
import React, { useEffect, useState } from "react"; import React, { useState } from "react";
import classes from "./comment.module.css"; import classes from "./comment.module.css";
import { useAtom, useAtomValue } from "jotai"; import { useAtom, useAtomValue } from "jotai";
import { timeAgo } from "@/lib/time"; import { timeAgo } from "@/lib/time";
@ -15,14 +15,12 @@ import {
import { IComment } from "@/features/comment/types/comment.types"; import { IComment } from "@/features/comment/types/comment.types";
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx"; import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts"; import { currentUserAtom } from "@/features/user/atoms/current-user-atom.ts";
import { useQueryEmit } from "@/features/websocket/use-query-emit";
interface CommentListItemProps { interface CommentListItemProps {
comment: IComment; comment: IComment;
pageId: string;
} }
function CommentListItem({ comment, pageId }: CommentListItemProps) { function CommentListItem({ comment }: CommentListItemProps) {
const { hovered, ref } = useHover(); const { hovered, ref } = useHover();
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
@ -31,11 +29,6 @@ function CommentListItem({ comment, pageId }: CommentListItemProps) {
const updateCommentMutation = useUpdateCommentMutation(); const updateCommentMutation = useUpdateCommentMutation();
const deleteCommentMutation = useDeleteCommentMutation(comment.pageId); const deleteCommentMutation = useDeleteCommentMutation(comment.pageId);
const [currentUser] = useAtom(currentUserAtom); const [currentUser] = useAtom(currentUserAtom);
const emit = useQueryEmit();
useEffect(() => {
setContent(comment.content)
}, [comment]);
async function handleUpdateComment() { async function handleUpdateComment() {
try { try {
@ -46,11 +39,6 @@ function CommentListItem({ comment, pageId }: CommentListItemProps) {
}; };
await updateCommentMutation.mutateAsync(commentToUpdate); await updateCommentMutation.mutateAsync(commentToUpdate);
setIsEditing(false); setIsEditing(false);
emit({
operation: "invalidateComment",
pageId: pageId,
});
} catch (error) { } catch (error) {
console.error("Failed to update comment:", error); console.error("Failed to update comment:", error);
} finally { } finally {
@ -62,27 +50,11 @@ function CommentListItem({ comment, pageId }: CommentListItemProps) {
try { try {
await deleteCommentMutation.mutateAsync(comment.id); await deleteCommentMutation.mutateAsync(comment.id);
editor?.commands.unsetComment(comment.id); editor?.commands.unsetComment(comment.id);
emit({
operation: "invalidateComment",
pageId: pageId,
});
} catch (error) { } catch (error) {
console.error("Failed to delete comment:", error); console.error("Failed to delete comment:", error);
} }
} }
function handleCommentClick(comment: IComment) {
const el = document.querySelector(`.comment-mark[data-comment-id="${comment.id}"]`);
if (el) {
el.scrollIntoView({ behavior: "smooth", block: "center" });
el.classList.add("comment-highlight");
setTimeout(() => {
el.classList.remove("comment-highlight");
}, 3000);
}
}
function handleEditToggle() { function handleEditToggle() {
setIsEditing(true); setIsEditing(true);
} }
@ -127,7 +99,7 @@ function CommentListItem({ comment, pageId }: CommentListItemProps) {
<div> <div>
{!comment.parentCommentId && comment?.selection && ( {!comment.parentCommentId && comment?.selection && (
<Box className={classes.textSelection} onClick={() => handleCommentClick(comment)}> <Box className={classes.textSelection}>
<Text size="sm">{comment?.selection}</Text> <Text size="sm">{comment?.selection}</Text>
</Box> </Box>
)} )}
@ -140,7 +112,6 @@ function CommentListItem({ comment, pageId }: CommentListItemProps) {
defaultContent={content} defaultContent={content}
editable={true} editable={true}
onUpdate={(newContent: any) => setContent(newContent)} onUpdate={(newContent: any) => setContent(newContent)}
onSave={handleUpdateComment}
autofocus={true} autofocus={true}
/> />

View File

@ -14,7 +14,6 @@ import { usePageQuery } from "@/features/page/queries/page-query.ts";
import { IPagination } from "@/lib/types.ts"; import { IPagination } from "@/lib/types.ts";
import { extractPageSlugId } from "@/lib"; import { extractPageSlugId } from "@/lib";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useQueryEmit } from "@/features/websocket/use-query-emit";
function CommentList() { function CommentList() {
const { t } = useTranslation(); const { t } = useTranslation();
@ -27,7 +26,6 @@ function CommentList() {
} = useCommentsQuery({ pageId: page?.id, limit: 100 }); } = useCommentsQuery({ pageId: page?.id, limit: 100 });
const createCommentMutation = useCreateCommentMutation(); const createCommentMutation = useCreateCommentMutation();
const [isLoading, setIsLoading] = useState(false); const [isLoading, setIsLoading] = useState(false);
const emit = useQueryEmit();
const handleAddReply = useCallback( const handleAddReply = useCallback(
async (commentId: string, content: string) => { async (commentId: string, content: string) => {
@ -40,11 +38,6 @@ function CommentList() {
}; };
await createCommentMutation.mutateAsync(commentData); await createCommentMutation.mutateAsync(commentData);
emit({
operation: "invalidateComment",
pageId: page?.id,
});
} catch (error) { } catch (error) {
console.error("Failed to post comment:", error); console.error("Failed to post comment:", error);
} finally { } finally {
@ -66,8 +59,8 @@ function CommentList() {
data-comment-id={comment.id} data-comment-id={comment.id}
> >
<div> <div>
<CommentListItem comment={comment} pageId={page?.id} /> <CommentListItem comment={comment} />
<MemoizedChildComments comments={comments} parentId={comment.id} pageId={page?.id} /> <MemoizedChildComments comments={comments} parentId={comment.id} />
</div> </div>
<Divider my={4} /> <Divider my={4} />
@ -106,9 +99,8 @@ function CommentList() {
interface ChildCommentsProps { interface ChildCommentsProps {
comments: IPagination<IComment>; comments: IPagination<IComment>;
parentId: string; parentId: string;
pageId: string;
} }
const ChildComments = ({ comments, parentId, pageId }: ChildCommentsProps) => { const ChildComments = ({ comments, parentId }: ChildCommentsProps) => {
const getChildComments = useCallback( const getChildComments = useCallback(
(parentId: string) => (parentId: string) =>
comments.items.filter( comments.items.filter(
@ -121,11 +113,10 @@ const ChildComments = ({ comments, parentId, pageId }: ChildCommentsProps) => {
<div> <div>
{getChildComments(parentId).map((childComment) => ( {getChildComments(parentId).map((childComment) => (
<div key={childComment.id}> <div key={childComment.id}>
<CommentListItem comment={childComment} pageId={pageId} /> <CommentListItem comment={childComment} />
<MemoizedChildComments <MemoizedChildComments
comments={comments} comments={comments}
parentId={childComment.id} parentId={childComment.id}
pageId={pageId}
/> />
</div> </div>
))} ))}
@ -151,7 +142,6 @@ const CommentEditorWithActions = ({ commentId, onSave, isLoading }) => {
<CommentEditor <CommentEditor
ref={commentEditorRef} ref={commentEditorRef}
onUpdate={setContent} onUpdate={setContent}
onSave={handleSave}
editable={true} editable={true}
/> />
{focused && <CommentActions onSave={handleSave} isLoading={isLoading} />} {focused && <CommentActions onSave={handleSave} isLoading={isLoading} />}

View File

@ -11,25 +11,22 @@
border-left: 2px solid var(--mantine-color-gray-6); border-left: 2px solid var(--mantine-color-gray-6);
padding: 8px; padding: 8px;
background: var(--mantine-color-gray-light); background: var(--mantine-color-gray-light);
cursor: pointer;
} }
.commentEditor { .commentEditor {
.focused { .focused {
border-radius: var(--mantine-radius-sm);
box-shadow: 0 0 0 2px var(--mantine-color-blue-3); box-shadow: 0 0 0 2px var(--mantine-color-blue-3);
} }
.ProseMirror :global(.ProseMirror){ .ProseMirror :global(.ProseMirror){
border-radius: var(--mantine-radius-sm);
max-width: 100%; max-width: 100%;
white-space: pre-wrap; white-space: pre-wrap;
word-break: break-word; word-break: break-word;
max-height: 20vh; max-height: 20vh;
padding-left: 6px; padding-left: 6px;
padding-right: 6px; padding-right: 6px;
margin-top: 10px; margin-top: 2px;
margin-bottom: 2px; margin-bottom: 2px;
overflow: hidden auto; overflow: hidden auto;
} }

View File

@ -15,10 +15,13 @@ import {
import { IconEdit } from "@tabler/icons-react"; import { IconEdit } from "@tabler/icons-react";
import { z } from "zod"; import { z } from "zod";
import { useForm, zodResolver } from "@mantine/form"; import { useForm, zodResolver } from "@mantine/form";
import {
getEmbedProviderById,
getEmbedUrlAndProvider,
} from "@/features/editor/components/embed/providers.ts";
import { notifications } from "@mantine/notifications"; import { notifications } from "@mantine/notifications";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import i18n from "i18next"; import i18n from "i18next";
import { getEmbedProviderById, getEmbedUrlAndProvider } from '@docmost/editor-ext';
const schema = z.object({ const schema = z.object({
url: z url: z

View File

@ -7,109 +7,102 @@ export interface IEmbedProvider {
export const embedProviders: IEmbedProvider[] = [ export const embedProviders: IEmbedProvider[] = [
{ {
id: "loom", id: 'loom',
name: "Loom", name: 'Loom',
regex: /^https?:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-zA-Z]+)\/?/, regex: /^https?:\/\/(?:www\.)?loom\.com\/(?:share|embed)\/([\da-zA-Z]+)\/?/,
getEmbedUrl: (match, url) => { getEmbedUrl: (match, url) => {
if (url.includes("/embed/")) { if(url.includes("/embed/")){
return url; return url;
} }
return `https://loom.com/embed/${match[1]}`; return `https://loom.com/embed/${match[1]}`;
}, }
}, },
{ {
id: "airtable", id: 'airtable',
name: "Airtable", name: 'Airtable',
regex: /^https:\/\/(www.)?airtable.com\/([a-zA-Z0-9]{2,})\/.*/, regex: /^https:\/\/(www.)?airtable.com\/([a-zA-Z0-9]{2,})\/.*/,
getEmbedUrl: (match, url: string) => { getEmbedUrl: (match, url: string) => {
const path = url.split("airtable.com/"); const path = url.split('airtable.com/');
if (url.includes("/embed/")) { if(url.includes("/embed/")){
return url; return url;
} }
return `https://airtable.com/embed/${path[1]}`; return `https://airtable.com/embed/${path[1]}`;
}, }
}, },
{ {
id: "figma", id: 'figma',
name: "Figma", name: 'Figma',
regex: regex: /^https:\/\/[\w\.-]+\.?figma.com\/(file|proto|board|design|slides|deck)\/([0-9a-zA-Z]{22,128})/,
/^https:\/\/[\w\.-]+\.?figma.com\/(file|proto|board|design|slides|deck)\/([0-9a-zA-Z]{22,128})/,
getEmbedUrl: (match, url: string) => { getEmbedUrl: (match, url: string) => {
return `https://www.figma.com/embed?url=${url}&embed_host=docmost`; return `https://www.figma.com/embed?url=${url}&embed_host=docmost`;
}, }
}, },
{ {
id: "typeform", 'id': 'typeform',
name: "Typeform", name: 'Typeform',
regex: /^(https?:)?(\/\/)?[\w\.]+\.typeform\.com\/to\/.+/, regex: /^(https?:)?(\/\/)?[\w\.]+\.typeform\.com\/to\/.+/,
getEmbedUrl: (match, url: string) => { getEmbedUrl: (match, url: string) => {
return url; return url;
}, }
}, },
{ {
id: "miro", id: 'miro',
name: "Miro", name: 'Miro',
regex: /^https:\/\/(www\.)?miro\.com\/app\/board\/([\w-]+=)/, regex: /^https:\/\/(www\.)?miro\.com\/app\/board\/([\w-]+=)/,
getEmbedUrl: (match, url) => { getEmbedUrl: (match, url) => {
if (url.includes("/live-embed/")) { if(url.includes("/live-embed/")){
return url; return url;
} }
return `https://miro.com/app/live-embed/${match[2]}?embedMode=view_only_without_ui&autoplay=true&embedSource=docmost`; return `https://miro.com/app/live-embed/${match[2]}?embedMode=view_only_without_ui&autoplay=true&embedSource=docmost`;
}, }
}, },
{ {
id: "youtube", id: 'youtube',
name: "YouTube", name: 'YouTube',
regex: regex: /^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/,
/^((?:https?:)?\/\/)?((?:www|m|music)\.)?((?:youtube\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/,
getEmbedUrl: (match, url) => { getEmbedUrl: (match, url) => {
if (url.includes("/embed/")) { if (url.includes("/embed/")){
return url; return url;
} }
return `https://www.youtube-nocookie.com/embed/${match[5]}`; return `https://www.youtube-nocookie.com/embed/${match[5]}`;
}, }
}, },
{ {
id: "vimeo", id: 'vimeo',
name: "Vimeo", name: 'Vimeo',
regex: regex: /^(https:)?\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)/,
/^(https:)?\/\/(?:www\.|player\.)?vimeo.com\/(?:channels\/(?:\w+\/)?|groups\/([^/]*)\/videos\/|album\/(\d+)\/video\/|video\/|)(\d+)/,
getEmbedUrl: (match) => { getEmbedUrl: (match) => {
return `https://player.vimeo.com/video/${match[4]}`; return `https://player.vimeo.com/video/${match[4]}`;
}, }
}, },
{ {
id: "framer", id: 'framer',
name: "Framer", name: 'Framer',
regex: /^https:\/\/(www\.)?framer\.com\/embed\/([\w-]+)/, regex: /^https:\/\/(www\.)?framer\.com\/embed\/([\w-]+)/,
getEmbedUrl: (match, url: string) => { getEmbedUrl: (match, url: string) => {
return url; return url;
}, }
}, },
{ {
id: "gdrive", id: 'gdrive',
name: "Google Drive", name: 'Google Drive',
regex: regex: /^((?:https?:)?\/\/)?((?:www|m)\.)?(drive\.google\.com)\/file\/d\/([a-zA-Z0-9_-]+)\/.*$/,
/^((?:https?:)?\/\/)?((?:www|m)\.)?(drive\.google\.com)\/file\/d\/([a-zA-Z0-9_-]+)\/.*$/,
getEmbedUrl: (match) => { getEmbedUrl: (match) => {
return `https://drive.google.com/file/d/${match[4]}/preview`; return `https://drive.google.com/file/d/${match[4]}/preview`;
}, }
}, },
{ {
id: "gsheets", id: 'gsheets',
name: "Google Sheets", name: 'Google Sheets',
regex: regex: /^((?:https?:)?\/\/)?((?:www|m)\.)?(docs\.google\.com)\/spreadsheets\/d\/e\/([a-zA-Z0-9_-]+)\/.*$/,
/^((?:https?:)?\/\/)?((?:www|m)\.)?(docs\.google\.com)\/spreadsheets\/d\/e\/([a-zA-Z0-9_-]+)\/.*$/,
getEmbedUrl: (match, url: string) => { getEmbedUrl: (match, url: string) => {
return url; return url
}, }
}, },
]; ];
export function getEmbedProviderById(id: string) { export function getEmbedProviderById(id: string) {
return embedProviders.find( return embedProviders.find(provider => provider.id.toLowerCase() === id.toLowerCase());
(provider) => provider.id.toLowerCase() === id.toLowerCase(),
);
} }
export interface IEmbedResult { export interface IEmbedResult {
@ -123,12 +116,14 @@ export function getEmbedUrlAndProvider(url: string): IEmbedResult {
if (match) { if (match) {
return { return {
embedUrl: provider.getEmbedUrl(match, url), embedUrl: provider.getEmbedUrl(match, url),
provider: provider.name.toLowerCase(), provider: provider.name.toLowerCase()
}; };
} }
} }
return { return {
embedUrl: url, embedUrl: url,
provider: "iframe", provider: 'iframe',
}; };
} }

View File

@ -33,7 +33,7 @@ const renderEmojiItems = () => {
showOnCreate: true, showOnCreate: true,
interactive: true, interactive: true,
trigger: "manual", trigger: "manual",
placement: "bottom", placement: "bottom-start",
}); });
}, },
onStart: (props: { onStart: (props: {

View File

@ -3,7 +3,6 @@ import React, {
useCallback, useCallback,
useEffect, useEffect,
useImperativeHandle, useImperativeHandle,
useMemo,
useRef, useRef,
useState, useState,
} from "react"; } from "react";
@ -19,7 +18,7 @@ import {
import clsx from "clsx"; import clsx from "clsx";
import classes from "./mention.module.css"; import classes from "./mention.module.css";
import { CustomAvatar } from "@/components/ui/custom-avatar.tsx"; import { CustomAvatar } from "@/components/ui/custom-avatar.tsx";
import { IconFileDescription, IconPlus } from "@tabler/icons-react"; import { IconFileDescription } from "@tabler/icons-react";
import { useSpaceQuery } from "@/features/space/queries/space-query.ts"; import { useSpaceQuery } from "@/features/space/queries/space-query.ts";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { v7 as uuid7 } from "uuid"; import { v7 as uuid7 } from "uuid";
@ -29,28 +28,14 @@ import {
MentionListProps, MentionListProps,
MentionSuggestionItem, MentionSuggestionItem,
} from "@/features/editor/components/mention/mention.type.ts"; } from "@/features/editor/components/mention/mention.type.ts";
import { IPage } from "@/features/page/types/page.types";
import { useCreatePageMutation, usePageQuery } from "@/features/page/queries/page-query";
import { treeDataAtom } from "@/features/page/tree/atoms/tree-data-atom";
import { SimpleTree } from "react-arborist";
import { SpaceTreeNode } from "@/features/page/tree/types";
import { useTranslation } from "react-i18next";
import { useQueryEmit } from "@/features/websocket/use-query-emit";
import { extractPageSlugId } from "@/lib";
const MentionList = forwardRef<any, MentionListProps>((props, ref) => { const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
const [selectedIndex, setSelectedIndex] = useState(1); const [selectedIndex, setSelectedIndex] = useState(1);
const viewportRef = useRef<HTMLDivElement>(null); const viewportRef = useRef<HTMLDivElement>(null);
const { pageSlug, spaceSlug } = useParams(); const { spaceSlug } = useParams();
const { data: page } = usePageQuery({ pageId: extractPageSlugId(pageSlug) });
const { data: space } = useSpaceQuery(spaceSlug); const { data: space } = useSpaceQuery(spaceSlug);
const [currentUser] = useAtom(currentUserAtom); const [currentUser] = useAtom(currentUserAtom);
const [renderItems, setRenderItems] = useState<MentionSuggestionItem[]>([]); const [renderItems, setRenderItems] = useState<MentionSuggestionItem[]>([]);
const { t } = useTranslation();
const [data, setData] = useAtom(treeDataAtom);
const tree = useMemo(() => new SimpleTree<SpaceTreeNode>(data), [data]);
const createPageMutation = useCreatePageMutation();
const emit = useQueryEmit();
const { data: suggestion, isLoading } = useSearchSuggestionsQuery({ const { data: suggestion, isLoading } = useSearchSuggestionsQuery({
query: props.query, query: props.query,
@ -60,23 +45,12 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
limit: 10, limit: 10,
}); });
const createPageItem = (label: string) : MentionSuggestionItem => {
return {
id: null,
label: label,
entityType: "page",
entityId: null,
slugId: null,
icon: null,
}
}
useEffect(() => { useEffect(() => {
if (suggestion && !isLoading) { if (suggestion && !isLoading) {
let items: MentionSuggestionItem[] = []; let items: MentionSuggestionItem[] = [];
if (suggestion?.users?.length > 0) { if (suggestion?.users?.length > 0) {
items.push({ entityType: "header", label: t("Users") }); items.push({ entityType: "header", label: "Users" });
items = items.concat( items = items.concat(
suggestion.users.map((user) => ({ suggestion.users.map((user) => ({
@ -90,7 +64,7 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
} }
if (suggestion?.pages?.length > 0) { if (suggestion?.pages?.length > 0) {
items.push({ entityType: "header", label: t("Pages") }); items.push({ entityType: "header", label: "Pages" });
items = items.concat( items = items.concat(
suggestion.pages.map((page) => ({ suggestion.pages.map((page) => ({
id: uuid7(), id: uuid7(),
@ -102,7 +76,6 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
})), })),
); );
} }
items.push(createPageItem(props.query));
setRenderItems(items); setRenderItems(items);
// update editor storage // update editor storage
@ -123,7 +96,7 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
creatorId: currentUser?.user.id, creatorId: currentUser?.user.id,
}); });
} }
if (item.entityType === "page" && item.id!==null) { if (item.entityType === "page") {
props.command({ props.command({
id: item.id, id: item.id,
label: item.label || "Untitled", label: item.label || "Untitled",
@ -133,9 +106,6 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
creatorId: currentUser?.user.id, creatorId: currentUser?.user.id,
}); });
} }
if (item.entityType === "page" && item.id===null) {
createPage(item.label);
}
} }
}, },
[renderItems], [renderItems],
@ -197,58 +167,6 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
}, },
})); }));
const createPage = async (title: string) => {
const payload: { spaceId: string; parentPageId?: string; title: string } = {
spaceId: space.id,
parentPageId: page.id || null,
title: title
};
let createdPage: IPage;
try {
createdPage = await createPageMutation.mutateAsync(payload);
const parentId = page.id || null;
const data = {
id: createdPage.id,
slugId: createdPage.slugId,
name: createdPage.title,
position: createdPage.position,
spaceId: createdPage.spaceId,
parentPageId: createdPage.parentPageId,
children: [],
} as any;
const lastIndex = tree.data.length;
tree.create({ parentId, index: lastIndex, data });
setData(tree.data);
props.command({
id: uuid7(),
label: createdPage.title || "Untitled",
entityType: "page",
entityId: createdPage.id,
slugId: createdPage.slugId,
creatorId: currentUser?.user.id,
});
setTimeout(() => {
emit({
operation: "addTreeNode",
spaceId: space.id,
payload: {
parentId,
index: lastIndex,
data,
},
});
}, 50);
} catch (err) {
throw new Error("Failed to create page");
}
}
// if no results and enter what to do? // if no results and enter what to do?
useEffect(() => { useEffect(() => {
@ -260,7 +178,7 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
if (renderItems.length === 0) { if (renderItems.length === 0) {
return ( return (
<Paper shadow="md" p="xs" withBorder> <Paper shadow="md" p="xs" withBorder>
{ t("No results") } No results
</Paper> </Paper>
); );
} }
@ -330,14 +248,14 @@ const MentionList = forwardRef<any, MentionListProps>((props, ref) => {
color="gray" color="gray"
size={18} size={18}
> >
{ (item.id) ? <IconFileDescription size={18} /> : <IconPlus size={18} /> } <IconFileDescription size={18} />
</ActionIcon> </ActionIcon>
)} )}
</ActionIcon> </ActionIcon>
<div style={{ flex: 1 }}> <div style={{ flex: 1 }}>
<Text size="sm" fw={500}> <Text size="sm" fw={500}>
{ (item.id) ? item.label : t("Create page") + ': ' + item.label } {item.label}
</Text> </Text>
</div> </div>
</Group> </Group>

View File

@ -143,12 +143,6 @@ export const TableOfContents: FC<TableOfContentsProps> = (props) => {
{t("Add headings (H1, H2, H3) to generate a table of contents.")} {t("Add headings (H1, H2, H3) to generate a table of contents.")}
</Text> </Text>
)} )}
{props.isShare && (
<Text size="sm" c="dimmed">
{t("No table of contents.")}
</Text>
)}
</> </>
); );
} }

View File

@ -58,7 +58,6 @@ import ExcalidrawView from "@/features/editor/components/excalidraw/excalidraw-v
import EmbedView from "@/features/editor/components/embed/embed-view.tsx"; import EmbedView from "@/features/editor/components/embed/embed-view.tsx";
import plaintext from "highlight.js/lib/languages/plaintext"; import plaintext from "highlight.js/lib/languages/plaintext";
import powershell from "highlight.js/lib/languages/powershell"; import powershell from "highlight.js/lib/languages/powershell";
import abap from "highlightjs-sap-abap";
import elixir from "highlight.js/lib/languages/elixir"; import elixir from "highlight.js/lib/languages/elixir";
import erlang from "highlight.js/lib/languages/erlang"; import erlang from "highlight.js/lib/languages/erlang";
import dockerfile from "highlight.js/lib/languages/dockerfile"; import dockerfile from "highlight.js/lib/languages/dockerfile";
@ -77,7 +76,7 @@ import { CharacterCount } from "@tiptap/extension-character-count";
const lowlight = createLowlight(common); const lowlight = createLowlight(common);
lowlight.register("mermaid", plaintext); lowlight.register("mermaid", plaintext);
lowlight.register("powershell", powershell); lowlight.register("powershell", powershell);
lowlight.register("abap", abap); lowlight.register("powershell", powershell);
lowlight.register("erlang", erlang); lowlight.register("erlang", erlang);
lowlight.register("elixir", elixir); lowlight.register("elixir", elixir);
lowlight.register("dockerfile", dockerfile); lowlight.register("dockerfile", dockerfile);

View File

@ -219,12 +219,9 @@ export default function PageEditor({
setActiveCommentId(commentId); setActiveCommentId(commentId);
setAsideState({ tab: "comments", isAsideOpen: true }); setAsideState({ tab: "comments", isAsideOpen: true });
//wait if aside is closed const selector = `div[data-comment-id="${commentId}"]`;
setTimeout(() => { const commentElement = document.querySelector(selector);
const selector = `div[data-comment-id="${commentId}"]`; commentElement?.scrollIntoView();
const commentElement = document.querySelector(selector);
commentElement?.scrollIntoView({ behavior: "smooth", block: "center" });
}, 400);
}; };
useEffect(() => { useEffect(() => {

View File

@ -144,19 +144,6 @@
border-bottom: 2px solid rgb(166, 158, 12); border-bottom: 2px solid rgb(166, 158, 12);
} }
.comment-highlight {
animation: flash-highlight 3s ease-out;
}
@keyframes flash-highlight {
0% {
background-color: #ff4d4d;
}
100% {
background-color: rgba(255, 215, 0, 0.14);
}
}
.resize-cursor { .resize-cursor {
cursor: ew-resize; cursor: ew-resize;
cursor: col-resize; cursor: col-resize;

View File

@ -47,7 +47,7 @@
.column-resize-handle { .column-resize-handle {
background-color: #adf; background-color: #adf;
bottom: -1px; bottom: -2px;
position: absolute; position: absolute;
right: -2px; right: -2px;
pointer-events: none; pointer-events: none;

View File

@ -10,7 +10,7 @@ import {
pageEditorAtom, pageEditorAtom,
titleEditorAtom, titleEditorAtom,
} from "@/features/editor/atoms/editor-atoms"; } from "@/features/editor/atoms/editor-atoms";
import { updatePageData, useUpdateTitlePageMutation } from "@/features/page/queries/page-query"; import { useUpdatePageMutation } from "@/features/page/queries/page-query";
import { useDebouncedCallback } from "@mantine/hooks"; import { useDebouncedCallback } from "@mantine/hooks";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { useQueryEmit } from "@/features/websocket/use-query-emit.ts"; import { useQueryEmit } from "@/features/websocket/use-query-emit.ts";
@ -38,7 +38,7 @@ export function TitleEditor({
editable, editable,
}: TitleEditorProps) { }: TitleEditorProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const { mutateAsync: updateTitlePageMutationAsync } = useUpdateTitlePageMutation(); const { mutateAsync: updatePageMutationAsync } = useUpdatePageMutation();
const pageEditor = useAtomValue(pageEditorAtom); const pageEditor = useAtomValue(pageEditorAtom);
const [, setTitleEditor] = useAtom(titleEditorAtom); const [, setTitleEditor] = useAtom(titleEditorAtom);
const emit = useQueryEmit(); const emit = useQueryEmit();
@ -94,7 +94,7 @@ export function TitleEditor({
return; return;
} }
updateTitlePageMutationAsync({ updatePageMutationAsync({
pageId: pageId, pageId: pageId,
title: titleEditor.getText(), title: titleEditor.getText(),
}).then((page) => { }).then((page) => {
@ -106,10 +106,6 @@ export function TitleEditor({
payload: { title: page.title, slugId: page.slugId }, payload: { title: page.title, slugId: page.slugId },
}; };
if (page.title !== titleEditor.getText()) return;
updatePageData(page);
localEmitter.emit("message", event); localEmitter.emit("message", event);
emit(event); emit(event);
}); });

View File

@ -1,105 +0,0 @@
import { Modal, Button, Group, Text } from "@mantine/core";
import { copyPageToSpace } from "@/features/page/services/page-service.ts";
import { useState } from "react";
import { notifications } from "@mantine/notifications";
import { useTranslation } from "react-i18next";
import { ISpace } from "@/features/space/types/space.types.ts";
import { queryClient } from "@/main.tsx";
import { SpaceSelect } from "@/features/space/components/sidebar/space-select.tsx";
import { useNavigate } from "react-router-dom";
import { buildPageUrl } from "@/features/page/page.utils.ts";
interface CopyPageModalProps {
pageId: string;
currentSpaceSlug: string;
open: boolean;
onClose: () => void;
}
export default function CopyPageModal({
pageId,
currentSpaceSlug,
open,
onClose,
}: CopyPageModalProps) {
const { t } = useTranslation();
const [targetSpace, setTargetSpace] = useState<ISpace>(null);
const navigate = useNavigate();
const handleCopy = async () => {
if (!targetSpace) return;
try {
const copiedPage = await copyPageToSpace({
pageId,
spaceId: targetSpace.id,
});
queryClient.removeQueries({
predicate: (item) =>
["pages", "sidebar-pages", "root-sidebar-pages"].includes(
item.queryKey[0] as string,
),
});
const pageUrl = buildPageUrl(
copiedPage.space.slug,
copiedPage.slugId,
copiedPage.title,
);
navigate(pageUrl);
notifications.show({
message: t("Page copied successfully"),
});
onClose();
setTargetSpace(null);
} catch (err) {
notifications.show({
message: err.response?.data.message || "An error occurred",
color: "red",
});
console.log(err);
}
};
const handleChange = (space: ISpace) => {
setTargetSpace(space);
};
return (
<Modal.Root
opened={open}
onClose={onClose}
size={500}
padding="xl"
yOffset="10vh"
xOffset={0}
mah={400}
onClick={(e) => e.stopPropagation()}
>
<Modal.Overlay />
<Modal.Content style={{ overflow: "hidden" }}>
<Modal.Header py={0}>
<Modal.Title fw={500}>{t("Copy page")}</Modal.Title>
<Modal.CloseButton />
</Modal.Header>
<Modal.Body>
<Text mb="xs" c="dimmed" size="sm">
{t("Copy page to a different space.")}
</Text>
<SpaceSelect
value={currentSpaceSlug}
clearable={false}
onChange={handleChange}
/>
<Group justify="end" mt="md">
<Button onClick={onClose} variant="default">
{t("Cancel")}
</Button>
<Button onClick={handleCopy}>{t("Copy")}</Button>
</Group>
</Modal.Body>
</Modal.Content>
</Modal.Root>
);
}

View File

@ -12,7 +12,7 @@ import {
IconTrash, IconTrash,
IconWifiOff, IconWifiOff,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import React from "react"; import React, { useEffect } from "react";
import useToggleAside from "@/hooks/use-toggle-aside.tsx"; import useToggleAside from "@/hooks/use-toggle-aside.tsx";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { historyAtoms } from "@/features/page-history/atoms/history-atoms.ts"; import { historyAtoms } from "@/features/page-history/atoms/history-atoms.ts";
@ -35,7 +35,7 @@ import {
import { formattedDate, timeAgo } from "@/lib/time.ts"; import { formattedDate, timeAgo } from "@/lib/time.ts";
import MovePageModal from "@/features/page/components/move-page-modal.tsx"; import MovePageModal from "@/features/page/components/move-page-modal.tsx";
import { useTimeAgo } from "@/hooks/use-time-ago.tsx"; import { useTimeAgo } from "@/hooks/use-time-ago.tsx";
import ShareModal from "@/features/share/components/share-modal.tsx"; import ShareModal from '@/features/share/components/share-modal.tsx';
interface PageHeaderMenuProps { interface PageHeaderMenuProps {
readOnly?: boolean; readOnly?: boolean;
@ -59,7 +59,7 @@ export default function PageHeaderMenu({ readOnly }: PageHeaderMenuProps) {
</Tooltip> </Tooltip>
)} )}
<ShareModal readOnly={readOnly} /> <ShareModal readOnly={readOnly}/>
<Tooltip label={t("Comments")} openDelay={250} withArrow> <Tooltip label={t("Comments")} openDelay={250} withArrow>
<ActionIcon <ActionIcon
@ -106,7 +106,7 @@ function PageActionMenu({ readOnly }: PageActionMenuProps) {
{ open: openMovePageModal, close: closeMoveSpaceModal }, { open: openMovePageModal, close: closeMoveSpaceModal },
] = useDisclosure(false); ] = useDisclosure(false);
const [pageEditor] = useAtom(pageEditorAtom); const [pageEditor] = useAtom(pageEditorAtom);
const pageUpdatedAt = useTimeAgo(page?.updatedAt); const pageUpdatedAt = useTimeAgo(page.updatedAt);
const handleCopyLink = () => { const handleCopyLink = () => {
const pageUrl = const pageUrl =

View File

@ -46,7 +46,6 @@ export default function MovePageModal({
message: t("Page moved successfully"), message: t("Page moved successfully"),
}); });
onClose(); onClose();
setTargetSpace(null);
} catch (err) { } catch (err) {
notifications.show({ notifications.show({
message: err.response?.data.message || "An error occurred", message: err.response?.data.message || "An error occurred",
@ -54,6 +53,7 @@ export default function MovePageModal({
}); });
console.log(err); console.log(err);
} }
setTargetSpace(null);
}; };
const handleChange = (space: ISpace) => { const handleChange = (space: ISpace) => {
@ -69,7 +69,7 @@ export default function MovePageModal({
yOffset="10vh" yOffset="10vh"
xOffset={0} xOffset={0}
mah={400} mah={400}
onClick={(e) => e.stopPropagation()} onClick={e => e.stopPropagation()}
> >
<Modal.Overlay /> <Modal.Overlay />
<Modal.Content style={{ overflow: "hidden" }}> <Modal.Content style={{ overflow: "hidden" }}>
@ -78,9 +78,7 @@ export default function MovePageModal({
<Modal.CloseButton /> <Modal.CloseButton />
</Modal.Header> </Modal.Header>
<Modal.Body> <Modal.Body>
<Text mb="xs" c="dimmed" size="sm"> <Text mb="xs" c="dimmed" size="sm">{t("Move page to a different space.")}</Text>
{t("Move page to a different space.")}
</Text>
<SpaceSelect <SpaceSelect
value={currentSpaceSlug} value={currentSpaceSlug}

View File

@ -63,36 +63,28 @@ export function useCreatePageMutation() {
}); });
} }
export function updatePageData(data: IPage) {
const pageBySlug = queryClient.getQueryData<IPage>([
"pages",
data.slugId,
]);
const pageById = queryClient.getQueryData<IPage>(["pages", data.id]);
if (pageBySlug) {
queryClient.setQueryData(["pages", data.slugId], {
...pageBySlug,
...data,
});
}
if (pageById) {
queryClient.setQueryData(["pages", data.id], { ...pageById, ...data });
}
}
export function useUpdateTitlePageMutation() {
return useMutation<IPage, Error, Partial<IPageInput>>({
mutationFn: (data) => updatePage(data),
});
}
export function useUpdatePageMutation() { export function useUpdatePageMutation() {
const queryClient = useQueryClient();
return useMutation<IPage, Error, Partial<IPageInput>>({ return useMutation<IPage, Error, Partial<IPageInput>>({
mutationFn: (data) => updatePage(data), mutationFn: (data) => updatePage(data),
onSuccess: (data) => { onSuccess: (data) => {
updatePage(data); const pageBySlug = queryClient.getQueryData<IPage>([
"pages",
data.slugId,
]);
const pageById = queryClient.getQueryData<IPage>(["pages", data.id]);
if (pageBySlug) {
queryClient.setQueryData(["pages", data.slugId], {
...pageBySlug,
...data,
});
}
if (pageById) {
queryClient.setQueryData(["pages", data.id], { ...pageById, ...data });
}
}, },
}); });
} }

View File

@ -1,6 +1,5 @@
import api from "@/lib/api-client"; import api from "@/lib/api-client";
import { import {
ICopyPageToSpace,
IExportPageParams, IExportPageParams,
IMovePage, IMovePage,
IMovePageToSpace, IMovePageToSpace,
@ -40,11 +39,6 @@ export async function movePageToSpace(data: IMovePageToSpace): Promise<void> {
await api.post<void>("/pages/move-to-space", data); await api.post<void>("/pages/move-to-space", data);
} }
export async function copyPageToSpace(data: ICopyPageToSpace): Promise<IPage> {
const req = await api.post<IPage>("/pages/copy-to-space", data);
return req.data;
}
export async function getSidebarPages( export async function getSidebarPages(
params: SidebarPagesParams, params: SidebarPagesParams,
): Promise<IPagination<IPage>> { ): Promise<IPagination<IPage>> {

View File

@ -15,7 +15,6 @@ import {
IconArrowRight, IconArrowRight,
IconChevronDown, IconChevronDown,
IconChevronRight, IconChevronRight,
IconCopy,
IconDotsVertical, IconDotsVertical,
IconFileDescription, IconFileDescription,
IconFileExport, IconFileExport,
@ -61,7 +60,6 @@ import ExportModal from "@/components/common/export-modal";
import MovePageModal from "../../components/move-page-modal.tsx"; import MovePageModal from "../../components/move-page-modal.tsx";
import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts"; import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts"; import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
import CopyPageModal from "../../components/copy-page-modal.tsx";
interface SpaceTreeProps { interface SpaceTreeProps {
spaceId: string; spaceId: string;
@ -450,10 +448,6 @@ function NodeMenu({ node, treeApi }: NodeMenuProps) {
movePageModalOpened, movePageModalOpened,
{ open: openMovePageModal, close: closeMoveSpaceModal }, { open: openMovePageModal, close: closeMoveSpaceModal },
] = useDisclosure(false); ] = useDisclosure(false);
const [
copyPageModalOpened,
{ open: openCopyPageModal, close: closeCopySpaceModal },
] = useDisclosure(false);
const handleCopyLink = () => { const handleCopyLink = () => {
const pageUrl = const pageUrl =
@ -517,17 +511,6 @@ function NodeMenu({ node, treeApi }: NodeMenuProps) {
{t("Move")} {t("Move")}
</Menu.Item> </Menu.Item>
<Menu.Item
leftSection={<IconCopy size={16} />}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
openCopyPageModal();
}}
>
{t("Copy")}
</Menu.Item>
<Menu.Divider /> <Menu.Divider />
<Menu.Item <Menu.Item
c="red" c="red"
@ -553,13 +536,6 @@ function NodeMenu({ node, treeApi }: NodeMenuProps) {
open={movePageModalOpened} open={movePageModalOpened}
/> />
<CopyPageModal
pageId={node.id}
currentSpaceSlug={spaceSlug}
onClose={closeCopySpaceModal}
open={copyPageModalOpened}
/>
<ExportModal <ExportModal
type="page" type="page"
id={node.id} id={node.id}

View File

@ -12,7 +12,7 @@ export interface IPage {
spaceId: string; spaceId: string;
workspaceId: string; workspaceId: string;
isLocked: boolean; isLocked: boolean;
lastUpdatedById: string; lastUpdatedById: Date;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
deletedAt: Date; deletedAt: Date;
@ -47,11 +47,6 @@ export interface IMovePageToSpace {
spaceId: string; spaceId: string;
} }
export interface ICopyPageToSpace {
pageId: string;
spaceId: string;
}
export interface SidebarPagesParams { export interface SidebarPagesParams {
spaceId: string; spaceId: string;
pageId?: string; pageId?: string;

View File

@ -1,44 +0,0 @@
.root {
height: 34px;
padding-left: var(--mantine-spacing-sm);
padding-right: 4px;
border-radius: var(--mantine-radius-md);
color: var(--mantine-color-placeholder);
border: 1px solid;
@mixin light {
border-color: var(--mantine-color-gray-3);
background-color: var(--mantine-color-white);
}
@mixin dark {
border-color: var(--mantine-color-dark-4);
background-color: var(--mantine-color-dark-6);
}
@mixin rtl {
padding-left: 4px;
padding-right: var(--mantine-spacing-sm);
}
}
.shortcut {
font-size: 11px;
line-height: 1;
padding: 4px 7px;
border-radius: var(--mantine-radius-sm);
border: 1px solid;
font-weight: bold;
@mixin light {
color: var(--mantine-color-gray-7);
border-color: var(--mantine-color-gray-2);
background-color: var(--mantine-color-gray-0);
}
@mixin dark {
color: var(--mantine-color-dark-0);
border-color: var(--mantine-color-dark-7);
background-color: var(--mantine-color-dark-7);
}
}

View File

@ -1,56 +0,0 @@
import { IconSearch } from "@tabler/icons-react";
import cx from "clsx";
import {
ActionIcon,
BoxProps,
ElementProps,
Group,
rem,
Text,
Tooltip,
UnstyledButton,
} from "@mantine/core";
import classes from "./search-control.module.css";
import React from "react";
import { useTranslation } from "react-i18next";
interface SearchControlProps extends BoxProps, ElementProps<"button"> {}
export function SearchControl({ className, ...others }: SearchControlProps) {
const { t } = useTranslation();
return (
<UnstyledButton {...others} className={cx(classes.root, className)}>
<Group gap="xs" wrap="nowrap">
<IconSearch style={{ width: rem(15), height: rem(15) }} stroke={1.5} />
<Text fz="sm" c="dimmed" pr={80}>
{t("Search")}
</Text>
<Text fw={700} className={classes.shortcut}>
Ctrl + K
</Text>
</Group>
</UnstyledButton>
);
}
interface SearchMobileControlProps {
onSearch: () => void;
}
export function SearchMobileControl({ onSearch }: SearchMobileControlProps) {
const { t } = useTranslation();
return (
<Tooltip label={t("Search")} withArrow>
<ActionIcon
variant="default"
style={{ border: "none" }}
onClick={onSearch}
size="sm"
>
<IconSearch size={20} stroke={2} />
</ActionIcon>
</Tooltip>
);
}

View File

@ -1,7 +0,0 @@
import { createSpotlight } from '@mantine/spotlight';
export const [searchSpotlightStore, searchSpotlight] = createSpotlight();
export const [shareSearchSpotlightStore, shareSearchSpotlight] =
createSpotlight();

View File

@ -1,7 +1,6 @@
import { useQuery, UseQueryResult } from "@tanstack/react-query"; import { useQuery, UseQueryResult } from "@tanstack/react-query";
import { import {
searchPage, searchPage,
searchShare,
searchSuggestions, searchSuggestions,
} from "@/features/search/services/search-service"; } from "@/features/search/services/search-service";
import { import {
@ -31,13 +30,3 @@ export function useSearchSuggestionsQuery(
enabled: !!params.query, enabled: !!params.query,
}); });
} }
export function useShareSearchQuery(
params: IPageSearchParams,
): UseQueryResult<IPageSearch[], Error> {
return useQuery({
queryKey: ["share-search", params],
queryFn: () => searchShare(params),
enabled: !!params.query,
});
}

View File

@ -2,36 +2,36 @@ import { Group, Center, Text } from "@mantine/core";
import { Spotlight } from "@mantine/spotlight"; import { Spotlight } from "@mantine/spotlight";
import { IconSearch } from "@tabler/icons-react"; import { IconSearch } from "@tabler/icons-react";
import React, { useState } from "react"; import React, { useState } from "react";
import { Link } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { useDebouncedValue } from "@mantine/hooks"; import { useDebouncedValue } from "@mantine/hooks";
import { usePageSearchQuery } from "@/features/search/queries/search-query"; import { usePageSearchQuery } from "@/features/search/queries/search-query";
import { buildPageUrl } from "@/features/page/page.utils.ts"; import { buildPageUrl } from "@/features/page/page.utils.ts";
import { getPageIcon } from "@/lib"; import { getPageIcon } from "@/lib";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { searchSpotlightStore } from "./constants";
interface SearchSpotlightProps { interface SearchSpotlightProps {
spaceId?: string; spaceId?: string;
} }
export function SearchSpotlight({ spaceId }: SearchSpotlightProps) { export function SearchSpotlight({ spaceId }: SearchSpotlightProps) {
const { t } = useTranslation(); const { t } = useTranslation();
const navigate = useNavigate();
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const [debouncedSearchQuery] = useDebouncedValue(query, 300); const [debouncedSearchQuery] = useDebouncedValue(query, 300);
const { data: searchResults } = usePageSearchQuery({ const {
query: debouncedSearchQuery, data: searchResults,
spaceId, isLoading,
}); error,
} = usePageSearchQuery({ query: debouncedSearchQuery, spaceId });
const pages = ( const pages = (
searchResults && searchResults.length > 0 ? searchResults : [] searchResults && searchResults.length > 0 ? searchResults : []
).map((page) => ( ).map((page) => (
<Spotlight.Action <Spotlight.Action
key={page.id} key={page.id}
component={Link} onClick={() =>
//@ts-ignore navigate(buildPageUrl(page.space.slug, page.slugId, page.title))
to={buildPageUrl(page.space.slug, page.slugId, page.title)} }
style={{ userSelect: "none" }}
> >
<Group wrap="nowrap" w="100%"> <Group wrap="nowrap" w="100%">
<Center>{getPageIcon(page?.icon)}</Center> <Center>{getPageIcon(page?.icon)}</Center>
@ -54,7 +54,6 @@ export function SearchSpotlight({ spaceId }: SearchSpotlightProps) {
return ( return (
<> <>
<Spotlight.Root <Spotlight.Root
store={searchSpotlightStore}
query={query} query={query}
onQueryChange={setQuery} onQueryChange={setQuery}
scrollable scrollable

View File

@ -19,10 +19,3 @@ export async function searchSuggestions(
const req = await api.post<ISuggestionResult>("/search/suggest", params); const req = await api.post<ISuggestionResult>("/search/suggest", params);
return req.data; return req.data;
} }
export async function searchShare(
params: IPageSearchParams,
): Promise<IPageSearch[]> {
const req = await api.post<IPageSearch[]>("/search/share-search", params);
return req.data;
}

View File

@ -1,87 +0,0 @@
import { Group, Center, Text } from "@mantine/core";
import { Spotlight } from "@mantine/spotlight";
import { IconSearch } from "@tabler/icons-react";
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { useDebouncedValue } from "@mantine/hooks";
import { useShareSearchQuery } from "@/features/search/queries/search-query";
import { buildSharedPageUrl } from "@/features/page/page.utils.ts";
import { getPageIcon } from "@/lib";
import { useTranslation } from "react-i18next";
import { shareSearchSpotlightStore } from "@/features/search/constants.ts";
interface ShareSearchSpotlightProps {
shareId?: string;
}
export function ShareSearchSpotlight({ shareId }: ShareSearchSpotlightProps) {
const { t } = useTranslation();
const [query, setQuery] = useState("");
const [debouncedSearchQuery] = useDebouncedValue(query, 300);
const { data: searchResults } = useShareSearchQuery({
query: debouncedSearchQuery,
shareId,
});
const pages = (
searchResults && searchResults.length > 0 ? searchResults : []
).map((page) => (
<Spotlight.Action
key={page.id}
component={Link}
//@ts-ignore
to={buildSharedPageUrl({
shareId: shareId,
pageTitle: page.title,
pageSlugId: page.slugId,
})}
style={{ userSelect: "none" }}
>
<Group wrap="nowrap" w="100%">
<Center>{getPageIcon(page?.icon)}</Center>
<div style={{ flex: 1 }}>
<Text>{page.title}</Text>
{page?.highlight && (
<Text
opacity={0.6}
size="xs"
dangerouslySetInnerHTML={{ __html: page.highlight }}
/>
)}
</div>
</Group>
</Spotlight.Action>
));
return (
<>
<Spotlight.Root
store={shareSearchSpotlightStore}
query={query}
onQueryChange={setQuery}
scrollable
overlayProps={{
backgroundOpacity: 0.55,
}}
>
<Spotlight.Search
placeholder={t("Search...")}
leftSection={<IconSearch size={20} stroke={1.5} />}
/>
<Spotlight.ActionsList>
{query.length === 0 && pages.length === 0 && (
<Spotlight.Empty>{t("Start typing to search...")}</Spotlight.Empty>
)}
{query.length > 0 && pages.length === 0 && (
<Spotlight.Empty>{t("No results found...")}</Spotlight.Empty>
)}
{pages.length > 0 && pages}
</Spotlight.ActionsList>
</Spotlight.Root>
</>
);
}

View File

@ -35,5 +35,4 @@ export interface ISuggestionResult {
export interface IPageSearchParams { export interface IPageSearchParams {
query: string; query: string;
spaceId?: string; spaceId?: string;
shareId?: string;
} }

View File

@ -1,16 +0,0 @@
import { Affix, Button } from "@mantine/core";
export default function ShareBranding() {
return (
<Affix position={{ bottom: 20, right: 20 }}>
<Button
variant="default"
component="a"
target="_blank"
href="https://docmost.com?ref=public-share"
>
Powered by Docmost
</Button>
</Affix>
);
}

View File

@ -1,4 +1,4 @@
import React from "react"; import React, { useState } from "react";
import { import {
ActionIcon, ActionIcon,
Affix, Affix,
@ -30,13 +30,7 @@ import {
import { IconList } from "@tabler/icons-react"; import { IconList } from "@tabler/icons-react";
import { useToggleToc } from "@/features/share/hooks/use-toggle-toc.ts"; import { useToggleToc } from "@/features/share/hooks/use-toggle-toc.ts";
import classes from "./share.module.css"; import classes from "./share.module.css";
import { import { useClickOutside } from "@mantine/hooks";
SearchControl,
SearchMobileControl,
} from "@/features/search/components/search-control.tsx";
import { ShareSearchSpotlight } from "@/features/search/share-search-spotlight";
import { shareSearchSpotlight } from "@/features/search/constants";
import ShareBranding from '@/features/share/components/share-branding.tsx';
const MemoizedSharedTree = React.memo(SharedTree); const MemoizedSharedTree = React.memo(SharedTree);
@ -60,9 +54,25 @@ export default function ShareShell({
const { data } = useGetSharedPageTreeQuery(shareId); const { data } = useGetSharedPageTreeQuery(shareId);
const readOnlyEditor = useAtomValue(readOnlyEditorAtom); const readOnlyEditor = useAtomValue(readOnlyEditorAtom);
const [navbarOutside, setNavbarOutside] = useState<HTMLElement | null>(null);
const [asideOutside, setAsideOutside] = useState<HTMLElement | null>(null);
useClickOutside(
() => {
if (mobileOpened) {
toggleMobile();
}
if (mobileTocOpened) {
toggleTocMobile();
}
},
null,
[navbarOutside, asideOutside],
);
return ( return (
<AppShell <AppShell
header={{ height: 50 }} header={{ height: 48 }}
{...(data?.pageTree?.length > 1 && { {...(data?.pageTree?.length > 1 && {
navbar: { navbar: {
width: 300, width: 300,
@ -85,7 +95,7 @@ export default function ShareShell({
> >
<AppShell.Header> <AppShell.Header>
<Group wrap="nowrap" justify="space-between" py="sm" px="xl"> <Group wrap="nowrap" justify="space-between" py="sm" px="xl">
<Group wrap="nowrap"> <Group>
{data?.pageTree?.length > 1 && ( {data?.pageTree?.length > 1 && (
<> <>
<Tooltip label={t("Sidebar toggle")}> <Tooltip label={t("Sidebar toggle")}>
@ -110,21 +120,8 @@ export default function ShareShell({
</> </>
)} )}
</Group> </Group>
{shareId && (
<Group visibleFrom="sm">
<SearchControl onClick={shareSearchSpotlight.open} />
</Group>
)}
<Group> <Group>
<> <>
{shareId && (
<Group hiddenFrom="sm">
<SearchMobileControl onSearch={shareSearchSpotlight.open} />
</Group>
)}
<Tooltip label={t("Table of contents")} withArrow> <Tooltip label={t("Table of contents")} withArrow>
<ActionIcon <ActionIcon
variant="default" variant="default"
@ -156,7 +153,11 @@ export default function ShareShell({
</AppShell.Header> </AppShell.Header>
{data?.pageTree?.length > 1 && ( {data?.pageTree?.length > 1 && (
<AppShell.Navbar p="md" className={classes.navbar}> <AppShell.Navbar
p="md"
className={classes.navbar}
ref={setNavbarOutside}
>
<MemoizedSharedTree sharedPageTree={data} /> <MemoizedSharedTree sharedPageTree={data} />
</AppShell.Navbar> </AppShell.Navbar>
)} )}
@ -164,13 +165,23 @@ export default function ShareShell({
<AppShell.Main> <AppShell.Main>
{children} {children}
{data && shareId && !data.hasLicenseKey && <ShareBranding />} <Affix position={{ bottom: 20, right: 20 }}>
<Button
variant="default"
component="a"
target="_blank"
href="https://docmost.com?ref=public-share"
>
Powered by Docmost
</Button>
</Affix>
</AppShell.Main> </AppShell.Main>
<AppShell.Aside <AppShell.Aside
p="md" p="md"
withBorder={mobileTocOpened} withBorder={mobileTocOpened}
className={classes.aside} className={classes.aside}
ref={setAsideOutside}
> >
<ScrollArea style={{ height: "80vh" }} scrollbarSize={5} type="scroll"> <ScrollArea style={{ height: "80vh" }} scrollbarSize={5} type="scroll">
<div style={{ paddingBottom: "50px" }}> <div style={{ paddingBottom: "50px" }}>
@ -180,8 +191,6 @@ export default function ShareShell({
</div> </div>
</ScrollArea> </ScrollArea>
</AppShell.Aside> </AppShell.Aside>
<ShareSearchSpotlight shareId={shareId} />
</AppShell> </AppShell>
); );
} }

View File

@ -15,7 +15,6 @@ import clsx from "clsx";
import { import {
IconChevronDown, IconChevronDown,
IconChevronRight, IconChevronRight,
IconFileDescription,
IconPointFilled, IconPointFilled,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import { ActionIcon, Box } from "@mantine/core"; import { ActionIcon, Box } from "@mantine/core";
@ -24,7 +23,6 @@ import { OpenMap } from "react-arborist/dist/main/state/open-slice";
import classes from "@/features/page/tree/styles/tree.module.css"; import classes from "@/features/page/tree/styles/tree.module.css";
import styles from "./share.module.css"; import styles from "./share.module.css";
import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts"; import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
import EmojiPicker from "@/components/ui/emoji-picker.tsx";
interface SharedTree { interface SharedTree {
sharedPageTree: ISharedPageTree; sharedPageTree: ISharedPageTree;
@ -143,20 +141,6 @@ function Node({ node, style, tree }: NodeRendererProps<any>) {
}} }}
> >
<PageArrow node={node} /> <PageArrow node={node} />
<div style={{ marginRight: "4px" }}>
<EmojiPicker
onEmojiSelect={() => {}}
icon={
node.data.icon ? (
node.data.icon
) : (
<IconFileDescription size="18" />
)
}
readOnly={true}
removeEmojiAction={() => {}}
/>
</div>
<span className={classes.text}>{node.data.name || t("untitled")}</span> <span className={classes.text}>{node.data.name || t("untitled")}</span>
</Box> </Box>
</> </>

View File

@ -41,7 +41,6 @@ export interface ISharedPage extends IShare {
level: number; level: number;
sharedPage: { id: string; slugId: string; title: string; icon: string }; sharedPage: { id: string; slugId: string; title: string; icon: string };
}; };
hasLicenseKey: boolean;
} }
export interface IShareForPage extends IShare { export interface IShareForPage extends IShare {
@ -71,5 +70,4 @@ export interface IShareInfoInput {
export interface ISharedPageTree { export interface ISharedPageTree {
share: IShare; share: IShare;
pageTree: Partial<IPage[]>; pageTree: Partial<IPage[]>;
hasLicenseKey: boolean;
} }

View File

@ -11,13 +11,11 @@ export type SharedPageTreeNode = {
parentPageId: string; parentPageId: string;
hasChildren: boolean; hasChildren: boolean;
children: SharedPageTreeNode[]; children: SharedPageTreeNode[];
label: string; label: string,
value: string; value: string,
}; };
export function buildSharedPageTree( export function buildSharedPageTree(pages: Partial<IPage[]>): SharedPageTreeNode[] {
pages: Partial<IPage[]>,
): SharedPageTreeNode[] {
const pageMap: Record<string, SharedPageTreeNode> = {}; const pageMap: Record<string, SharedPageTreeNode> = {};
// Initialize each page as a tree node and store it in a map. // Initialize each page as a tree node and store it in a map.
@ -32,7 +30,7 @@ export function buildSharedPageTree(
hasChildren: false, hasChildren: false,
spaceId: page.spaceId, spaceId: page.spaceId,
parentPageId: page.parentPageId, parentPageId: page.parentPageId,
label: page.title || "untitled", label: page.title || 'untitled',
value: page.id, value: page.id,
children: [], children: [],
}; };
@ -57,12 +55,6 @@ export function buildSharedPageTree(
} }
}); });
function sortTree(nodes: SharedPageTreeNode[]): SharedPageTreeNode[] { // Return the sorted tree.
return sortPositionKeys(nodes).map((node: SharedPageTreeNode) => ({ return sortPositionKeys(tree);
...node,
children: sortTree(node.children),
}));
}
return sortTree(tree);
} }

View File

@ -81,7 +81,7 @@ export function SpaceSelect({
nothingFoundMessage={t("No space found")} nothingFoundMessage={t("No space found")}
limit={50} limit={50}
checkIconPosition="right" checkIconPosition="right"
comboboxProps={{ width, withinPortal: true, position: "bottom" }} comboboxProps={{ width, withinPortal: false }}
dropdownOpened={opened} dropdownOpened={opened}
/> />
); );

View File

@ -6,6 +6,7 @@ import {
Tooltip, Tooltip,
UnstyledButton, UnstyledButton,
} from "@mantine/core"; } from "@mantine/core";
import { spotlight } from "@mantine/spotlight";
import { import {
IconArrowDown, IconArrowDown,
IconDots, IconDots,
@ -15,8 +16,9 @@ import {
IconSearch, IconSearch,
IconSettings, IconSettings,
} from "@tabler/icons-react"; } from "@tabler/icons-react";
import classes from "./space-sidebar.module.css"; import classes from "./space-sidebar.module.css";
import React from "react"; import React, { useMemo } from "react";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { SearchSpotlight } from "@/features/search/search-spotlight.tsx"; import { SearchSpotlight } from "@/features/search/search-spotlight.tsx";
import { treeApiAtom } from "@/features/page/tree/atoms/tree-api-atom.ts"; import { treeApiAtom } from "@/features/page/tree/atoms/tree-api-atom.ts";
@ -38,7 +40,6 @@ import { SwitchSpace } from "./switch-space";
import ExportModal from "@/components/common/export-modal"; import ExportModal from "@/components/common/export-modal";
import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts"; import { mobileSidebarAtom } from "@/components/layouts/global/hooks/atoms/sidebar-atom.ts";
import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts"; import { useToggleSidebar } from "@/components/layouts/global/hooks/hooks/use-toggle-sidebar.ts";
import { searchSpotlight } from "@/features/search/constants";
export function SpaceSidebar() { export function SpaceSidebar() {
const { t } = useTranslation(); const { t } = useTranslation();
@ -50,7 +51,7 @@ export function SpaceSidebar() {
const toggleMobileSidebar = useToggleSidebar(mobileSidebarAtom); const toggleMobileSidebar = useToggleSidebar(mobileSidebarAtom);
const { spaceSlug } = useParams(); const { spaceSlug } = useParams();
const { data: space } = useGetSpaceBySlugQuery(spaceSlug); const { data: space, isLoading, isError } = useGetSpaceBySlugQuery(spaceSlug);
const spaceRules = space?.membership?.permissions; const spaceRules = space?.membership?.permissions;
const spaceAbility = useSpaceAbility(spaceRules); const spaceAbility = useSpaceAbility(spaceRules);
@ -99,10 +100,7 @@ export function SpaceSidebar() {
</div> </div>
</UnstyledButton> </UnstyledButton>
<UnstyledButton <UnstyledButton className={classes.menu} onClick={spotlight.open}>
className={classes.menu}
onClick={searchSpotlight.open}
>
<div className={classes.menuItemInner}> <div className={classes.menuItemInner}>
<IconSearch <IconSearch
size={18} size={18}

View File

@ -7,11 +7,6 @@ export type InvalidateEvent = {
id?: string; id?: string;
}; };
export type InvalidateCommentsEvent = {
operation: "invalidateComment";
pageId: string;
};
export type UpdateEvent = { export type UpdateEvent = {
operation: "updateOne"; operation: "updateOne";
spaceId: string; spaceId: string;
@ -57,4 +52,4 @@ export type DeleteTreeNodeEvent = {
} }
}; };
export type WebSocketEvent = InvalidateEvent | InvalidateCommentsEvent | UpdateEvent | DeleteEvent | AddTreeNodeEvent | MoveTreeNodeEvent | DeleteTreeNodeEvent; export type WebSocketEvent = InvalidateEvent | UpdateEvent | DeleteEvent | AddTreeNodeEvent | MoveTreeNodeEvent | DeleteTreeNodeEvent;

View File

@ -3,7 +3,6 @@ import { socketAtom } from "@/features/websocket/atoms/socket-atom.ts";
import { useAtom } from "jotai"; import { useAtom } from "jotai";
import { useQueryClient } from "@tanstack/react-query"; import { useQueryClient } from "@tanstack/react-query";
import { WebSocketEvent } from "@/features/websocket/types"; import { WebSocketEvent } from "@/features/websocket/types";
import { RQ_KEY } from "../comment/queries/comment-query";
export const useQuerySubscription = () => { export const useQuerySubscription = () => {
const queryClient = useQueryClient(); const queryClient = useQueryClient();
@ -22,11 +21,6 @@ export const useQuerySubscription = () => {
queryKey: [...data.entity, data.id].filter(Boolean), queryKey: [...data.entity, data.id].filter(Boolean),
}); });
break; break;
case "invalidateComment":
queryClient.invalidateQueries({
queryKey: RQ_KEY(data.pageId),
});
break;
case "updateOne": case "updateOne":
entity = data.entity[0]; entity = data.entity[0];
if (entity === "pages") { if (entity === "pages") {

View File

@ -1,14 +0,0 @@
import { settingsOriginAtom } from "@/components/settings/atoms/settings-origin-atom";
import { useAtomValue } from "jotai";
import { useNavigate } from "react-router-dom";
export function useSettingsNavigation() {
const navigate = useNavigate();
const origin = useAtomValue(settingsOriginAtom);
const goBack = () => {
navigate(origin ?? "/home", { replace: true });
};
return { goBack };
}

View File

@ -1,16 +0,0 @@
import { settingsOriginAtom } from "@/components/settings/atoms/settings-origin-atom";
import { useAtomValue, useSetAtom } from "jotai";
import { useEffect } from "react";
import { useLocation } from "react-router-dom";
export function useTrackOrigin() {
const location = useLocation();
const setOrigin = useSetAtom(settingsOriginAtom);
useEffect(() => {
const isInSettings = location.pathname.startsWith("/settings");
if (!isInSettings) {
setOrigin(location.pathname);
}
}, [location.pathname, setOrigin]);
}

View File

@ -74,10 +74,6 @@ export function getDrawioUrl() {
return getConfigValue("DRAWIO_URL", "https://embed.diagrams.net"); return getConfigValue("DRAWIO_URL", "https://embed.diagrams.net");
} }
export function getBillingTrialDays() {
return getConfigValue("BILLING_TRIAL_DAYS");
}
function getConfigValue(key: string, defaultValue: string = undefined): string { function getConfigValue(key: string, defaultValue: string = undefined): string {
const rawValue = import.meta.env.DEV const rawValue = import.meta.env.DEV
? process?.env?.[key] ? process?.env?.[key]

View File

@ -7,9 +7,8 @@ import React, { useEffect } from "react";
import ReadonlyPageEditor from "@/features/editor/readonly-page-editor.tsx"; import ReadonlyPageEditor from "@/features/editor/readonly-page-editor.tsx";
import { extractPageSlugId } from "@/lib"; import { extractPageSlugId } from "@/lib";
import { Error404 } from "@/components/ui/error-404.tsx"; import { Error404 } from "@/components/ui/error-404.tsx";
import ShareBranding from "@/features/share/components/share-branding.tsx";
export default function SharedPage() { export default function SingleSharedPage() {
const { t } = useTranslation(); const { t } = useTranslation();
const { pageSlug } = useParams(); const { pageSlug } = useParams();
const { shareId } = useParams(); const { shareId } = useParams();
@ -54,8 +53,6 @@ export default function SharedPage() {
content={data.page.content} content={data.page.content}
/> />
</Container> </Container>
{data && !shareId && !data.hasLicenseKey && <ShareBranding />}
</div> </div>
); );
} }

View File

@ -12,7 +12,6 @@ export default defineConfig(({ mode }) => {
CLOUD, CLOUD,
SUBDOMAIN_HOST, SUBDOMAIN_HOST,
COLLAB_URL, COLLAB_URL,
BILLING_TRIAL_DAYS,
} = loadEnv(mode, envPath, ""); } = loadEnv(mode, envPath, "");
return { return {
@ -24,7 +23,6 @@ export default defineConfig(({ mode }) => {
CLOUD, CLOUD,
SUBDOMAIN_HOST, SUBDOMAIN_HOST,
COLLAB_URL, COLLAB_URL,
BILLING_TRIAL_DAYS,
}, },
APP_VERSION: JSON.stringify(process.env.npm_package_version), APP_VERSION: JSON.stringify(process.env.npm_package_version),
}, },

View File

@ -1,6 +1,6 @@
{ {
"name": "server", "name": "server",
"version": "0.20.4", "version": "0.10.2",
"description": "", "description": "",
"author": "", "author": "",
"private": true, "private": true,
@ -31,7 +31,6 @@
}, },
"dependencies": { "dependencies": {
"@aws-sdk/client-s3": "3.701.0", "@aws-sdk/client-s3": "3.701.0",
"@aws-sdk/lib-storage": "^3.701.0",
"@aws-sdk/s3-request-presigner": "3.701.0", "@aws-sdk/s3-request-presigner": "3.701.0",
"@casl/ability": "^6.7.3", "@casl/ability": "^6.7.3",
"@fastify/cookie": "^11.0.2", "@fastify/cookie": "^11.0.2",
@ -81,9 +80,7 @@
"sanitize-filename-ts": "^1.0.2", "sanitize-filename-ts": "^1.0.2",
"socket.io": "^4.8.1", "socket.io": "^4.8.1",
"stripe": "^17.5.0", "stripe": "^17.5.0",
"tmp-promise": "^3.0.3", "ws": "^8.18.0"
"ws": "^8.18.0",
"yauzl": "^3.2.0"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.20.0", "@eslint/js": "^9.20.0",
@ -102,7 +99,6 @@
"@types/pg": "^8.11.11", "@types/pg": "^8.11.11",
"@types/supertest": "^6.0.2", "@types/supertest": "^6.0.2",
"@types/ws": "^8.5.14", "@types/ws": "^8.5.14",
"@types/yauzl": "^2.10.3",
"eslint": "^9.20.1", "eslint": "^9.20.1",
"eslint-config-prettier": "^10.0.1", "eslint-config-prettier": "^10.0.1",
"globals": "^15.15.0", "globals": "^15.15.0",

View File

@ -1,4 +1,4 @@
import { Logger, Module, OnModuleDestroy, OnModuleInit } from '@nestjs/common'; import { Module, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { AuthenticationExtension } from './extensions/authentication.extension'; import { AuthenticationExtension } from './extensions/authentication.extension';
import { PersistenceExtension } from './extensions/persistence.extension'; import { PersistenceExtension } from './extensions/persistence.extension';
import { CollaborationGateway } from './collaboration.gateway'; import { CollaborationGateway } from './collaboration.gateway';
@ -22,7 +22,6 @@ import { LoggerExtension } from './extensions/logger.extension';
imports: [TokenModule], imports: [TokenModule],
}) })
export class CollaborationModule implements OnModuleInit, OnModuleDestroy { export class CollaborationModule implements OnModuleInit, OnModuleDestroy {
private readonly logger = new Logger(CollaborationModule.name);
private collabWsAdapter: CollabWsAdapter; private collabWsAdapter: CollabWsAdapter;
private path = '/collab'; private path = '/collab';
@ -39,15 +38,7 @@ export class CollaborationModule implements OnModuleInit, OnModuleDestroy {
wss.on('connection', (client: WebSocket, request: IncomingMessage) => { wss.on('connection', (client: WebSocket, request: IncomingMessage) => {
this.collaborationGateway.handleConnection(client, request); this.collaborationGateway.handleConnection(client, request);
client.on('error', (error) => {
this.logger.error('WebSocket client error:', error);
});
}); });
wss.on('error', (error) =>
this.logger.log('WebSocket server error:', error),
);
} }
async onModuleDestroy(): Promise<void> { async onModuleDestroy(): Promise<void> {

View File

@ -46,7 +46,7 @@ export const tiptapExtensions = [
codeBlock: false, codeBlock: false,
}), }),
Comment, Comment,
TextAlign.configure({ types: ["heading", "paragraph"] }), TextAlign,
TaskList, TaskList,
TaskItem, TaskItem,
Underline, Underline,

View File

@ -130,7 +130,7 @@ export class PersistenceExtension implements Extension {
); );
this.contributors.delete(documentName); this.contributors.delete(documentName);
} catch (err) { } catch (err) {
this.logger.debug('Contributors error:' + err?.['message']); this.logger.log('Contributors error:' + err?.['message']);
} }
await this.pageRepo.updatePage( await this.pageRepo.updatePage(

View File

@ -1,12 +1,6 @@
import { Node } from '@tiptap/pm/model'; import { Node } from '@tiptap/pm/model';
import { import { jsonToNode } from '../../../collaboration/collaboration.util';
jsonToNode,
tiptapExtensions,
} from '../../../collaboration/collaboration.util';
import { validate as isValidUUID } from 'uuid'; import { validate as isValidUUID } from 'uuid';
import { Transform } from '@tiptap/pm/transform';
import { TiptapTransformer } from '@hocuspocus/transformer';
import * as Y from 'yjs';
export interface MentionNode { export interface MentionNode {
id: string; id: string;
@ -64,6 +58,7 @@ export function extractPageMentions(mentionList: MentionNode[]): MentionNode[] {
return pageMentionList as MentionNode[]; return pageMentionList as MentionNode[];
} }
export function getProsemirrorContent(content: any) { export function getProsemirrorContent(content: any) {
return ( return (
content ?? { content ?? {
@ -100,30 +95,3 @@ export function getAttachmentIds(prosemirrorJson: any) {
return attachmentIds; return attachmentIds;
} }
export function removeMarkTypeFromDoc(doc: Node, markName: string): Node {
const { schema } = doc.type;
const markType = schema.marks[markName];
if (!markType) {
return doc;
}
const tr = new Transform(doc).removeMark(0, doc.content.size, markType);
return tr.doc;
}
export function createYdocFromJson(prosemirrorJson: any): Buffer | null {
if (prosemirrorJson) {
const ydoc = TiptapTransformer.toYdoc(
prosemirrorJson,
'default',
tiptapExtensions,
);
Y.encodeStateAsUpdate(ydoc);
return Buffer.from(Y.encodeStateAsUpdate(ydoc));
}
return null;
}

View File

@ -1,6 +1,5 @@
import * as path from 'path'; import * as path from 'path';
import * as bcrypt from 'bcrypt'; import * as bcrypt from 'bcrypt';
import { sanitize } from 'sanitize-filename-ts';
export const envPath = path.resolve(process.cwd(), '..', '..', '.env'); export const envPath = path.resolve(process.cwd(), '..', '..', '.env');
@ -63,8 +62,3 @@ export function extractDateFromUuid7(uuid7: string) {
return new Date(timestamp); return new Date(timestamp);
} }
export function sanitizeFileName(fileName: string): string {
const sanitizedFilename = sanitize(fileName).replace(/ /g, '_');
return sanitizedFilename.slice(0, 255);
}

View File

@ -1,24 +0,0 @@
import { IsString, IsNotEmpty } from 'class-validator';
export class CopyPageToSpaceDto {
@IsNotEmpty()
@IsString()
pageId: string;
@IsNotEmpty()
@IsString()
spaceId: string;
}
export type CopyPageMapEntry = {
newPageId: string;
newSlugId: string;
oldSlugId: string;
};
export type ICopyPageAttachment = {
newPageId: string,
oldPageId: string,
oldAttachmentId: string,
newAttachmentId: string,
};

View File

@ -1,10 +1,4 @@
import { import { IsString, IsOptional, MinLength, MaxLength } from 'class-validator';
IsString,
IsOptional,
MinLength,
MaxLength,
IsNotEmpty,
} from 'class-validator';
export class MovePageDto { export class MovePageDto {
@IsString() @IsString()
@ -21,11 +15,9 @@ export class MovePageDto {
} }
export class MovePageToSpaceDto { export class MovePageToSpaceDto {
@IsNotEmpty()
@IsString() @IsString()
pageId: string; pageId: string;
@IsNotEmpty()
@IsString() @IsString()
spaceId: string; spaceId: string;
} }

View File

@ -28,7 +28,6 @@ import {
import SpaceAbilityFactory from '../casl/abilities/space-ability.factory'; import SpaceAbilityFactory from '../casl/abilities/space-ability.factory';
import { PageRepo } from '@docmost/db/repos/page/page.repo'; import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { RecentPageDto } from './dto/recent-page.dto'; import { RecentPageDto } from './dto/recent-page.dto';
import { CopyPageToSpaceDto } from './dto/copy-page.dto';
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Controller('pages') @Controller('pages')
@ -238,36 +237,6 @@ export class PageController {
return this.pageService.movePageToSpace(movedPage, dto.spaceId); return this.pageService.movePageToSpace(movedPage, dto.spaceId);
} }
@HttpCode(HttpStatus.OK)
@Post('copy-to-space')
async copyPageToSpace(
@Body() dto: CopyPageToSpaceDto,
@AuthUser() user: User,
) {
const copiedPage = await this.pageRepo.findById(dto.pageId);
if (!copiedPage) {
throw new NotFoundException('Page to copy not found');
}
if (copiedPage.spaceId === dto.spaceId) {
throw new BadRequestException('Page is already in this space');
}
const abilities = await Promise.all([
this.spaceAbility.createForUser(user, copiedPage.spaceId),
this.spaceAbility.createForUser(user, dto.spaceId),
]);
if (
abilities.some((ability) =>
ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page),
)
) {
throw new ForbiddenException();
}
return this.pageService.copyPageToSpace(copiedPage, dto.spaceId, user);
}
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Post('move') @Post('move')
async movePage(@Body() dto: MovePageDto, @AuthUser() user: User) { async movePage(@Body() dto: MovePageDto, @AuthUser() user: User) {

View File

@ -2,12 +2,10 @@ import { Module } from '@nestjs/common';
import { PageService } from './services/page.service'; import { PageService } from './services/page.service';
import { PageController } from './page.controller'; import { PageController } from './page.controller';
import { PageHistoryService } from './services/page-history.service'; import { PageHistoryService } from './services/page-history.service';
import { StorageModule } from '../../integrations/storage/storage.module';
@Module({ @Module({
controllers: [PageController], controllers: [PageController],
providers: [PageService, PageHistoryService], providers: [PageService, PageHistoryService],
exports: [PageService, PageHistoryService], exports: [PageService, PageHistoryService],
imports: [StorageModule]
}) })
export class PageModule {} export class PageModule {}

View File

@ -1,13 +1,12 @@
import { import {
BadRequestException, BadRequestException,
Injectable, Injectable,
Logger,
NotFoundException, NotFoundException,
} from '@nestjs/common'; } from '@nestjs/common';
import { CreatePageDto } from '../dto/create-page.dto'; import { CreatePageDto } from '../dto/create-page.dto';
import { UpdatePageDto } from '../dto/update-page.dto'; import { UpdatePageDto } from '../dto/update-page.dto';
import { PageRepo } from '@docmost/db/repos/page/page.repo'; import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { InsertablePage, Page, User } from '@docmost/db/types/entity.types'; import { Page } from '@docmost/db/types/entity.types';
import { PaginationOptions } from '@docmost/db/pagination/pagination-options'; import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
import { import {
executeWithPagination, executeWithPagination,
@ -22,28 +21,13 @@ import { DB } from '@docmost/db/types/db';
import { generateSlugId } from '../../../common/helpers'; import { generateSlugId } from '../../../common/helpers';
import { executeTx } from '@docmost/db/utils'; import { executeTx } from '@docmost/db/utils';
import { AttachmentRepo } from '@docmost/db/repos/attachment/attachment.repo'; import { AttachmentRepo } from '@docmost/db/repos/attachment/attachment.repo';
import { v7 as uuid7 } from 'uuid';
import {
createYdocFromJson,
getAttachmentIds,
getProsemirrorContent,
isAttachmentNode,
removeMarkTypeFromDoc,
} from '../../../common/helpers/prosemirror/utils';
import { jsonToNode, jsonToText } from 'src/collaboration/collaboration.util';
import { CopyPageMapEntry, ICopyPageAttachment } from '../dto/copy-page.dto';
import { Node as PMNode } from '@tiptap/pm/model';
import { StorageService } from '../../../integrations/storage/storage.service';
@Injectable() @Injectable()
export class PageService { export class PageService {
private readonly logger = new Logger(PageService.name);
constructor( constructor(
private pageRepo: PageRepo, private pageRepo: PageRepo,
private attachmentRepo: AttachmentRepo, private attachmentRepo: AttachmentRepo,
@InjectKysely() private readonly db: KyselyDB, @InjectKysely() private readonly db: KyselyDB,
private readonly storageService: StorageService,
) {} ) {}
async findById( async findById(
@ -258,154 +242,6 @@ export class PageService {
}); });
} }
async copyPageToSpace(rootPage: Page, spaceId: string, authUser: User) {
//TODO:
// i. maintain internal links within copied pages
const nextPosition = await this.nextPagePosition(spaceId);
const pages = await this.pageRepo.getPageAndDescendants(rootPage.id, {
includeContent: true,
});
const pageMap = new Map<string, CopyPageMapEntry>();
pages.forEach((page) => {
pageMap.set(page.id, {
newPageId: uuid7(),
newSlugId: generateSlugId(),
oldSlugId: page.slugId,
});
});
const attachmentMap = new Map<string, ICopyPageAttachment>();
const insertablePages: InsertablePage[] = await Promise.all(
pages.map(async (page) => {
const pageContent = getProsemirrorContent(page.content);
const pageFromMap = pageMap.get(page.id);
const doc = jsonToNode(pageContent);
const prosemirrorDoc = removeMarkTypeFromDoc(doc, 'comment');
const attachmentIds = getAttachmentIds(prosemirrorDoc.toJSON());
if (attachmentIds.length > 0) {
attachmentIds.forEach((attachmentId: string) => {
const newPageId = pageFromMap.newPageId;
const newAttachmentId = uuid7();
attachmentMap.set(attachmentId, {
newPageId: newPageId,
oldPageId: page.id,
oldAttachmentId: attachmentId,
newAttachmentId: newAttachmentId,
});
prosemirrorDoc.descendants((node: PMNode) => {
if (isAttachmentNode(node.type.name)) {
if (node.attrs.attachmentId === attachmentId) {
//@ts-ignore
node.attrs.attachmentId = newAttachmentId;
if (node.attrs.src) {
//@ts-ignore
node.attrs.src = node.attrs.src.replace(
attachmentId,
newAttachmentId,
);
}
if (node.attrs.src) {
//@ts-ignore
node.attrs.src = node.attrs.src.replace(
attachmentId,
newAttachmentId,
);
}
}
}
});
});
}
const prosemirrorJson = prosemirrorDoc.toJSON();
return {
id: pageFromMap.newPageId,
slugId: pageFromMap.newSlugId,
title: page.title,
icon: page.icon,
content: prosemirrorJson,
textContent: jsonToText(prosemirrorJson),
ydoc: createYdocFromJson(prosemirrorJson),
position: page.id === rootPage.id ? nextPosition : page.position,
spaceId: spaceId,
workspaceId: page.workspaceId,
creatorId: authUser.id,
lastUpdatedById: authUser.id,
parentPageId: page.parentPageId
? pageMap.get(page.parentPageId)?.newPageId
: null,
};
}),
);
await this.db.insertInto('pages').values(insertablePages).execute();
//TODO: best to handle this in a queue
const attachmentsIds = Array.from(attachmentMap.keys());
if (attachmentsIds.length > 0) {
const attachments = await this.db
.selectFrom('attachments')
.selectAll()
.where('id', 'in', attachmentsIds)
.where('workspaceId', '=', rootPage.workspaceId)
.execute();
for (const attachment of attachments) {
try {
const pageAttachment = attachmentMap.get(attachment.id);
// make sure the copied attachment belongs to the page it was copied from
if (attachment.pageId !== pageAttachment.oldPageId) {
continue;
}
const newAttachmentId = pageAttachment.newAttachmentId;
const newPageId = pageAttachment.newPageId;
const newPathFile = attachment.filePath.replace(
attachment.id,
newAttachmentId,
);
await this.storageService.copy(attachment.filePath, newPathFile);
await this.db
.insertInto('attachments')
.values({
id: newAttachmentId,
type: attachment.type,
filePath: newPathFile,
fileName: attachment.fileName,
fileSize: attachment.fileSize,
mimeType: attachment.mimeType,
fileExt: attachment.fileExt,
creatorId: attachment.creatorId,
workspaceId: attachment.workspaceId,
pageId: newPageId,
spaceId: spaceId,
})
.execute();
} catch (err) {
this.logger.log(err);
}
}
}
const newPageId = pageMap.get(rootPage.id).newPageId;
return await this.pageRepo.findById(newPageId, {
includeSpace: true,
});
}
async movePage(dto: MovePageDto, movedPage: Page) { async movePage(dto: MovePageDto, movedPage: Page) {
// validate position value by attempting to generate a key // validate position value by attempting to generate a key
try { try {

View File

@ -5,11 +5,8 @@ import {
IsOptional, IsOptional,
IsString, IsString,
} from 'class-validator'; } from 'class-validator';
import { PartialType } from '@nestjs/mapped-types';
import { CreateWorkspaceDto } from '../../workspace/dto/create-workspace.dto';
export class SearchDTO { export class SearchDTO {
@IsNotEmpty()
@IsString() @IsString()
query: string; query: string;
@ -17,10 +14,6 @@ export class SearchDTO {
@IsString() @IsString()
spaceId: string; spaceId: string;
@IsOptional()
@IsString()
shareId?: string;
@IsOptional() @IsOptional()
@IsString() @IsString()
creatorId?: string; creatorId?: string;
@ -34,16 +27,6 @@ export class SearchDTO {
offset?: number; offset?: number;
} }
export class SearchShareDTO extends SearchDTO {
@IsNotEmpty()
@IsString()
shareId: string;
@IsOptional()
@IsString()
spaceId: string;
}
export class SearchSuggestionDTO { export class SearchSuggestionDTO {
@IsString() @IsString()
query: string; query: string;

View File

@ -1,19 +1,15 @@
import { import {
BadRequestException,
Body, Body,
Controller, Controller,
ForbiddenException, ForbiddenException,
HttpCode, HttpCode,
HttpStatus, HttpStatus,
NotImplementedException,
Post, Post,
UseGuards, UseGuards,
} from '@nestjs/common'; } from '@nestjs/common';
import { SearchService } from './search.service'; import { SearchService } from './search.service';
import { import { SearchDTO, SearchSuggestionDTO } from './dto/search.dto';
SearchDTO,
SearchShareDTO,
SearchSuggestionDTO,
} from './dto/search.dto';
import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator'; import { AuthWorkspace } from '../../common/decorators/auth-workspace.decorator';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'; import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { User, Workspace } from '@docmost/db/types/entity.types'; import { User, Workspace } from '@docmost/db/types/entity.types';
@ -23,7 +19,6 @@ import {
SpaceCaslSubject, SpaceCaslSubject,
} from '../casl/interfaces/space-ability.type'; } from '../casl/interfaces/space-ability.type';
import { AuthUser } from '../../common/decorators/auth-user.decorator'; import { AuthUser } from '../../common/decorators/auth-user.decorator';
import { Public } from 'src/common/decorators/public.decorator';
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Controller('search') @Controller('search')
@ -35,13 +30,7 @@ export class SearchController {
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@Post() @Post()
async pageSearch( async pageSearch(@Body() searchDto: SearchDTO, @AuthUser() user: User) {
@Body() searchDto: SearchDTO,
@AuthUser() user: User,
@AuthWorkspace() workspace: Workspace,
) {
delete searchDto.shareId;
if (searchDto.spaceId) { if (searchDto.spaceId) {
const ability = await this.spaceAbility.createForUser( const ability = await this.spaceAbility.createForUser(
user, user,
@ -51,12 +40,12 @@ export class SearchController {
if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) { if (ability.cannot(SpaceCaslAction.Read, SpaceCaslSubject.Page)) {
throw new ForbiddenException(); throw new ForbiddenException();
} }
return this.searchService.searchPage(searchDto.query, searchDto);
} }
return this.searchService.searchPage(searchDto.query, searchDto, { // TODO: search all spaces user is a member of if no spaceId provided
userId: user.id, throw new NotImplementedException();
workspaceId: workspace.id,
});
} }
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@ -68,21 +57,4 @@ export class SearchController {
) { ) {
return this.searchService.searchSuggestions(dto, user.id, workspace.id); return this.searchService.searchSuggestions(dto, user.id, workspace.id);
} }
@Public()
@HttpCode(HttpStatus.OK)
@Post('share-search')
async searchShare(
@Body() searchDto: SearchShareDTO,
@AuthWorkspace() workspace: Workspace,
) {
delete searchDto.spaceId;
if (!searchDto.shareId) {
throw new BadRequestException('shareId is required');
}
return this.searchService.searchPage(searchDto.query, searchDto, {
workspaceId: workspace.id,
});
}
} }

View File

@ -6,7 +6,6 @@ import { KyselyDB } from '@docmost/db/types/kysely.types';
import { sql } from 'kysely'; import { sql } from 'kysely';
import { PageRepo } from '@docmost/db/repos/page/page.repo'; import { PageRepo } from '@docmost/db/repos/page/page.repo';
import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo'; import { SpaceMemberRepo } from '@docmost/db/repos/space/space-member.repo';
import { ShareRepo } from '@docmost/db/repos/share/share.repo';
// eslint-disable-next-line @typescript-eslint/no-require-imports // eslint-disable-next-line @typescript-eslint/no-require-imports
const tsquery = require('pg-tsquery')(); const tsquery = require('pg-tsquery')();
@ -16,24 +15,19 @@ export class SearchService {
constructor( constructor(
@InjectKysely() private readonly db: KyselyDB, @InjectKysely() private readonly db: KyselyDB,
private pageRepo: PageRepo, private pageRepo: PageRepo,
private shareRepo: ShareRepo,
private spaceMemberRepo: SpaceMemberRepo, private spaceMemberRepo: SpaceMemberRepo,
) {} ) {}
async searchPage( async searchPage(
query: string, query: string,
searchParams: SearchDTO, searchParams: SearchDTO,
opts: {
userId?: string;
workspaceId: string;
},
): Promise<SearchResponseDto[]> { ): Promise<SearchResponseDto[]> {
if (query.length < 1) { if (query.length < 1) {
return; return;
} }
const searchQuery = tsquery(query.trim() + '*'); const searchQuery = tsquery(query.trim() + '*');
let queryResults = this.db const queryResults = await this.db
.selectFrom('pages') .selectFrom('pages')
.select([ .select([
'id', 'id',
@ -49,71 +43,18 @@ export class SearchService {
'highlight', 'highlight',
), ),
]) ])
.select((eb) => this.pageRepo.withSpace(eb))
.where('spaceId', '=', searchParams.spaceId)
.where('tsv', '@@', sql<string>`to_tsquery(${searchQuery})`) .where('tsv', '@@', sql<string>`to_tsquery(${searchQuery})`)
.$if(Boolean(searchParams.creatorId), (qb) => .$if(Boolean(searchParams.creatorId), (qb) =>
qb.where('creatorId', '=', searchParams.creatorId), qb.where('creatorId', '=', searchParams.creatorId),
) )
.orderBy('rank', 'desc') .orderBy('rank', 'desc')
.limit(searchParams.limit | 20) .limit(searchParams.limit | 20)
.offset(searchParams.offset || 0); .offset(searchParams.offset || 0)
.execute();
if (!searchParams.shareId) { const searchResults = queryResults.map((result) => {
queryResults = queryResults.select((eb) => this.pageRepo.withSpace(eb));
}
if (searchParams.spaceId) {
// search by spaceId
queryResults = queryResults.where('spaceId', '=', searchParams.spaceId);
} else if (opts.userId && !searchParams.spaceId) {
// only search spaces the user is a member of
const userSpaceIds = await this.spaceMemberRepo.getUserSpaceIds(
opts.userId,
);
if (userSpaceIds.length > 0) {
queryResults = queryResults
.where('spaceId', 'in', userSpaceIds)
.where('workspaceId', '=', opts.workspaceId);
} else {
return [];
}
} else if (searchParams.shareId && !searchParams.spaceId && !opts.userId) {
// search in shares
const shareId = searchParams.shareId;
const share = await this.shareRepo.findById(shareId);
if (!share || share.workspaceId !== opts.workspaceId) {
return [];
}
const pageIdsToSearch = [];
if (share.includeSubPages) {
const pageList = await this.pageRepo.getPageAndDescendants(
share.pageId,
{
includeContent: false,
},
);
pageIdsToSearch.push(...pageList.map((page) => page.id));
} else {
pageIdsToSearch.push(share.pageId);
}
if (pageIdsToSearch.length > 0) {
queryResults = queryResults
.where('id', 'in', pageIdsToSearch)
.where('workspaceId', '=', opts.workspaceId);
} else {
return [];
}
} else {
return [];
}
//@ts-ignore
queryResults = await queryResults.execute();
//@ts-ignore
const searchResults = queryResults.map((result: SearchResponseDto) => {
if (result.highlight) { if (result.highlight) {
result.highlight = result.highlight result.highlight = result.highlight
.replace(/\r\n|\r|\n/g, ' ') .replace(/\r\n|\r|\n/g, ' ')

View File

@ -30,7 +30,6 @@ import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { Public } from '../../common/decorators/public.decorator'; import { Public } from '../../common/decorators/public.decorator';
import { ShareRepo } from '@docmost/db/repos/share/share.repo'; import { ShareRepo } from '@docmost/db/repos/share/share.repo';
import { PaginationOptions } from '@docmost/db/pagination/pagination-options'; import { PaginationOptions } from '@docmost/db/pagination/pagination-options';
import { EnvironmentService } from '../../integrations/environment/environment.service';
@UseGuards(JwtAuthGuard) @UseGuards(JwtAuthGuard)
@Controller('shares') @Controller('shares')
@ -40,7 +39,6 @@ export class ShareController {
private readonly spaceAbility: SpaceAbilityFactory, private readonly spaceAbility: SpaceAbilityFactory,
private readonly shareRepo: ShareRepo, private readonly shareRepo: ShareRepo,
private readonly pageRepo: PageRepo, private readonly pageRepo: PageRepo,
private readonly environmentService: EnvironmentService,
) {} ) {}
@HttpCode(HttpStatus.OK) @HttpCode(HttpStatus.OK)
@ -63,12 +61,7 @@ export class ShareController {
throw new BadRequestException(); throw new BadRequestException();
} }
return { return this.shareService.getSharedPage(dto, workspace.id);
...(await this.shareService.getSharedPage(dto, workspace.id)),
hasLicenseKey:
Boolean(workspace.licenseKey) ||
(this.environmentService.isCloud() && workspace.plan === 'business'),
};
} }
@Public() @Public()
@ -173,11 +166,6 @@ export class ShareController {
@Body() dto: ShareIdDto, @Body() dto: ShareIdDto,
@AuthWorkspace() workspace: Workspace, @AuthWorkspace() workspace: Workspace,
) { ) {
return { return this.shareService.getShareTree(dto.shareId, workspace.id);
...(await this.shareService.getShareTree(dto.shareId, workspace.id)),
hasLicenseKey:
Boolean(workspace.licenseKey) ||
(this.environmentService.isCloud() && workspace.plan === 'business'),
};
} }
} }

View File

@ -15,7 +15,6 @@ import {
getAttachmentIds, getAttachmentIds,
getProsemirrorContent, getProsemirrorContent,
isAttachmentNode, isAttachmentNode,
removeMarkTypeFromDoc,
} from '../../common/helpers/prosemirror/utils'; } from '../../common/helpers/prosemirror/utils';
import { Node } from '@tiptap/pm/model'; import { Node } from '@tiptap/pm/model';
import { ShareRepo } from '@docmost/db/repos/share/share.repo'; import { ShareRepo } from '@docmost/db/repos/share/share.repo';
@ -224,7 +223,11 @@ export class ShareService {
.end() .end()
.as('found'), .as('found'),
]) ])
.where(isValidUUID(childPageId) ? 'id' : 'slugId', '=', childPageId) .where(
isValidUUID(childPageId) ? 'id' : 'slugId',
'=',
childPageId,
)
.unionAll((exp) => .unionAll((exp) =>
exp exp
.selectFrom('pages as p') .selectFrom('pages as p')
@ -289,7 +292,6 @@ export class ShareService {
updateAttachmentAttr(node, 'url', token); updateAttachmentAttr(node, 'url', token);
}); });
const removeCommentMarks = removeMarkTypeFromDoc(doc, 'comment'); return doc.toJSON();
return removeCommentMarks.toJSON();
} }
} }

View File

@ -387,14 +387,14 @@ export class WorkspaceService {
.replace(/[^a-z0-9]/g, '') .replace(/[^a-z0-9]/g, '')
.substring(0, 20); .substring(0, 20);
// Ensure we leave room for a random suffix. // Ensure we leave room for a random suffix.
const maxSuffixLength = 6; const maxSuffixLength = 3;
if (subdomain.length < 4) { if (subdomain.length < 4) {
subdomain = `${subdomain}-${generateRandomSuffix(maxSuffixLength)}`; subdomain = `${subdomain}-${generateRandomSuffix(maxSuffixLength)}`;
} }
if (DISALLOWED_HOSTNAMES.includes(subdomain)) { if (DISALLOWED_HOSTNAMES.includes(subdomain)) {
subdomain = `workspace-${generateRandomSuffix(maxSuffixLength)}`; subdomain = `myworkspace-${generateRandomSuffix(maxSuffixLength)}`;
} }
let uniqueHostname = subdomain; let uniqueHostname = subdomain;

View File

@ -1,45 +0,0 @@
import { Kysely, sql } from 'kysely';
export async function up(db: Kysely<any>): Promise<void> {
await db.schema
.createTable('file_tasks')
.addColumn('id', 'uuid', (col) =>
col.primaryKey().defaultTo(sql`gen_uuid_v7()`),
)
//type: import or export
.addColumn('type', 'varchar', (col) => col)
// source - generic, notion, confluence
// type or provider?
.addColumn('source', 'varchar', (col) => col)
// status (enum: PENDING|PROCESSING|SUCCESS|FAILED),
.addColumn('status', 'varchar', (col) => col)
// file name
// file path
// file size
.addColumn('file_name', 'varchar', (col) => col.notNull())
.addColumn('file_path', 'varchar', (col) => col.notNull())
.addColumn('file_size', 'int8', (col) => col)
.addColumn('file_ext', 'varchar', (col) => col)
.addColumn('creator_id', 'uuid', (col) => col.references('users.id'))
.addColumn('space_id', 'uuid', (col) =>
col.references('spaces.id').onDelete('cascade'),
)
.addColumn('workspace_id', 'uuid', (col) =>
col.references('workspaces.id').onDelete('cascade').notNull(),
)
.addColumn('created_at', 'timestamptz', (col) =>
col.notNull().defaultTo(sql`now()`),
)
.addColumn('updated_at', 'timestamptz', (col) =>
col.notNull().defaultTo(sql`now()`),
)
.addColumn('completed_at', 'timestamptz', (col) => col)
.addColumn('deleted_at', 'timestamptz', (col) => col)
.execute();
}
export async function down(db: Kysely<any>): Promise<void> {
await db.schema.dropTable('file_tasks').execute();
}

View File

@ -244,7 +244,7 @@ export class PageRepo {
'p.spaceId', 'p.spaceId',
'p.workspaceId', 'p.workspaceId',
]) ])
.$if(opts?.includeContent, (qb) => qb.select('p.content')) .$if(opts?.includeContent, (qb) => qb.select('content'))
.innerJoin('page_hierarchy as ph', 'p.parentPageId', 'ph.id'), .innerJoin('page_hierarchy as ph', 'p.parentPageId', 'ph.id'),
), ),
) )

View File

@ -70,7 +70,7 @@ export class UserTokenRepo {
.where('userId', '=', userId) .where('userId', '=', userId)
.where('workspaceId', '=', workspaceId) .where('workspaceId', '=', workspaceId)
.where('type', '=', tokenType) .where('type', '=', tokenType)
.orderBy('expiresAt', 'desc') .orderBy('expiresAt desc')
.execute(); .execute();
} }

View File

@ -70,7 +70,7 @@ export class WorkspaceRepo {
return await this.db return await this.db
.selectFrom('workspaces') .selectFrom('workspaces')
.selectAll() .selectAll()
.orderBy('createdAt', 'asc') .orderBy('createdAt asc')
.limit(1) .limit(1)
.executeTakeFirst(); .executeTakeFirst();
} }

View File

@ -122,24 +122,6 @@ export interface Comments {
workspaceId: string; workspaceId: string;
} }
export interface FileTasks {
completedAt: Timestamp | null;
createdAt: Generated<Timestamp>;
creatorId: string | null;
deletedAt: Timestamp | null;
fileExt: string | null;
fileName: string;
filePath: string;
fileSize: Int8 | null;
id: Generated<string>;
source: string | null;
spaceId: string | null;
status: string | null;
type: string | null;
updatedAt: Generated<Timestamp>;
workspaceId: string;
}
export interface Groups { export interface Groups {
createdAt: Generated<Timestamp>; createdAt: Generated<Timestamp>;
creatorId: string | null; creatorId: string | null;
@ -316,7 +298,6 @@ export interface DB {
backlinks: Backlinks; backlinks: Backlinks;
billing: Billing; billing: Billing;
comments: Comments; comments: Comments;
fileTasks: FileTasks;
groups: Groups; groups: Groups;
groupUsers: GroupUsers; groupUsers: GroupUsers;
pageHistory: PageHistory; pageHistory: PageHistory;

View File

@ -17,7 +17,6 @@ import {
AuthProviders, AuthProviders,
AuthAccounts, AuthAccounts,
Shares, Shares,
FileTasks,
} from './db'; } from './db';
// Workspace // Workspace
@ -108,8 +107,3 @@ export type UpdatableAuthAccount = Updateable<Omit<AuthAccounts, 'id'>>;
export type Share = Selectable<Shares>; export type Share = Selectable<Shares>;
export type InsertableShare = Insertable<Shares>; export type InsertableShare = Insertable<Shares>;
export type UpdatableShare = Updateable<Omit<Shares, 'id'>>; export type UpdatableShare = Updateable<Omit<Shares, 'id'>>;
// File Task
export type FileTask = Selectable<FileTasks>;
export type InsertableFileTask = Insertable<FileTasks>;
export type UpdatableFileTask = Updateable<Omit<FileTasks, 'id'>>;

View File

@ -1,6 +1,5 @@
import * as TurndownService from '@joplin/turndown'; import * as TurndownService from '@joplin/turndown';
import * as TurndownPluginGfm from '@joplin/turndown-plugin-gfm'; import * as TurndownPluginGfm from '@joplin/turndown-plugin-gfm';
import * as path from 'path';
export function turndown(html: string): string { export function turndown(html: string): string {
const turndownService = new TurndownService({ const turndownService = new TurndownService({
@ -24,7 +23,6 @@ export function turndown(html: string): string {
mathInline, mathInline,
mathBlock, mathBlock,
iframeEmbed, iframeEmbed,
video,
]); ]);
return turndownService.turndown(html).replaceAll('<br>', ' '); return turndownService.turndown(html).replaceAll('<br>', ' ');
} }
@ -70,7 +68,7 @@ function taskList(turndownService: TurndownService) {
) as HTMLInputElement; ) as HTMLInputElement;
const isChecked = checkbox.checked; const isChecked = checkbox.checked;
return `- ${isChecked ? '[x]' : '[ ]'} ${content.trim()} \n`; return `- ${isChecked ? '[x]' : '[ ]'} ${content.trim()} \n`;
}, },
}); });
} }
@ -89,12 +87,8 @@ function preserveDetail(turndownService: TurndownService) {
} }
const detailsContent = Array.from(node.childNodes) const detailsContent = Array.from(node.childNodes)
.filter((child) => child.nodeName !== 'SUMMARY') .filter(child => child.nodeName !== 'SUMMARY')
.map((child) => .map(child => (child.nodeType === 1 ? turndownService.turndown((child as HTMLElement).outerHTML) : child.textContent))
child.nodeType === 1
? turndownService.turndown((child as HTMLElement).outerHTML)
: child.textContent,
)
.join(''); .join('');
return `\n<details>\n${detailSummary}\n\n${detailsContent}\n\n</details>\n`; return `\n<details>\n${detailSummary}\n\n${detailsContent}\n\n</details>\n`;
@ -141,16 +135,3 @@ function iframeEmbed(turndownService: TurndownService) {
}, },
}); });
} }
function video(turndownService: TurndownService) {
turndownService.addRule('video', {
filter: function (node: HTMLInputElement) {
return node.tagName === 'VIDEO';
},
replacement: function (content: any, node: HTMLInputElement) {
const src = node.getAttribute('src') || '';
const name = path.basename(src);
return '[' + name + '](' + src + ')';
},
});
}

View File

@ -1,619 +0,0 @@
import { Injectable, Logger } from '@nestjs/common';
import * as path from 'path';
import { jsonToText } from '../../collaboration/collaboration.util';
import { InjectKysely } from 'nestjs-kysely';
import { KyselyDB } from '@docmost/db/types/kysely.types';
import { cleanUrlString, extractZip, FileTaskStatus } from './file.utils';
import { StorageService } from '../storage/storage.service';
import * as tmp from 'tmp-promise';
import { pipeline } from 'node:stream/promises';
import { createReadStream, createWriteStream } from 'node:fs';
import { ImportService } from './import.service';
import { promises as fs } from 'fs';
import {
generateSlugId,
getMimeType,
sanitizeFileName,
} from '../../common/helpers';
import { v7 } from 'uuid';
import { generateJitteredKeyBetween } from 'fractional-indexing-jittered';
import { FileTask, InsertablePage } from '@docmost/db/types/entity.types';
import {
DOMParser,
Node as HDNode,
Element as HDElement,
Window,
} from 'happy-dom';
import { markdownToHtml } from '@docmost/editor-ext';
import { getAttachmentFolderPath } from '../../core/attachment/attachment.utils';
import { AttachmentType } from '../../core/attachment/attachment.constants';
import { getProsemirrorContent } from '../../common/helpers/prosemirror/utils';
import { formatImportHtml, notionFormatter } from './import-formatter';
@Injectable()
export class FileTaskService {
private readonly logger = new Logger(FileTaskService.name);
constructor(
private readonly storageService: StorageService,
private readonly importService: ImportService,
@InjectKysely() private readonly db: KyselyDB,
) {}
async processZIpImport(fileTaskId: string): Promise<void> {
const fileTask = await this.db
.selectFrom('fileTasks')
.selectAll()
.where('id', '=', fileTaskId)
.executeTakeFirst();
if (!fileTask) {
this.logger.log(`File task with ID ${fileTaskId} not found`);
return;
}
const { path: tmpZipPath, cleanup: cleanupTmpFile } = await tmp.file({
prefix: 'docmost-import',
postfix: '.zip',
discardDescriptor: true,
});
const { path: tmpExtractDir, cleanup: cleanupTmpDir } = await tmp.dir({
prefix: 'docmost-extract-',
unsafeCleanup: true,
});
const fileStream = await this.storageService.readStream(fileTask.filePath);
await pipeline(fileStream, createWriteStream(tmpZipPath));
await extractZip(tmpZipPath, tmpExtractDir);
// TODO: backlinks
try {
await this.updateTaskStatus(fileTaskId, FileTaskStatus.Processing);
// if type == generic
await this.processGenericImport({ extractDir: tmpExtractDir, fileTask });
await this.updateTaskStatus(fileTaskId, FileTaskStatus.Success);
} catch (error) {
await this.updateTaskStatus(fileTaskId, FileTaskStatus.Failed);
console.error(error);
} finally {
await cleanupTmpFile();
await cleanupTmpDir();
}
}
async processGenericImport(opts: {
extractDir: string;
fileTask: FileTask;
}): Promise<void> {
const { extractDir, fileTask } = opts;
const allFiles = await this.collectMarkdownAndHtmlFiles(extractDir);
const attachmentCandidates =
await this.buildAttachmentCandidates(extractDir);
console.log('attachment count: ', attachmentCandidates.size);
const pagesMap = new Map<
string,
{
id: string;
slugId: string;
name: string;
content: string;
position?: string | null;
parentPageId: string | null;
fileExtension: string;
filePath: string;
}
>();
for (const absPath of allFiles) {
const relPath = path
.relative(extractDir, absPath)
.split(path.sep)
.join('/'); // normalize to forward-slashes
const ext = path.extname(relPath).toLowerCase();
let content = await fs.readFile(absPath, 'utf-8');
console.log('relative path: ', relPath, ' abs path: ', absPath);
if (ext.toLowerCase() === '.html' || ext.toLowerCase() === '.md') {
// we want to process all inputs as markr
if (ext === '.md') {
content = await markdownToHtml(content);
}
content = await this.rewriteLocalFilesInHtml({
html: content,
pageRelativePath: relPath,
extractDir,
pageId: v7(),
fileTask,
attachmentCandidates,
});
}
pagesMap.set(relPath, {
id: v7(),
slugId: generateSlugId(),
name: path.basename(relPath, ext),
content,
parentPageId: null,
fileExtension: ext,
filePath: relPath,
});
}
// parent/child linking
pagesMap.forEach((page, filePath) => {
const segments = filePath.split('/');
segments.pop();
let parentPage = null;
while (segments.length) {
const tryMd = segments.join('/') + '.md';
const tryHtml = segments.join('/') + '.html';
if (pagesMap.has(tryMd)) {
parentPage = pagesMap.get(tryMd)!;
break;
}
if (pagesMap.has(tryHtml)) {
parentPage = pagesMap.get(tryHtml)!;
break;
}
segments.pop();
}
if (parentPage) page.parentPageId = parentPage.id;
});
// generate position keys
const siblingsMap = new Map<string | null, typeof Array.prototype>();
pagesMap.forEach((page) => {
const sibs = siblingsMap.get(page.parentPageId) || [];
sibs.push(page);
siblingsMap.set(page.parentPageId, sibs);
});
siblingsMap.forEach((sibs) => {
sibs.sort((a, b) => a.name.localeCompare(b.name));
let prevPos: string | null = null;
for (const page of sibs) {
page.position = generateJitteredKeyBetween(prevPos, null);
prevPos = page.position;
}
});
const filePathToPageMetaMap = new Map<
string,
{ id: string; title: string; slugId: string }
>();
pagesMap.forEach((page) => {
filePathToPageMetaMap.set(page.filePath, {
id: page.id,
title: page.name,
slugId: page.slugId,
});
});
const insertablePages: InsertablePage[] = await Promise.all(
Array.from(pagesMap.values()).map(async (page) => {
const htmlContent = await this.rewriteInternalLinksToMentionHtml(
page.content,
page.filePath,
filePathToPageMetaMap,
fileTask.creatorId,
);
const pmState = getProsemirrorContent(
await this.importService.processHTML(formatImportHtml(htmlContent)),
);
const { title, prosemirrorJson } =
this.importService.extractTitleAndRemoveHeading(pmState);
return {
id: page.id,
slugId: page.slugId,
title: title || page.name,
content: prosemirrorJson,
textContent: jsonToText(prosemirrorJson),
ydoc: await this.importService.createYdoc(prosemirrorJson),
position: page.position!,
spaceId: fileTask.spaceId,
workspaceId: fileTask.workspaceId,
creatorId: fileTask.creatorId,
lastUpdatedById: fileTask.creatorId,
parentPageId: page.parentPageId,
};
}),
);
try {
await this.db.insertInto('pages').values(insertablePages).execute();
//todo: avoid duplicates
// log success
// backlinks mapping
// handle svg diagram nodes
} catch (e) {
console.error(e);
}
}
async rewriteLocalFilesInHtml(opts: {
html: string;
pageRelativePath: string;
extractDir: string;
pageId: string;
fileTask: FileTask;
attachmentCandidates: Map<string, string>;
}): Promise<string> {
const {
html,
pageRelativePath,
extractDir,
pageId,
fileTask,
attachmentCandidates,
} = opts;
const window = new Window();
const doc = window.document;
doc.body.innerHTML = html;
const tasks: Promise<void>[] = [];
const processFile = (relPath: string) => {
const abs = attachmentCandidates.get(relPath)!;
const attachmentId = v7();
const ext = path.extname(abs);
const fileNameWithExt =
sanitizeFileName(path.basename(abs, ext)) + ext.toLowerCase();
const storageFilePath = `${getAttachmentFolderPath(AttachmentType.File, fileTask.workspaceId)}/${attachmentId}/${fileNameWithExt}`;
const apiFilePath = `/api/files/${attachmentId}/${fileNameWithExt}`;
tasks.push(
(async () => {
const fileStream = createReadStream(abs);
await this.storageService.uploadStream(storageFilePath, fileStream);
const stat = await fs.stat(abs);
const uploaded = await this.db
.insertInto('attachments')
.values({
id: attachmentId,
filePath: storageFilePath,
fileName: fileNameWithExt,
fileSize: stat.size,
mimeType: getMimeType(fileNameWithExt),
type: 'file',
fileExt: ext,
creatorId: fileTask.creatorId,
workspaceId: fileTask.workspaceId,
pageId,
spaceId: fileTask.spaceId,
})
.returningAll()
.execute();
console.log(uploaded);
})(),
);
return {
attachmentId,
storageFilePath,
apiFilePath,
fileNameWithExt,
abs,
};
};
const pageDir = path.dirname(pageRelativePath);
for (const img of Array.from(doc.getElementsByTagName('img'))) {
const src = cleanUrlString(img.getAttribute('src')) ?? '';
if (!src || src.startsWith('http')) continue;
const relPath = this.resolveRelativeAttachmentPath(
src,
pageDir,
attachmentCandidates,
);
if (!relPath) continue;
const { attachmentId, apiFilePath, abs } = processFile(relPath);
const stat = await fs.stat(abs);
const width = img.getAttribute('width') || '100%';
const align = img.getAttribute('data-align') || 'center';
img.setAttribute('src', apiFilePath);
img.setAttribute('data-attachment-id', attachmentId);
img.setAttribute('data-size', stat.size.toString());
img.setAttribute('width', width);
img.setAttribute('data-align', align);
this.unwrapFromParagraph(img);
}
// rewrite <video>
for (const vid of Array.from(doc.getElementsByTagName('video'))) {
const src = cleanUrlString(vid.getAttribute('src')) ?? '';
if (!src || src.startsWith('http')) continue;
const relPath = this.resolveRelativeAttachmentPath(
src,
pageDir,
attachmentCandidates,
);
if (!relPath) continue;
const { attachmentId, apiFilePath, abs } = processFile(relPath);
const stat = await fs.stat(abs);
const width = vid.getAttribute('width') || '100%';
const align = vid.getAttribute('data-align') || 'center';
vid.setAttribute('src', apiFilePath);
vid.setAttribute('data-attachment-id', attachmentId);
vid.setAttribute('data-size', stat.size.toString());
vid.setAttribute('width', width);
vid.setAttribute('data-align', align);
// @ts-ignore
this.unwrapFromParagraph(vid);
}
// rewrite other attachments via <a>
for (const a of Array.from(doc.getElementsByTagName('a'))) {
const href = cleanUrlString(a.getAttribute('href')) ?? '';
if (!href || href.startsWith('http')) continue;
const relPath = this.resolveRelativeAttachmentPath(
href,
pageDir,
attachmentCandidates,
);
if (!relPath) continue;
const { attachmentId, apiFilePath, abs } = processFile(relPath);
const stat = await fs.stat(abs);
const ext = path.extname(relPath).toLowerCase();
if (ext === '.mp4') {
const video = doc.createElement('video');
video.setAttribute('src', apiFilePath);
video.setAttribute('data-attachment-id', attachmentId);
video.setAttribute('data-size', stat.size.toString());
video.setAttribute('width', '100%');
video.setAttribute('data-align', 'center');
a.replaceWith(video);
// @ts-ignore
this.unwrapFromParagraph(video);
} else {
const div = doc.createElement('div') as HDElement;
div.setAttribute('data-type', 'attachment');
div.setAttribute('data-attachment-url', apiFilePath);
div.setAttribute('data-attachment-name', path.basename(abs));
div.setAttribute('data-attachment-mime', getMimeType(abs));
div.setAttribute('data-attachment-size', stat.size.toString());
div.setAttribute('data-attachment-id', attachmentId);
a.replaceWith(div);
this.unwrapFromParagraph(div);
}
}
const attachmentDivs = Array.from(
doc.querySelectorAll('div[data-type="attachment"]'),
);
for (const oldDiv of attachmentDivs) {
const rawUrl =
cleanUrlString(oldDiv.getAttribute('data-attachment-url')) ?? '';
if (!rawUrl || rawUrl.startsWith('http')) continue;
const relPath = this.resolveRelativeAttachmentPath(
rawUrl,
pageDir,
attachmentCandidates,
);
if (!relPath) continue;
const { attachmentId, apiFilePath, abs } = processFile(relPath);
const stat = await fs.stat(abs);
const fileName = path.basename(abs);
const mime = getMimeType(abs);
const div = doc.createElement('div') as HDElement;
div.setAttribute('data-type', 'attachment');
div.setAttribute('data-attachment-url', apiFilePath);
div.setAttribute('data-attachment-name', fileName);
div.setAttribute('data-attachment-mime', mime);
div.setAttribute('data-attachment-size', stat.size.toString());
div.setAttribute('data-attachment-id', attachmentId);
oldDiv.replaceWith(div);
this.unwrapFromParagraph(div);
}
for (const type of ['excalidraw', 'drawio'] as const) {
const selector = `div[data-type="${type}"]`;
const oldDivs = Array.from(doc.querySelectorAll(selector));
for (const oldDiv of oldDivs) {
const rawSrc = cleanUrlString(oldDiv.getAttribute('data-src')) ?? '';
if (!rawSrc || rawSrc.startsWith('http')) continue;
const relPath = this.resolveRelativeAttachmentPath(
rawSrc,
pageDir,
attachmentCandidates,
);
if (!relPath) continue;
const { attachmentId, apiFilePath, abs } = processFile(relPath);
const stat = await fs.stat(abs);
const fileName = path.basename(abs);
const width = oldDiv.getAttribute('data-width') || '100%';
const align = oldDiv.getAttribute('data-align') || 'center';
const newDiv = doc.createElement('div') as HDElement;
newDiv.setAttribute('data-type', type);
newDiv.setAttribute('data-src', apiFilePath);
newDiv.setAttribute('data-title', fileName);
newDiv.setAttribute('data-width', width);
newDiv.setAttribute('data-size', stat.size.toString());
newDiv.setAttribute('data-align', align);
newDiv.setAttribute('data-attachment-id', attachmentId);
oldDiv.replaceWith(newDiv);
this.unwrapFromParagraph(newDiv);
}
}
// wait for all uploads & DB inserts
await Promise.all(tasks);
return doc.documentElement.outerHTML;
}
async rewriteInternalLinksToMentionHtml(
html: string,
currentFilePath: string,
filePathToPageMetaMap: Map<
string,
{ id: string; title: string; slugId: string }
>,
creatorId: string,
): Promise<string> {
const window = new Window();
const doc = window.document;
doc.body.innerHTML = html;
// normalize helper
const normalize = (p: string) => p.replace(/\\/g, '/');
for (const a of Array.from(doc.getElementsByTagName('a'))) {
const rawHref = a.getAttribute('href');
if (!rawHref) continue;
// skip absolute/external URLs
if (rawHref.startsWith('http') || rawHref.startsWith('/api/')) {
continue;
}
const decodedRef = decodeURIComponent(rawHref);
const parentDir = path.dirname(currentFilePath);
const joined = path.join(parentDir, decodedRef);
const resolved = normalize(joined);
const pageMeta = filePathToPageMetaMap.get(resolved);
if (!pageMeta) {
// not an internal link we know about
continue;
}
const mentionEl = doc.createElement('span') as HDElement;
mentionEl.setAttribute('data-type', 'mention');
mentionEl.setAttribute('data-id', v7());
mentionEl.setAttribute('data-entity-type', 'page');
mentionEl.setAttribute('data-entity-id', pageMeta.id);
mentionEl.setAttribute('data-label', pageMeta.title);
mentionEl.setAttribute('data-slug-id', pageMeta.slugId);
mentionEl.setAttribute('data-creator-id', creatorId);
mentionEl.textContent = pageMeta.title;
a.replaceWith(mentionEl);
}
return doc.body.innerHTML;
}
unwrapFromParagraph(node: HDElement) {
let wrapper = node.closest('p, a') as HDElement | null;
while (wrapper) {
if (wrapper.childNodes.length === 1) {
// e.g. <p><node/></p> or <a><node/></a> → <node/>
wrapper.replaceWith(node);
} else {
wrapper.parentNode!.insertBefore(node, wrapper);
}
wrapper = node.closest('p, a') as HDElement | null;
}
}
async buildAttachmentCandidates(
extractDir: string,
): Promise<Map<string, string>> {
const map = new Map<string, string>();
async function walk(dir: string) {
for (const ent of await fs.readdir(dir, { withFileTypes: true })) {
const abs = path.join(dir, ent.name);
if (ent.isDirectory()) {
await walk(abs);
} else {
if (['.md', '.html'].includes(path.extname(ent.name).toLowerCase())) {
continue;
}
const rel = path.relative(extractDir, abs).split(path.sep).join('/');
map.set(rel, abs);
}
}
}
await walk(extractDir);
return map;
}
async collectMarkdownAndHtmlFiles(dir: string): Promise<string[]> {
const results: string[] = [];
async function walk(current: string) {
const entries = await fs.readdir(current, { withFileTypes: true });
for (const ent of entries) {
const fullPath = path.join(current, ent.name);
if (ent.isDirectory()) {
await walk(fullPath);
} else if (
['.md', '.html'].includes(path.extname(ent.name).toLowerCase())
) {
results.push(fullPath);
}
}
}
await walk(dir);
return results;
}
resolveRelativeAttachmentPath(
raw: string,
pageDir: string,
attachmentCandidates: Map<string, string>,
): string | null {
const mainRel = decodeURIComponent(raw.replace(/^\.?\/+/, ''));
const fallback = path.normalize(path.join(pageDir, mainRel));
if (attachmentCandidates.has(mainRel)) {
return mainRel;
}
if (attachmentCandidates.has(fallback)) {
return fallback;
}
return null;
}
async updateTaskStatus(fileTaskId: string, status: FileTaskStatus) {
await this.db
.updateTable('fileTasks')
.set({ status: status })
.where('id', '=', fileTaskId)
.execute();
}
}

View File

@ -1,94 +0,0 @@
import * as yauzl from 'yauzl';
import * as path from 'path';
import * as fs from 'node:fs';
export enum FileTaskType {
Import = 'import',
Export = 'export',
}
export enum FileImportType {
Generic = 'generic',
Notion = 'notion',
Confluence = 'confluence',
}
export enum FileTaskStatus {
Pending = 'pending',
Processing = 'processing',
Success = 'success',
Failed = 'failed',
}
export function getFileTaskFolderPath(
type: FileTaskType,
workspaceId: string,
): string {
switch (type) {
case FileTaskType.Import:
return `${workspaceId}/imports`;
case FileTaskType.Export:
return `${workspaceId}/exports`;
}
}
export function extractZip(source: string, target: string) {
//https://github.com/Surfer-Org
return new Promise((resolve, reject) => {
yauzl.open(
source,
{ lazyEntries: true, decodeStrings: false, autoClose: true },
(err, zipfile) => {
if (err) return reject(err);
zipfile.readEntry();
zipfile.on('entry', (entry) => {
const name = entry.fileName.toString('utf8'); // or 'cp437' if you need the original DOS charset
const safeName = name.replace(/^\/+/, ''); // strip any leading slashes
const fullPath = path.join(target, safeName);
const directory = path.dirname(fullPath);
// <-- skip all macOS metadata
if (safeName.startsWith('__MACOSX/')) {
return zipfile.readEntry();
}
if (/\/$/.test(entry.fileName)) {
// Directory entry
try {
fs.mkdirSync(fullPath, { recursive: true });
zipfile.readEntry();
} catch (err) {
reject(err);
}
} else {
// File entry
try {
fs.mkdirSync(directory, { recursive: true });
zipfile.openReadStream(entry, (err, readStream) => {
if (err) return reject(err);
const writeStream = fs.createWriteStream(fullPath);
readStream.on('end', () => {
writeStream.end();
zipfile.readEntry();
});
readStream.pipe(writeStream);
});
} catch (err) {
reject(err);
}
}
});
zipfile.on('end', resolve);
zipfile.on('error', reject);
},
);
});
}
export function cleanUrlString(url: string): string {
const [maybePath] = url.split('?', 1);
return maybePath;
}

View File

@ -1,170 +0,0 @@
import { Window } from 'happy-dom';
import { cleanUrlString } from './file.utils';
import { getEmbedUrlAndProvider } from '@docmost/editor-ext';
export function formatImportHtml(html: string) {
const pmHtml = notionFormatter(html);
return defaultHtmlFormatter(pmHtml);
}
export function defaultHtmlFormatter(html: string): string {
const window = new Window();
const doc = window.document;
doc.body.innerHTML = html;
// embed providers
const anchors = Array.from(doc.getElementsByTagName('a'));
for (const a of anchors) {
const href = cleanUrlString(a.getAttribute('href')) ?? '';
if (!href) continue;
const embedProvider = getEmbedUrlAndProvider(href);
if (embedProvider) {
const embed = doc.createElement('div');
embed.setAttribute('data-type', 'embed');
embed.setAttribute('data-src', href);
embed.setAttribute('data-provider', embedProvider.provider);
embed.setAttribute('data-align', 'center');
embed.setAttribute('data-width', '640');
embed.setAttribute('data-height', '480');
a.replaceWith(embed);
}
}
return doc.body.innerHTML;
}
export function notionFormatter(html: string): string {
const window = new Window();
const doc = window.document;
doc.body.innerHTML = html;
// remove empty description paragraph
doc.querySelectorAll('p.page-description').forEach((p) => {
if (p.textContent?.trim() === '') {
p.remove();
}
});
// Block math
for (const fig of Array.from(doc.querySelectorAll('figure.equation'))) {
// get TeX source from the MathML <annotation>
const annotation = fig.querySelector(
'annotation[encoding="application/x-tex"]',
);
const tex = annotation?.textContent?.trim() ?? '';
const mathBlock = doc.createElement('div');
mathBlock.setAttribute('data-type', 'mathBlock');
mathBlock.setAttribute('data-katex', 'true');
mathBlock.textContent = tex;
fig.replaceWith(mathBlock);
}
// Inline math
for (const token of Array.from(
doc.querySelectorAll('span.notion-text-equation-token'),
)) {
// remove the preceding <style> if its that KaTeX import
const prev = token.previousElementSibling;
if (prev?.tagName === 'STYLE') prev.remove();
const annotation = token.querySelector(
'annotation[encoding="application/x-tex"]',
);
const tex = annotation?.textContent?.trim() ?? '';
const mathInline = doc.createElement('span');
mathInline.setAttribute('data-type', 'mathInline');
mathInline.setAttribute('data-katex', 'true');
mathInline.textContent = tex;
token.replaceWith(mathInline);
}
// Callouts
const figs = Array.from(doc.querySelectorAll('figure.callout')).reverse();
for (const fig of figs) {
// find the content <div> (always the 2nd child in a Notion callout)
const contentDiv = fig.querySelector(
'div:nth-of-type(2)',
) as unknown as HTMLElement | null;
if (!contentDiv) continue;
// pull out every block inside (tables, p, nested callouts, lists…)
const blocks = Array.from(contentDiv.childNodes);
const wrapper = fig.ownerDocument.createElement('div');
wrapper.setAttribute('data-type', 'callout');
wrapper.setAttribute('data-callout-type', 'info');
// move each real node into the wrapper (preserves nested structure)
// @ts-ignore
wrapper.append(...blocks);
fig.replaceWith(wrapper);
}
// Todolist
const todoLists = Array.from(doc.querySelectorAll('ul.to-do-list'));
for (const oldList of todoLists) {
const newList = doc.createElement('ul');
newList.setAttribute('data-type', 'taskList');
// for each old <li>, create a <li data-type="taskItem" data-checked="…">
for (const li of oldList.querySelectorAll('li')) {
const isChecked = li.querySelector('.checkbox.checkbox-on') != null;
const textSpan = li.querySelector(
'span.to-do-children-unchecked, span.to-do-children-checked',
);
const text = textSpan?.textContent?.trim() ?? '';
// <li data-type="taskItem" data-checked="true|false">
const taskItem = doc.createElement('li');
taskItem.setAttribute('data-type', 'taskItem');
taskItem.setAttribute('data-checked', String(isChecked));
// <label><input type="checkbox" [checked]><span></span></label>
const label = doc.createElement('label');
const input = doc.createElement('input');
input.type = 'checkbox';
if (isChecked) input.checked = true;
const spacer = doc.createElement('span');
label.append(input, spacer);
const container = doc.createElement('div');
const p = doc.createElement('p');
p.textContent = text;
container.appendChild(p);
taskItem.append(label, container);
newList.appendChild(taskItem);
}
oldList.replaceWith(newList);
}
// Fix toggle blocks
const detailsList = Array.from(
doc.querySelectorAll('ul.toggle details'),
).reverse();
// unwrap from ul and li tags
for (const details of detailsList) {
const li = details.closest('li');
if (li) {
li.parentNode!.insertBefore(details, li);
if (li.childNodes.length === 0) li.remove();
}
const ul = details.closest('ul.toggle');
if (ul) {
ul.parentNode!.insertBefore(details, ul);
if (ul.childNodes.length === 0) ul.remove();
}
}
return doc.body.innerHTML;
}

View File

@ -83,57 +83,4 @@ export class ImportController {
return this.importService.importPage(file, user.id, spaceId, workspace.id); return this.importService.importPage(file, user.id, spaceId, workspace.id);
} }
@UseInterceptors(FileInterceptor)
@UseGuards(JwtAuthGuard)
@HttpCode(HttpStatus.OK)
// temporary naming
@Post('pages/import-zip')
async importZip(
@Req() req: any,
@AuthUser() user: User,
@AuthWorkspace() workspace: Workspace,
) {
const validFileExtensions = ['.zip'];
const maxFileSize = bytes('100mb');
let file = null;
try {
file = await req.file({
limits: { fileSize: maxFileSize, fields: 3, files: 1 },
});
} catch (err: any) {
this.logger.error(err.message);
if (err?.statusCode === 413) {
throw new BadRequestException(
`File too large. Exceeds the 100mb import limit`,
);
}
}
if (!file) {
throw new BadRequestException('Failed to upload file');
}
if (
!validFileExtensions.includes(path.extname(file.filename).toLowerCase())
) {
throw new BadRequestException('Invalid import file type.');
}
const spaceId = file.fields?.spaceId?.value;
const source = file.fields?.source?.value;
if (!spaceId) {
throw new BadRequestException('spaceId or format not found');
}
const ability = await this.spaceAbility.createForUser(user, spaceId);
if (ability.cannot(SpaceCaslAction.Edit, SpaceCaslSubject.Page)) {
throw new ForbiddenException();
}
return this.importService.importZip(file, source, user.id, spaceId, workspace.id);
}
} }

View File

@ -1,13 +1,9 @@
import { Module } from '@nestjs/common'; import { Module } from '@nestjs/common';
import { ImportService } from './import.service'; import { ImportService } from './import.service';
import { ImportController } from './import.controller'; import { ImportController } from './import.controller';
import { StorageModule } from '../storage/storage.module';
import { FileTaskService } from './file-task.service';
import { FileTaskProcessor } from './processors/file-task.processor';
@Module({ @Module({
providers: [ImportService, FileTaskService, FileTaskProcessor], providers: [ImportService],
controllers: [ImportController], controllers: [ImportController],
imports: [StorageModule],
}) })
export class ImportModule {} export class ImportModule {}

View File

@ -4,8 +4,7 @@ import { MultipartFile } from '@fastify/multipart';
import { sanitize } from 'sanitize-filename-ts'; import { sanitize } from 'sanitize-filename-ts';
import * as path from 'path'; import * as path from 'path';
import { import {
htmlToJson, htmlToJson, jsonToText,
jsonToText,
tiptapExtensions, tiptapExtensions,
} from '../../collaboration/collaboration.util'; } from '../../collaboration/collaboration.util';
import { InjectKysely } from 'nestjs-kysely'; import { InjectKysely } from 'nestjs-kysely';
@ -14,20 +13,7 @@ import { generateSlugId } from '../../common/helpers';
import { generateJitteredKeyBetween } from 'fractional-indexing-jittered'; import { generateJitteredKeyBetween } from 'fractional-indexing-jittered';
import { TiptapTransformer } from '@hocuspocus/transformer'; import { TiptapTransformer } from '@hocuspocus/transformer';
import * as Y from 'yjs'; import * as Y from 'yjs';
import { markdownToHtml } from '@docmost/editor-ext'; import { markdownToHtml } from "@docmost/editor-ext";
import {
FileTaskStatus,
FileTaskType,
getFileTaskFolderPath,
} from './file.utils';
import { v7, v7 as uuid7 } from 'uuid';
import { StorageService } from '../storage/storage.service';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
import { QueueJob, QueueName } from '../queue/constants';
import { Node as PMNode } from '@tiptap/pm/model';
import { EditorState, Transaction } from '@tiptap/pm/state';
import { getSchema } from '@tiptap/core';
@Injectable() @Injectable()
export class ImportService { export class ImportService {
@ -35,10 +21,7 @@ export class ImportService {
constructor( constructor(
private readonly pageRepo: PageRepo, private readonly pageRepo: PageRepo,
private readonly storageService: StorageService,
@InjectKysely() private readonly db: KyselyDB, @InjectKysely() private readonly db: KyselyDB,
@InjectQueue(QueueName.FILE_TASK_QUEUE)
private readonly fileTaskQueue: Queue,
) {} ) {}
async importPage( async importPage(
@ -130,7 +113,7 @@ export class ImportService {
async createYdoc(prosemirrorJson: any): Promise<Buffer | null> { async createYdoc(prosemirrorJson: any): Promise<Buffer | null> {
if (prosemirrorJson) { if (prosemirrorJson) {
// this.logger.debug(`Converting prosemirror json state to ydoc`); this.logger.debug(`Converting prosemirror json state to ydoc`);
const ydoc = TiptapTransformer.toYdoc( const ydoc = TiptapTransformer.toYdoc(
prosemirrorJson, prosemirrorJson,
@ -146,34 +129,20 @@ export class ImportService {
} }
extractTitleAndRemoveHeading(prosemirrorState: any) { extractTitleAndRemoveHeading(prosemirrorState: any) {
let title: string | null = null; let title = null;
const content = prosemirrorState.content ?? [];
if ( if (
content.length > 0 && prosemirrorState?.content?.length > 0 &&
content[0].type === 'heading' && prosemirrorState.content[0].type === 'heading' &&
content[0].attrs?.level === 1 prosemirrorState.content[0].attrs?.level === 1
) { ) {
title = content[0].content?.[0]?.text ?? null; title = prosemirrorState.content[0].content[0].text;
content.shift();
// remove h1 header node from state
prosemirrorState.content.shift();
} }
// ensure at least one paragraph return { title, prosemirrorJson: prosemirrorState };
if (content.length === 0) {
content.push({
type: 'paragraph',
content: [],
});
}
return {
title,
prosemirrorJson: {
...prosemirrorState,
content,
},
};
} }
async getNewPagePosition(spaceId: string): Promise<string> { async getNewPagePosition(spaceId: string): Promise<string> {
@ -192,141 +161,4 @@ export class ImportService {
return generateJitteredKeyBetween(null, null); return generateJitteredKeyBetween(null, null);
} }
} }
async importZip(
filePromise: Promise<MultipartFile>,
source: string,
userId: string,
spaceId: string,
workspaceId: string,
): Promise<void> {
const file = await filePromise;
const fileBuffer = await file.toBuffer();
const fileExtension = path.extname(file.filename).toLowerCase();
const fileName = sanitize(
path.basename(file.filename, fileExtension).slice(0, 255),
);
const fileTaskId = uuid7();
const filePath = `${getFileTaskFolderPath(FileTaskType.Import, workspaceId)}/${fileTaskId}/${fileName}`;
// upload file
await this.storageService.upload(filePath, fileBuffer);
// store in fileTasks table
await this.db
.insertInto('fileTasks')
.values({
id: fileTaskId,
type: FileTaskType.Import,
source: source,
status: FileTaskStatus.Pending,
fileName: fileName,
filePath: filePath,
fileSize: 0,
fileExt: 'zip',
creatorId: userId,
spaceId: spaceId,
workspaceId: workspaceId,
})
.execute();
// what to send to queue
// pass the task ID
await this.fileTaskQueue.add(QueueJob.IMPORT_TASK, {
fileTaskId: fileTaskId,
});
// return tasks info
// when the processor picks it up
// we change the status to processing
// if it gets processed successfully,
// we change the status to success
// else failed
}
async markdownOrHtmlToProsemirror(
fileContent: string,
fileExtension: string,
): Promise<any> {
let prosemirrorState = '';
if (fileExtension === '.md') {
prosemirrorState = await this.processMarkdown(fileContent);
} else if (fileExtension.endsWith('.html')) {
prosemirrorState = await this.processHTML(fileContent);
}
return prosemirrorState;
}
async convertInternalLinksToMentionsPM(
doc: PMNode,
currentFilePath: string,
filePathToPageMetaMap: Map<
string,
{ id: string; title: string; slugId: string }
>,
): Promise<PMNode> {
const schema = getSchema(tiptapExtensions);
const state = EditorState.create({ doc, schema });
let tr: Transaction = state.tr;
const normalizePath = (p: string) => p.replace(/\\/g, '/');
// Collect replacements from the original doc.
const replacements: Array<{
from: number;
to: number;
mentionNode: PMNode;
}> = [];
doc.descendants((node, pos) => {
if (!node.isText || !node.marks?.length) return;
// Look for the link mark
const linkMark = node.marks.find(
(mark) => mark.type.name === 'link' && mark.attrs?.href,
);
if (!linkMark) return;
// Compute the range for the entire text node.
const from = pos;
const to = pos + node.nodeSize;
// Resolve the path and get page meta.
const resolvedPath = normalizePath(
path.join(path.dirname(currentFilePath), linkMark.attrs.href),
);
const pageMeta = filePathToPageMetaMap.get(resolvedPath);
if (!pageMeta) return;
// Create the mention node with all required attributes.
const mentionNode = schema.nodes.mention.create({
id: v7(),
entityType: 'page',
entityId: pageMeta.id,
label: node.text || pageMeta.title,
slugId: pageMeta.slugId,
creatorId: 'not available', // This is required per your schema.
});
replacements.push({ from, to, mentionNode });
});
// Apply replacements in reverse order.
for (let i = replacements.length - 1; i >= 0; i--) {
const { from, to, mentionNode } = replacements[i];
try {
tr = tr.replaceWith(from, to, mentionNode);
} catch (err) {
console.error('❌ Failed to insert mention:', err);
}
}
if (tr.docChanged) {
console.log('doc changed');
console.log(JSON.stringify(state.apply(tr).doc.toJSON()));
}
// Return the updated document if any change was made.
return tr.docChanged ? state.apply(tr).doc : doc;
}
} }

View File

@ -1,52 +0,0 @@
import { Logger, OnModuleDestroy } from '@nestjs/common';
import { OnWorkerEvent, Processor, WorkerHost } from '@nestjs/bullmq';
import { Job } from 'bullmq';
import { QueueJob, QueueName } from 'src/integrations/queue/constants';
import { FileTaskService } from '../file-task.service';
@Processor(QueueName.FILE_TASK_QUEUE)
export class FileTaskProcessor extends WorkerHost implements OnModuleDestroy {
private readonly logger = new Logger(FileTaskProcessor.name);
constructor(private readonly fileTaskService: FileTaskService) {
super();
}
async process(job: Job<any, void>): Promise<void> {
try {
switch (job.name) {
case QueueJob.IMPORT_TASK:
console.log('import task', job.data.fileTaskId);
await this.fileTaskService.processZIpImport(job.data.fileTaskId);
break;
case QueueJob.EXPORT_TASK:
console.log('export task', job.data.fileTaskId);
}
} catch (err) {
console.error(err);
throw err;
}
}
@OnWorkerEvent('active')
onActive(job: Job) {
this.logger.debug(`Processing ${job.name} job`);
}
@OnWorkerEvent('failed')
onError(job: Job) {
this.logger.error(
`Error processing ${job.name} job. Reason: ${job.failedReason}`,
);
}
@OnWorkerEvent('completed')
onCompleted(job: Job) {
this.logger.debug(`Completed ${job.name} job`);
}
async onModuleDestroy(): Promise<void> {
if (this.worker) {
await this.worker.close();
}
}
}

View File

@ -3,7 +3,6 @@ export enum QueueName {
ATTACHMENT_QUEUE = '{attachment-queue}', ATTACHMENT_QUEUE = '{attachment-queue}',
GENERAL_QUEUE = '{general-queue}', GENERAL_QUEUE = '{general-queue}',
BILLING_QUEUE = '{billing-queue}', BILLING_QUEUE = '{billing-queue}',
FILE_TASK_QUEUE = '{file-task-queue}',
} }
export enum QueueJob { export enum QueueJob {
@ -20,7 +19,4 @@ export enum QueueJob {
TRIAL_ENDED = 'trial-ended', TRIAL_ENDED = 'trial-ended',
WELCOME_EMAIL = 'welcome-email', WELCOME_EMAIL = 'welcome-email',
FIRST_PAYMENT_EMAIL = 'first-payment-email', FIRST_PAYMENT_EMAIL = 'first-payment-email',
IMPORT_TASK = 'import-task',
EXPORT_TASK = 'export-task',
} }

Some files were not shown because too many files have changed in this diff Show More