Skip to content

armgit / plane

Public Imported from GitHub
0

πŸ”₯πŸ”₯πŸ”₯ Open-source Jira, Linear, Monday, and ClickUp alternative. Plane is a modern project management platform to manage tasks, sprints, docs, and triage.

[WEB-460] refactor: editors, chore: pages list improvement (#4090)

Aaryan Khandelwal3e2355e2233d
diff --git a/apiserver/plane/app/serializers/__init__.py b/apiserver/plane/app/serializers/__init__.py
index 2f3c944509..cd0fc11ce7 100644
--- a/apiserver/plane/app/serializers/__init__.py
+++ b/apiserver/plane/app/serializers/__init__.py
@@ -93,6 +93,7 @@ from .page import (
PageSerializer,
PageLogSerializer,
SubPageSerializer,
+ PageDetailSerializer,
PageFavoriteSerializer,
)
diff --git a/apiserver/plane/app/serializers/page.py b/apiserver/plane/app/serializers/page.py
index 4dfe6ea9d6..604ac2c2e3 100644
--- a/apiserver/plane/app/serializers/page.py
+++ b/apiserver/plane/app/serializers/page.py
@@ -3,9 +3,6 @@ from rest_framework import serializers
# Module imports
from .base import BaseSerializer
-from .issue import LabelLiteSerializer
-from .workspace import WorkspaceLiteSerializer
-from .project import ProjectLiteSerializer
from plane.db.models import (
Page,
PageLog,
@@ -17,22 +14,33 @@ from plane.db.models import (
class PageSerializer(BaseSerializer):
is_favorite = serializers.BooleanField(read_only=True)
- label_details = LabelLiteSerializer(
- read_only=True, source="labels", many=True
- )
labels = serializers.ListField(
child=serializers.PrimaryKeyRelatedField(queryset=Label.objects.all()),
write_only=True,
required=False,
)
- project_detail = ProjectLiteSerializer(source="project", read_only=True)
- workspace_detail = WorkspaceLiteSerializer(
- source="workspace", read_only=True
- )
class Meta:
model = Page
- fields = "__all__"
+ fields = [
+ "id",
+ "name",
+ "owned_by",
+ "access",
+ "color",
+ "labels",
+ "parent",
+ "is_favorite",
+ "is_locked",
+ "archived_at",
+ "workspace",
+ "project",
+ "created_at",
+ "updated_at",
+ "created_by",
+ "updated_by",
+ "view_props",
+ ]
read_only_fields = [
"workspace",
"project",
@@ -48,8 +56,12 @@ class PageSerializer(BaseSerializer):
labels = validated_data.pop("labels", None)
project_id = self.context["project_id"]
owned_by_id = self.context["owned_by_id"]
+ description_html = self.context["description_html"]
page = Page.objects.create(
- **validated_data, project_id=project_id, owned_by_id=owned_by_id
+ **validated_data,
+ description_html=description_html,
+ project_id=project_id,
+ owned_by_id=owned_by_id,
)
if labels is not None:
@@ -91,6 +103,13 @@ class PageSerializer(BaseSerializer):
return super().update(instance, validated_data)
+class PageDetailSerializer(PageSerializer):
+ description_html = serializers.CharField()
+
+ class Meta(PageSerializer.Meta):
+ fields = PageSerializer.Meta.fields + ["description_html"]
+
+
class SubPageSerializer(BaseSerializer):
entity_details = serializers.SerializerMethodField()
diff --git a/apiserver/plane/app/urls/page.py b/apiserver/plane/app/urls/page.py
index 58cec2cd46..1a73e4ed30 100644
--- a/apiserver/plane/app/urls/page.py
+++ b/apiserver/plane/app/urls/page.py
@@ -31,102 +31,51 @@ urlpatterns = [
),
name="project-pages",
),
+ # favorite pages
path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/user-favorite-pages/",
+ "workspaces/<str:slug>/projects/<uuid:project_id>/favorite-pages/<uuid:pk>/",
PageFavoriteViewSet.as_view(
{
- "get": "list",
"post": "create",
- }
- ),
- name="user-favorite-pages",
- ),
- path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/user-favorite-pages/<uuid:page_id>/",
- PageFavoriteViewSet.as_view(
- {
"delete": "destroy",
}
),
name="user-favorite-pages",
),
+ # archived pages
path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/",
- PageViewSet.as_view(
- {
- "get": "list",
- "post": "create",
- }
- ),
- name="project-pages",
- ),
- path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:pk>/",
- PageViewSet.as_view(
- {
- "get": "retrieve",
- "patch": "partial_update",
- "delete": "destroy",
- }
- ),
- name="project-pages",
- ),
- path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:page_id>/archive/",
+ "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:pk>/archive/",
PageViewSet.as_view(
{
"post": "archive",
+ "delete": "unarchive",
}
),
- name="project-page-archive",
- ),
- path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:page_id>/unarchive/",
- PageViewSet.as_view(
- {
- "post": "unarchive",
- }
- ),
- name="project-page-unarchive",
- ),
- path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/archived-pages/",
- PageViewSet.as_view(
- {
- "get": "archive_list",
- }
- ),
- name="project-pages",
+ name="project-page-archive-unarchive",
),
+ # lock and unlock
path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:page_id>/lock/",
+ "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:pk>/lock/",
PageViewSet.as_view(
{
"post": "lock",
+ "delete": "unlock",
}
),
- name="project-pages",
- ),
- path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:page_id>/unlock/",
- PageViewSet.as_view(
- {
- "post": "unlock",
- }
- ),
+ name="project-pages-lock-unlock",
),
path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:page_id>/transactions/",
+ "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:pk>/transactions/",
PageLogEndpoint.as_view(),
name="page-transactions",
),
path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:page_id>/transactions/<uuid:transaction>/",
+ "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:pk>/transactions/<uuid:transaction>/",
PageLogEndpoint.as_view(),
name="page-transactions",
),
path(
- "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:page_id>/sub-pages/",
+ "workspaces/<str:slug>/projects/<uuid:project_id>/pages/<uuid:pk>/sub-pages/",
SubPagesEndpoint.as_view(),
name="sub-page",
),
diff --git a/apiserver/plane/app/views/page/base.py b/apiserver/plane/app/views/page/base.py
index d60d78500c..1bbfdf33f8 100644
--- a/apiserver/plane/app/views/page/base.py
+++ b/apiserver/plane/app/views/page/base.py
@@ -1,4 +1,5 @@
# Python imports
+import json
from datetime import datetime
# Django imports
@@ -17,6 +18,7 @@ from plane.app.serializers import (
PageLogSerializer,
PageSerializer,
SubPageSerializer,
+ PageDetailSerializer,
)
from plane.db.models import (
Page,
@@ -28,6 +30,8 @@ from plane.db.models import (
# Module imports
from ..base import BaseAPIView, BaseViewSet
+from plane.bgtasks.page_transaction_task import page_transaction
+
def unarchive_archive_page_and_descendants(page_id, archived_at):
# Your SQL query
@@ -87,11 +91,21 @@ class PageViewSet(BaseViewSet):
def create(self, request, slug, project_id):
serializer = PageSerializer(
data=request.data,
- context={"project_id": project_id, "owned_by_id": request.user.id},
+ context={
+ "project_id": project_id,
+ "owned_by_id": request.user.id,
+ "description_html": request.data.get(
+ "description_html", "<p></p>"
+ ),
+ },
)
if serializer.is_valid():
serializer.save()
+ # capture the page transaction
+ page_transaction.delay(request.data, None, serializer.data["id"])
+ page = Page.objects.get(pk=serializer.data["id"])
+ serializer = PageDetailSerializer(page)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@@ -125,9 +139,22 @@ class PageViewSet(BaseViewSet):
status=status.HTTP_400_BAD_REQUEST,
)
- serializer = PageSerializer(page, data=request.data, partial=True)
+ serializer = PageDetailSerializer(
+ page, data=request.data, partial=True
+ )
if serializer.is_valid():
serializer.save()
+ # capture the page transaction
+ if request.data.get("description_html"):
+ page_transaction.delay(
+ new_value=request.data,
+ old_value=json.dumps(
+ {
+ "description_html": page.description_html,
+ }
+ ),
+ page_id=pk,
+ )
return Response(serializer.data, status=status.HTTP_200_OK)
return Response(
serializer.errors, status=status.HTTP_400_BAD_REQUEST
@@ -140,18 +167,24 @@ class PageViewSet(BaseViewSet):
status=status.HTTP_400_BAD_REQUEST,
)
- def lock(self, request, slug, project_id, page_id):
+ def retrieve(self, request, slug, project_id, pk=None):
+ page = self.get_queryset().filter(pk=pk).first()
+ return Response(
+ PageDetailSerializer(page).data, status=status.HTTP_200_OK
+ )
+
+ def lock(self, request, slug, project_id, pk):
page = Page.objects.filter(
- pk=page_id, workspace__slug=slug, project_id=project_id
+ pk=pk, workspace__slug=slug, project_id=project_id
).first()
page.is_locked = True
page.save()
return Response(status=status.HTTP_204_NO_CONTENT)
- def unlock(self, request, slug, project_id, page_id):
+ def unlock(self, request, slug, project_id, pk):
page = Page.objects.filter(
- pk=page_id, workspace__slug=slug, project_id=project_id
+ pk=pk, workspace__slug=slug, project_id=project_id
).first()
page.is_locked = False
@@ -160,13 +193,13 @@ class PageViewSet(BaseViewSet):
return Response(status=status.HTTP_204_NO_CONTENT)
def list(self, request, slug, project_id):
- queryset = self.get_queryset().filter(archived_at__isnull=True)
+ queryset = self.get_queryset()
pages = PageSerializer(queryset, many=True).data
return Response(pages, status=status.HTTP_200_OK)
- def archive(self, request, slug, project_id, page_id):
+ def archive(self, request, slug, project_id, pk):
page = Page.objects.get(
- pk=page_id, workspace__slug=slug, project_id=project_id
+ pk=pk, workspace__slug=slug, project_id=project_id
)
# only the owner or admin can archive the page
@@ -184,13 +217,16 @@ class PageViewSet(BaseViewSet):
status=status.HTTP_400_BAD_REQUEST,
)
- unarchive_archive_page_and_descendants(page_id, datetime.now())
+ unarchive_archive_page_and_descendants(pk, datetime.now())
- return Response(status=status.HTTP_204_NO_CONTENT)
+ return Response(
+ {"archived_at": str(datetime.now())},
+ status=status.HTTP_200_OK,
+ )
- def unarchive(self, request, slug, project_id, page_id):
+ def unarchive(self, request, slug, project_id, pk):
page = Page.objects.get(
- pk=page_id, workspace__slug=slug, project_id=project_id
+ pk=pk, workspace__slug=slug, project_id=project_id
)
# only the owner or admin can un archive the page
@@ -213,19 +249,10 @@ class PageViewSet(BaseViewSet):
page.parent = None
page.save(update_fields=["parent"])
- unarchive_archive_page_and_descendants(page_id, None)
+ unarchive_archive_page_and_descendants(pk, None)
return Response(status=status.HTTP_204_NO_CONTENT)
- def archive_list(self, request, slug, project_id):
- pages = Page.objects.filter(
- project_id=project_id,
- workspace__slug=slug,
- ).filter(archived_at__isnull=False)
-
- pages = PageSerializer(pages, many=True).data
- return Response(pages, status=status.HTTP_200_OK)
-
def destroy(self, request, slug, project_id, pk):
page = Page.objects.get(
pk=pk, workspace__slug=slug, project_id=project_id
@@ -269,29 +296,20 @@ class PageFavoriteViewSet(BaseViewSet):
serializer_class = PageFavoriteSerializer
model = PageFavorite
- def get_queryset(self):
- return self.filter_queryset(
- super()
- .get_queryset()
- .filter(archived_at__isnull=True)
- .filter(workspace__slug=self.kwargs.get("slug"))
- .filter(user=self.request.user)
- .select_related("page", "page__owned_by")
+ def create(self, request, slug, project_id, pk):
+ _ = PageFavorite.objects.create(
+ project_id=project_id,
+ page_id=pk,
+ user=request.user,
)
+ return Response(status=status.HTTP_204_NO_CONTENT)
- def create(self, request, slug, project_id):
- serializer = PageFavoriteSerializer(data=request.data)
- if serializer.is_valid():
- serializer.save(user=request.user, project_id=project_id)
- return Response(serializer.data, status=status.HTTP_201_CREATED)
- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
-
- def destroy(self, request, slug, project_id, page_id):
+ def destroy(self, request, slug, project_id, pk):
page_favorite = PageFavorite.objects.get(
project=project_id,
user=request.user,
workspace__slug=slug,
- page_id=page_id,
+ page_id=pk,
)
page_favorite.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/apiserver/plane/app/views/state/base.py b/apiserver/plane/app/views/state/base.py
index 06f118c318..b488d9efb7 100644
--- a/apiserver/plane/app/views/state/base.py
+++ b/apiserver/plane/app/views/state/base.py
@@ -14,6 +14,7 @@ from plane.app.permissions import (
from plane.db.models import State, Issue
from plane.utils.cache import invalidate_cache
+
class StateViewSet(BaseViewSet):
serializer_class = StateSerializer
model = State
@@ -38,7 +39,9 @@ class StateViewSet(BaseViewSet):
.distinct()
)
- @invalidate_cache(path="workspaces/:slug/states/", url_params=True, user=False)
+ @invalidate_cache(
+ path="workspaces/:slug/states/", url_params=True, user=False
+ )
def create(self, request, slug, project_id):
serializer = StateSerializer(data=request.data)
if serializer.is_valid():
@@ -59,7 +62,9 @@ class StateViewSet(BaseViewSet):
return Response(state_dict, status=status.HTTP_200_OK)
return Response(states, status=status.HTTP_200_OK)
- @invalidate_cache(path="workspaces/:slug/states/", url_params=True, user=False)
+ @invalidate_cache(
+ path="workspaces/:slug/states/", url_params=True, user=False
+ )
def mark_as_default(self, request, slug, project_id, pk):
# Select all the states which are marked as default
_ = State.objects.filter(
@@ -70,7 +75,9 @@ class StateViewSet(BaseViewSet):
).update(default=True)
return Response(status=status.HTTP_204_NO_CONTENT)
- @invalidate_cache(path="workspaces/:slug/states/", url_params=True, user=False)
+ @invalidate_cache(
+ path="workspaces/:slug/states/", url_params=True, user=False
+ )
def destroy(self, request, slug, project_id, pk):
state = State.objects.get(
is_triage=False,
diff --git a/apiserver/plane/app/views/view/base.py b/apiserver/plane/app/views/view/base.py
index 45e7bd29cf..35772ccf3b 100644
--- a/apiserver/plane/app/views/view/base.py
+++ b/apiserver/plane/app/views/view/base.py
@@ -326,11 +326,11 @@ class IssueViewFavoriteViewSet(BaseViewSet):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def destroy(self, request, slug, project_id, view_id):
- view_favourite = IssueViewFavorite.objects.get(
+ view_favorite = IssueViewFavorite.objects.get(
project=project_id,
user=request.user,
workspace__slug=slug,
view_id=view_id,
)
- view_favourite.delete()
+ view_favorite.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
diff --git a/apiserver/plane/bgtasks/page_transaction_task.py b/apiserver/plane/bgtasks/page_transaction_task.py
new file mode 100644
index 0000000000..57f4f644e4
--- /dev/null
+++ b/apiserver/plane/bgtasks/page_transaction_task.py
@@ -0,0 +1,76 @@
+# Python imports
+import json
+
+# Django imports
+from django.utils import timezone
+
+# Third-party imports
+from bs4 import BeautifulSoup
+
+# Module imports
+from plane.db.models import Page, PageLog
+from celery import shared_task
+
+
+def extract_components(value, tag):
+ try:
+ mentions = []
+ html = value.get("description_html")
+ soup = BeautifulSoup(html, "html.parser")
+ mention_tags = soup.find_all(tag)
+
+ for mention_tag in mention_tags:
+ mention = {
+ "id": mention_tag.get("id"),
+ "entity_identifier": mention_tag.get("entity_identifier"),
+ "entity_name": mention_tag.get("entity_name"),
+ }
+ mentions.append(mention)
+
+ return mentions
+ except Exception:
+ return []
+
+
+@shared_task
+def page_transaction(new_value, old_value, page_id):
+ page = Page.objects.get(pk=page_id)
+ new_page_mention = PageLog.objects.filter(page_id=page_id).exists()
+
+ old_value = json.loads(old_value)
+
+ new_transactions = []
+ deleted_transaction_ids = set()
+
+ # TODO - Add "issue-embed-component", "img", "todo" components
+ components = ["mention-component"]
+ for component in components:
+ old_mentions = extract_components(old_value, component)
+ new_mentions = extract_components(new_value, component)
+
+ new_mentions_ids = {mention["id"] for mention in new_mentions}
+ old_mention_ids = {mention["id"] for mention in old_mentions}
+ deleted_transaction_ids.update(old_mention_ids - new_mentions_ids)
+
+ new_transactions.extend(
+ PageLog(
+ transaction=mention["id"],
+ page_id=page_id,
+ entity_identifier=mention["entity_identifier"],
+ entity_name=mention["entity_name"],
+ workspace_id=page.workspace_id,
+ project_id=page.project_id,
+ created_at=timezone.now(),
+ updated_at=timezone.now(),
+ )
+ for mention in new_mentions
+ if mention["id"] not in old_mention_ids or not new_page_mention
+ )
+
+ # Create new PageLog objects for new transactions
+ PageLog.objects.bulk_create(new_transactions, batch_size=10, ignore_conflicts=True)
+
+ # Delete the removed transactions
+ PageLog.objects.filter(
+ transaction__in=deleted_transaction_ids
+ ).delete()
diff --git a/apiserver/plane/db/migrations/0064_auto_20240409_1134.py b/apiserver/plane/db/migrations/0064_auto_20240409_1134.py
new file mode 100644
index 0000000000..53e5938af1
--- /dev/null
+++ b/apiserver/plane/db/migrations/0064_auto_20240409_1134.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.10 on 2024-04-09 11:34
+
+from django.db import migrations, models
+import plane.db.models.page
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('db', '0063_state_is_triage_alter_state_group'),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="page",
+ name="view_props",
+ field=models.JSONField(
+ default=plane.db.models.page.get_view_props
+ ),
+ ),
+ ]
diff --git a/apiserver/plane/db/models/page.py b/apiserver/plane/db/models/page.py
index 6ed94798a2..da7e050bbf 100644
--- a/apiserver/plane/db/models/page.py
+++ b/apiserver/plane/db/models/page.py
@@ -9,6 +9,10 @@ from . import ProjectBaseModel
from plane.utils.html_processor import strip_tags
+def get_view_props():
+ return {"full_width": False}
+
+
class Page(ProjectBaseModel):
name = models.CharField(max_length=255)
description = models.JSONField(default=dict, blank=True)
@@ -35,6 +39,7 @@ class Page(ProjectBaseModel):
)
archived_at = models.DateField(null=True)
is_locked = models.BooleanField(default=False)
+ view_props = models.JSONField(default=get_view_props)
class Meta:
verbose_name = "Page"
@@ -81,7 +86,7 @@ class PageLog(ProjectBaseModel):
ordering = ("-created_at",)
def __str__(self):
- return f"{self.page.name} {self.type}"
+ return f"{self.page.name} {self.entity_name}"
class PageBlock(ProjectBaseModel):
diff --git a/packages/editor/core/package.json b/packages/editor/core/package.json
index a0d7351d30..2657d1c7a7 100644
--- a/packages/editor/core/package.json
+++ b/packages/editor/core/package.json
@@ -28,6 +28,7 @@
"react-dom": "18.2.0"
},
"dependencies": {
+ "@plane/ui": "*",
"@tiptap/core": "^2.1.13",
"@tiptap/extension-blockquote": "^2.1.13",
"@tiptap/extension-code-block-lowlight": "^2.1.13",
@@ -39,6 +40,7 @@
"@tiptap/extension-task-list": "^2.1.13",
"@tiptap/extension-text-style": "^2.1.13",
"@tiptap/extension-underline": "^2.1.13",
+ "prosemirror-codemark": "^0.4.2",
"@tiptap/pm": "^2.1.13",
"@tiptap/react": "^2.1.13",
"@tiptap/starter-kit": "^2.1.13",
diff --git a/packages/editor/core/src/helpers/scroll-to-node.ts b/packages/editor/core/src/helpers/scroll-to-node.ts
new file mode 100644
index 0000000000..65d32a7d21
--- /dev/null
+++ b/packages/editor/core/src/helpers/scroll-to-node.ts
@@ -0,0 +1,40 @@
+import { Editor } from "@tiptap/react";
+
+export interface IMarking {
+ type: "heading";
+ level: number;
+ text: string;
+ sequence: number;
+}
+
+function findNthH1(editor: Editor, n: number, level: number): number {
+ let count = 0;
+ let pos = 0;
+ editor.state.doc.descendants((node, position) => {
+ if (node.type.name === "heading" && node.attrs.level === level) {
+ count++;
+ if (count === n) {
+ pos = position;
+ return false;
+ }
+ }
+ });
+ return pos;
+}
+
+function scrollToNode(editor: Editor, pos: number): void {
+ const headingNode = editor.state.doc.nodeAt(pos);
+ if (headingNode) {
+ const headingDOM = editor.view.nodeDOM(pos);
+ if (headingDOM instanceof HTMLElement) {
+ headingDOM.scrollIntoView({ behavior: "smooth" });
+ }
+ }
+}
+
+export function scrollSummary(editor: Editor, marking: IMarking) {
+ if (editor) {
+ const pos = findNthH1(editor, marking.sequence, marking.level);
+ scrollToNode(editor, pos);
+ }
+}
diff --git a/packages/editor/core/src/hooks/use-editor.tsx b/packages/editor/core/src/hooks/use-editor.tsx
index 7e6aa5912a..493071a365 100644
--- a/packages/editor/core/src/hooks/use-editor.tsx
+++ b/packages/editor/core/src/hooks/use-editor.tsx
@@ -1,111 +1,178 @@
import { useEditor as useCustomEditor, Editor } from "@tiptap/react";
-import { useImperativeHandle, useRef, MutableRefObject, useState } from "react";
+import { useImperativeHandle, useRef, MutableRefObject, useState, useEffect } from "react";
import { CoreEditorProps } from "src/ui/props";
import { CoreEditorExtensions } from "src/ui/extensions";
import { EditorProps } from "@tiptap/pm/view";
import { getTrimmedHTML } from "src/lib/utils";
import { DeleteImage } from "src/types/delete-image";
-import { IMentionSuggestion } from "src/types/mention-suggestion";
+import { IMentionHighlight, IMentionSuggestion } from "src/types/mention-suggestion";
import { RestoreImage } from "src/types/restore-image";
import { UploadImage } from "src/types/upload-image";
import { Selection } from "@tiptap/pm/state";
import { insertContentAtSavedSelection } from "src/helpers/insert-content-at-cursor-position";
+import { EditorMenuItemNames, getEditorMenuItems } from "src/ui/menus/menu-items";
+import { EditorRefApi } from "src/types/editor-ref-api";
+import { IMarking, scrollSummary } from "src/helpers/scroll-to-node";
interface CustomEditorProps {
+ id?: string;
uploadFile: UploadImage;
restoreFile: RestoreImage;
- rerenderOnPropsChange?: {
- id: string;
- description_html: string;
- };
deleteFile: DeleteImage;
cancelUploadImage?: () => any;
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
- setShouldShowAlert?: (showAlert: boolean) => void;
- value: string;
- debouncedUpdatesEnabled?: boolean;
- onStart?: (json: any, html: string) => void;
- onChange?: (json: any, html: string) => void;
+ initialValue: string;
+ editorClassName: string;
+ // undefined when prop is not passed, null if intentionally passed to stop
+ // swr syncing
+ value: string | null | undefined;
+ onChange?: (json: object, html: string) => void;
extensions?: any;
editorProps?: EditorProps;
- forwardedRef?: any;
- mentionHighlights?: string[];
- mentionSuggestions?: IMentionSuggestion[];
+ forwardedRef?: MutableRefObject<EditorRefApi | null>;
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
+ suggestions?: () => Promise<IMentionSuggestion[]>;
+ };
+ handleEditorReady?: (value: boolean) => void;
}
export const useEditor = ({
uploadFile,
+ id = "",
deleteFile,
cancelUploadImage,
editorProps = {},
+ initialValue,
+ editorClassName,
value,
- rerenderOnPropsChange,
extensions = [],
- onStart,
onChange,
- setIsSubmitting,
forwardedRef,
restoreFile,
- setShouldShowAlert,
- mentionHighlights,
- mentionSuggestions,
+ handleEditorReady,
+ mentionHandler,
}: CustomEditorProps) => {
- const editor = useCustomEditor(
- {
- editorProps: {
- ...CoreEditorProps(uploadFile, setIsSubmitting),
- ...editorProps,
- },
- extensions: [
- ...CoreEditorExtensions(
- {
- mentionSuggestions: mentionSuggestions ?? [],
- mentionHighlights: mentionHighlights ?? [],
- },
- deleteFile,
- restoreFile,
- cancelUploadImage
- ),
- ...extensions,
- ],
- content: typeof value === "string" && value.trim() !== "" ? value : "<p></p>",
- onCreate: async ({ editor }) => {
- onStart?.(editor.getJSON(), getTrimmedHTML(editor.getHTML()));
- },
- onTransaction: async ({ editor }) => {
- setSavedSelection(editor.state.selection);
- },
- onUpdate: async ({ editor }) => {
- setIsSubmitting?.("submitting");
- setShouldShowAlert?.(true);
- onChange?.(editor.getJSON(), getTrimmedHTML(editor.getHTML()));
- },
+ const editor = useCustomEditor({
+ editorProps: {
+ ...CoreEditorProps(uploadFile, editorClassName),
+ ...editorProps,
},
- [rerenderOnPropsChange]
- );
+ extensions: [
+ ...CoreEditorExtensions(
+ {
+ mentionSuggestions: mentionHandler.suggestions ?? (() => Promise.resolve<IMentionSuggestion[]>([])),
+ mentionHighlights: mentionHandler.highlights ?? [],
+ },
+ deleteFile,
+ restoreFile,
+ cancelUploadImage
+ ),
+ ...extensions,
+ ],
+ content: typeof initialValue === "string" && initialValue.trim() !== "" ? initialValue : "<p></p>",
+ onCreate: async () => {
+ handleEditorReady?.(true);
+ },
+ onTransaction: async ({ editor }) => {
+ setSavedSelection(editor.state.selection);
+ },
+ onUpdate: async ({ editor }) => {
+ onChange?.(editor.getJSON(), getTrimmedHTML(editor.getHTML()));
+ },
+ onDestroy: async () => {
+ handleEditorReady?.(false);
+ },
+ });
+
+ // for syncing swr data on tab refocus etc, can remove it once this is merged
+ // https://github.com/ueberdosis/tiptap/pull/4453
+ useEffect(() => {
+ // value is null when intentionally passed where syncing is not yet
+ // supported and value is undefined when the data from swr is not populated
+ if (value === null || value === undefined) return;
+ if (editor && !editor.isDestroyed) editor?.commands.setContent(value);
+ }, [editor, value, id]);
const editorRef: MutableRefObject<Editor | null> = useRef(null);
- editorRef.current = editor;
const [savedSelection, setSavedSelection] = useState<Selection | null>(null);
- useImperativeHandle(forwardedRef, () => ({
- clearEditor: () => {
- editorRef.current?.commands.clearContent();
- },
- setEditorValue: (content: string) => {
- editorRef.current?.commands.setContent(content);
- },
- setEditorValueAtCursorPosition: (content: string) => {
- if (savedSelection) {
- insertContentAtSavedSelection(editorRef, content, savedSelection);
- }
- },
- }));
+ useImperativeHandle(
+ forwardedRef,
+ () => ({
+ clearEditor: () => {
+ editorRef.current?.commands.clearContent();
+ },
+ setEditorValue: (content: string) => {
+ editorRef.current?.commands.setContent(content);
+ },
+ setEditorValueAtCursorPosition: (content: string) => {
+ if (savedSelection) {
+ insertContentAtSavedSelection(editorRef, content, savedSelection);
+ }
+ },
+ executeMenuItemCommand: (itemName: EditorMenuItemNames) => {
+ const editorItems = getEditorMenuItems(editorRef.current, uploadFile);
+
+ const getEditorMenuItem = (itemName: EditorMenuItemNames) => editorItems.find((item) => item.name === itemName);
+
+ const item = getEditorMenuItem(itemName);
+ if (item) {
+ if (item.name === "image") {
+ item.command(savedSelection);
+ } else {
+ item.command();
+ }
+ } else {
+ console.warn(`No command found for item: ${itemName}`);
+ }
+ },
+ isMenuItemActive: (itemName: EditorMenuItemNames): boolean => {
+ const editorItems = getEditorMenuItems(editorRef.current, uploadFile);
+
+ const getEditorMenuItem = (itemName: EditorMenuItemNames) => editorItems.find((item) => item.name === itemName);
+ const item = getEditorMenuItem(itemName);
+ return item ? item.isActive() : false;
+ },
+ onStateChange: (callback: () => void) => {
+ // Subscribe to editor state changes
+ editorRef.current?.on("transaction", () => {
+ callback();
+ });
+ // Return a function to unsubscribe to the continuous transactions of
+ // the editor on unmounting the component that has subscribed to this
+ // method
+ return () => {
+ editorRef.current?.off("transaction");
+ };
+ },
+ getMarkDown: (): string => {
+ const markdownOutput = editorRef.current?.storage.markdown.getMarkdown();
+ return markdownOutput;
+ },
+ scrollSummary: (marking: IMarking): void => {
+ if (!editorRef.current) return;
+ scrollSummary(editorRef.current, marking);
+ },
+ setFocusAtPosition: (position: number) => {
+ if (!editorRef.current) return;
+ editorRef.current
+ .chain()
+ .insertContentAt(position, [{ type: "paragraph" }])
+ .focus()
+ .run();
+ },
+ }),
+ [editorRef, savedSelection, uploadFile]
+ );
if (!editor) {
return null;
}
+ // the editorRef is used to access the editor instance from outside the hook
+ // and should only be used after editor is initialized
+ editorRef.current = editor;
+
return editor;
};
diff --git a/packages/editor/core/src/hooks/use-read-only-editor.tsx b/packages/editor/core/src/hooks/use-read-only-editor.tsx
index ecd49255ca..9607586d8e 100644
--- a/packages/editor/core/src/hooks/use-read-only-editor.tsx
+++ b/packages/editor/core/src/hooks/use-read-only-editor.tsx
@@ -1,53 +1,61 @@
import { useEditor as useCustomEditor, Editor } from "@tiptap/react";
-import { useImperativeHandle, useRef, MutableRefObject } from "react";
+import { useImperativeHandle, useRef, MutableRefObject, useEffect } from "react";
import { CoreReadOnlyEditorExtensions } from "src/ui/read-only/extensions";
import { CoreReadOnlyEditorProps } from "src/ui/read-only/props";
import { EditorProps } from "@tiptap/pm/view";
-import { IMentionSuggestion } from "src/types/mention-suggestion";
+import { EditorReadOnlyRefApi } from "src/types/editor-ref-api";
+import { IMarking, scrollSummary } from "src/helpers/scroll-to-node";
+import { IMentionHighlight } from "src/types/mention-suggestion";
interface CustomReadOnlyEditorProps {
- value: string;
- forwardedRef?: any;
+ initialValue: string;
+ editorClassName: string;
+ forwardedRef?: MutableRefObject<EditorReadOnlyRefApi | null>;
extensions?: any;
editorProps?: EditorProps;
- rerenderOnPropsChange?: {
- id: string;
- description_html: string;
+ handleEditorReady?: (value: boolean) => void;
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
};
- mentionHighlights?: string[];
- mentionSuggestions?: IMentionSuggestion[];
}
export const useReadOnlyEditor = ({
- value,
+ initialValue,
+ editorClassName,
forwardedRef,
extensions = [],
editorProps = {},
- rerenderOnPropsChange,
- mentionHighlights,
- mentionSuggestions,
+ handleEditorReady,
+ mentionHandler,
}: CustomReadOnlyEditorProps) => {
- const editor = useCustomEditor(
- {
- editable: false,
- content: typeof value === "string" && value.trim() !== "" ? value : "<p></p>",
- editorProps: {
- ...CoreReadOnlyEditorProps,
- ...editorProps,
- },
- extensions: [
- ...CoreReadOnlyEditorExtensions({
- mentionSuggestions: mentionSuggestions ?? [],
- mentionHighlights: mentionHighlights ?? [],
- }),
- ...extensions,
- ],
+ const editor = useCustomEditor({
+ editable: false,
+ content: typeof initialValue === "string" && initialValue.trim() !== "" ? initialValue : "<p></p>",
+ editorProps: {
+ ...CoreReadOnlyEditorProps(editorClassName),
+ ...editorProps,
},
- [rerenderOnPropsChange]
- );
+ onCreate: async () => {
+ handleEditorReady?.(true);
+ },
+ extensions: [
+ ...CoreReadOnlyEditorExtensions({
+ mentionHighlights: mentionHandler.highlights,
+ }),
+ ...extensions,
+ ],
+ onDestroy: () => {
+ handleEditorReady?.(false);
+ },
+ });
+
+ // for syncing swr data on tab refocus etc
+ useEffect(() => {
+ if (initialValue === null || initialValue === undefined) return;
+ if (editor && !editor.isDestroyed) editor?.commands.setContent(initialValue);
+ }, [editor, initialValue]);
const editorRef: MutableRefObject<Editor | null> = useRef(null);
- editorRef.current = editor;
useImperativeHandle(forwardedRef, () => ({
clearEditor: () => {
@@ -56,11 +64,20 @@ export const useReadOnlyEditor = ({
setEditorValue: (content: string) => {
editorRef.current?.commands.setContent(content);
},
+ getMarkDown: (): string => {
+ const markdownOutput = editorRef.current?.storage.markdown.getMarkdown();
+ return markdownOutput;
+ },
+ scrollSummary: (marking: IMarking): void => {
+ if (!editorRef.current) return;
+ scrollSummary(editorRef.current, marking);
+ },
}));
if (!editor) {
return null;
}
+ editorRef.current = editor;
return editor;
};
diff --git a/packages/editor/core/src/index.ts b/packages/editor/core/src/index.ts
index c7e39d240a..336daed436 100644
--- a/packages/editor/core/src/index.ts
+++ b/packages/editor/core/src/index.ts
@@ -26,6 +26,7 @@ export * from "src/lib/editor-commands";
// types
export type { DeleteImage } from "src/types/delete-image";
export type { UploadImage } from "src/types/upload-image";
+export type { EditorRefApi, EditorReadOnlyRefApi } from "src/types/editor-ref-api";
export type { RestoreImage } from "src/types/restore-image";
export type { IMentionHighlight, IMentionSuggestion } from "src/types/mention-suggestion";
export type { ISlashCommandItem, CommandProps } from "src/types/slash-commands-suggestion";
diff --git a/packages/editor/core/src/lib/editor-commands.ts b/packages/editor/core/src/lib/editor-commands.ts
index 7c3e7f11e6..e163b17dd5 100644
--- a/packages/editor/core/src/lib/editor-commands.ts
+++ b/packages/editor/core/src/lib/editor-commands.ts
@@ -1,21 +1,22 @@
import { Editor, Range } from "@tiptap/core";
import { startImageUpload } from "src/ui/plugins/upload-image";
import { findTableAncestor } from "src/lib/utils";
+import { Selection } from "@tiptap/pm/state";
import { UploadImage } from "src/types/upload-image";
export const toggleHeadingOne = (editor: Editor, range?: Range) => {
- if (range) editor.chain().focus().deleteRange(range).clearNodes().setNode("heading", { level: 1 }).run();
- else editor.chain().focus().clearNodes().toggleHeading({ level: 1 }).run();
+ if (range) editor.chain().focus().deleteRange(range).setNode("heading", { level: 1 }).run();
+ else editor.chain().focus().toggleHeading({ level: 1 }).run();
};
export const toggleHeadingTwo = (editor: Editor, range?: Range) => {
- if (range) editor.chain().focus().deleteRange(range).clearNodes().setNode("heading", { level: 2 }).run();
- else editor.chain().focus().clearNodes().toggleHeading({ level: 2 }).run();
+ if (range) editor.chain().focus().deleteRange(range).setNode("heading", { level: 2 }).run();
+ else editor.chain().focus().toggleHeading({ level: 2 }).run();
};
export const toggleHeadingThree = (editor: Editor, range?: Range) => {
- if (range) editor.chain().focus().deleteRange(range).clearNodes().setNode("heading", { level: 3 }).run();
- else editor.chain().focus().clearNodes().toggleHeading({ level: 3 }).run();
+ if (range) editor.chain().focus().deleteRange(range).setNode("heading", { level: 3 }).run();
+ else editor.chain().focus().toggleHeading({ level: 3 }).run();
};
export const toggleBold = (editor: Editor, range?: Range) => {
@@ -37,10 +38,10 @@ export const toggleCodeBlock = (editor: Editor, range?: Range) => {
// Check if code block is active then toggle code block
if (editor.isActive("codeBlock")) {
if (range) {
- editor.chain().focus().deleteRange(range).clearNodes().toggleCodeBlock().run();
+ editor.chain().focus().deleteRange(range).toggleCodeBlock().run();
return;
}
- editor.chain().focus().clearNodes().toggleCodeBlock().run();
+ editor.chain().focus().toggleCodeBlock().run();
return;
}
@@ -49,32 +50,32 @@ export const toggleCodeBlock = (editor: Editor, range?: Range) => {
if (isSelectionEmpty) {
if (range) {
- editor.chain().focus().deleteRange(range).clearNodes().toggleCodeBlock().run();
+ editor.chain().focus().deleteRange(range).toggleCodeBlock().run();
return;
}
- editor.chain().focus().clearNodes().toggleCodeBlock().run();
+ editor.chain().focus().toggleCodeBlock().run();
} else {
if (range) {
- editor.chain().focus().deleteRange(range).clearNodes().toggleCode().run();
+ editor.chain().focus().deleteRange(range).toggleCode().run();
return;
}
- editor.chain().focus().clearNodes().toggleCode().run();
+ editor.chain().focus().toggleCode().run();
}
};
export const toggleOrderedList = (editor: Editor, range?: Range) => {
- if (range) editor.chain().focus().deleteRange(range).clearNodes().toggleOrderedList().run();
- else editor.chain().focus().clearNodes().toggleOrderedList().run();
+ if (range) editor.chain().focus().deleteRange(range).toggleOrderedList().run();
+ else editor.chain().focus().toggleOrderedList().run();
};
export const toggleBulletList = (editor: Editor, range?: Range) => {
- if (range) editor.chain().focus().deleteRange(range).clearNodes().toggleBulletList().run();
- else editor.chain().focus().clearNodes().toggleBulletList().run();
+ if (range) editor.chain().focus().deleteRange(range).toggleBulletList().run();
+ else editor.chain().focus().toggleBulletList().run();
};
export const toggleTaskList = (editor: Editor, range?: Range) => {
- if (range) editor.chain().focus().deleteRange(range).clearNodes().toggleTaskList().run();
- else editor.chain().focus().clearNodes().toggleTaskList().run();
+ if (range) editor.chain().focus().deleteRange(range).toggleTaskList().run();
+ else editor.chain().focus().toggleTaskList().run();
};
export const toggleStrike = (editor: Editor, range?: Range) => {
@@ -83,17 +84,19 @@ export const toggleStrike = (editor: Editor, range?: Range) => {
};
export const toggleBlockquote = (editor: Editor, range?: Range) => {
- if (range) editor.chain().focus().deleteRange(range).clearNodes().toggleBlockquote().run();
- else editor.chain().focus().clearNodes().toggleBlockquote().run();
+ if (range) editor.chain().focus().deleteRange(range).toggleBlockquote().run();
+ else editor.chain().focus().toggleBlockquote().run();
};
export const insertTableCommand = (editor: Editor, range?: Range) => {
if (typeof window !== "undefined") {
- const selection: any = window?.getSelection();
- if (selection.rangeCount !== 0) {
- const range = selection.getRangeAt(0);
- if (findTableAncestor(range.startContainer)) {
- return;
+ const selection = window.getSelection();
+ if (selection) {
+ if (selection.rangeCount !== 0) {
+ const range = selection.getRangeAt(0);
+ if (findTableAncestor(range.startContainer)) {
+ return;
+ }
}
}
}
@@ -112,7 +115,7 @@ export const setLinkEditor = (editor: Editor, url: string) => {
export const insertImageCommand = (
editor: Editor,
uploadFile: UploadImage,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void,
+ savedSelection?: Selection | null,
range?: Range
) => {
if (range) editor.chain().focus().deleteRange(range).run();
@@ -122,8 +125,8 @@ export const insertImageCommand = (
input.onchange = async () => {
if (input.files?.length) {
const file = input.files[0];
- const pos = editor.view.state.selection.from;
- startImageUpload(file, editor.view, pos, uploadFile, setIsSubmitting);
+ const pos = savedSelection?.anchor ?? editor.view.state.selection.from;
+ startImageUpload(file, editor.view, pos, uploadFile);
}
};
input.click();
diff --git a/packages/editor/core/src/lib/utils.ts b/packages/editor/core/src/lib/utils.ts
index c943d4c604..84ad7046ee 100644
--- a/packages/editor/core/src/lib/utils.ts
+++ b/packages/editor/core/src/lib/utils.ts
@@ -4,15 +4,17 @@ import { twMerge } from "tailwind-merge";
interface EditorClassNames {
noBorder?: boolean;
borderOnFocus?: boolean;
- customClassName?: string;
+ containerClassName?: string;
}
-export const getEditorClassNames = ({ noBorder, borderOnFocus, customClassName }: EditorClassNames) =>
+export const getEditorClassNames = ({ noBorder, borderOnFocus, containerClassName }: EditorClassNames) =>
cn(
- "relative w-full max-w-full sm:rounded-lg mt-2 p-3 relative focus:outline-none rounded-md",
- noBorder ? "" : "border border-custom-border-200",
- borderOnFocus ? "focus:border border-custom-border-300" : "focus:border-0",
- customClassName
+ "w-full max-w-full sm:rounded-lg focus:outline-none focus:border-0",
+ {
+ "border border-custom-border-200": !noBorder,
+ "focus:border border-custom-border-300": borderOnFocus,
+ },
+ containerClassName
);
export function cn(...inputs: ClassValue[]) {
diff --git a/packages/editor/core/src/styles/editor.css b/packages/editor/core/src/styles/editor.css
index dbbea671eb..63bc5a6d6c 100644
--- a/packages/editor/core/src/styles/editor.css
+++ b/packages/editor/core/src/styles/editor.css
@@ -7,10 +7,17 @@
}
/* block quotes */
+.ProseMirror blockquote {
+ font-style: normal;
+ font-weight: 400;
+ border-left: 3px solid rgb(var(--color-border-300));
+}
+
.ProseMirror blockquote p::before,
.ProseMirror blockquote p::after {
display: none;
}
+/* end block quotes */
.ProseMirror code::before,
.ProseMirror code::after {
@@ -28,8 +35,8 @@
/* Custom image styles */
.ProseMirror img {
transition: filter 0.1s ease-in-out;
- margin-top: 0 !important;
- margin-bottom: 0 !important;
+ margin-top: 8px;
+ margin-bottom: 0;
&:hover {
cursor: pointer;
@@ -37,22 +44,52 @@
}
&.ProseMirror-selectednode {
- outline: 3px solid #5abbf7;
+ outline: 3px solid rgba(var(--color-primary-100));
filter: brightness(90%);
}
}
-.ProseMirror-gapcursor:after {
+/* Custom list item styles */
+
+/* Custom gap cursor styles */
+.ProseMirror-gapcursor::after {
border-top: 1px solid rgb(var(--color-text-100)) !important;
}
/* Custom TODO list checkboxes – shoutout to this awesome tutorial: https://moderncss.dev/pure-css-custom-checkbox-style/ */
+ul[data-type="taskList"] li {
+ font-size: 1rem;
+ line-height: 1.5;
+}
+
ul[data-type="taskList"] li > label {
- margin-right: 0.2rem;
+ margin: 0.1rem 0.15rem 0 0;
user-select: none;
}
+ul[data-type="taskList"] li > label input[type="checkbox"] {
+ border: 1px solid rgba(var(--color-border-300)) !important;
+ outline: none;
+ border-radius: 2px;
+ transform: scale(1.05);
+}
+
+ul[data-type="taskList"] li > label input[type="checkbox"]:hover {
+ background-color: rgba(var(--color-background-80)) !important;
+}
+
+ul[data-type="taskList"] li > label input[type="checkbox"]:checked {
+ background-color: rgba(var(--color-primary-100)) !important;
+ border-color: rgba(var(--color-primary-100)) !important;
+ color: white !important;
+}
+
+ul[data-type="taskList"] li > label input[type="checkbox"]:checked:hover {
+ background-color: rgba(var(--color-primary-300)) !important;
+ border-color: rgba(var(--color-primary-300)) !important;
+}
+
@media screen and (max-width: 768px) {
ul[data-type="taskList"] li > label {
margin-right: 0.5rem;
@@ -60,6 +97,7 @@ ul[data-type="taskList"] li > label {
}
ul[data-type="taskList"] li > label input[type="checkbox"] {
+ position: relative;
-webkit-appearance: none;
appearance: none;
background-color: rgb(var(--color-background-100));
@@ -71,8 +109,6 @@ ul[data-type="taskList"] li > label input[type="checkbox"] {
border: 1.5px solid rgb(var(--color-text-100));
margin-right: 0.2rem;
margin-top: 0.15rem;
- display: grid;
- place-content: center;
&:hover {
background-color: rgb(var(--color-background-80));
@@ -82,24 +118,28 @@ ul[data-type="taskList"] li > label input[type="checkbox"] {
background-color: rgb(var(--color-background-90));
}
+ /* check sign */
&::before {
content: "";
+ position: absolute;
+ top: 50%;
+ left: 50%;
width: 0.5em;
height: 0.5em;
transform: scale(0);
+ transform-origin: center;
transition: 120ms transform ease-in-out;
box-shadow: inset 1em 1em;
- transform-origin: center;
clip-path: polygon(14% 44%, 0 65%, 50% 100%, 100% 16%, 80% 0%, 43% 62%);
}
&:checked::before {
- transform: scale(1);
+ transform: scale(1) translate(-50%, -50%);
}
}
ul[data-type="taskList"] li[data-checked="true"] > div > p {
- color: rgb(var(--color-text-200));
+ color: rgb(var(--color-text-400));
text-decoration: line-through;
text-decoration-thickness: 2px;
}
@@ -133,12 +173,12 @@ ul[data-type="taskList"] li[data-checked="true"] > div > p {
-moz-appearance: textfield;
}
-.fadeIn {
+.fade-in {
opacity: 1;
transition: opacity 0.3s ease-in;
}
-.fadeOut {
+.fade-out {
opacity: 0;
transition: opacity 0.2s ease-out;
}
@@ -149,7 +189,7 @@ ul[data-type="taskList"] li[data-checked="true"] > div > p {
margin-top: 0 !important;
margin-bottom: 0 !important;
- &:before {
+ &::before {
content: "";
box-sizing: border-box;
position: absolute;
@@ -175,21 +215,13 @@ ul[data-type="taskList"] li[data-checked="true"] > div > p {
cursor: col-resize;
}
-.ProseMirror table * p {
- padding: 0px 1px;
- margin: 6px 2px;
-}
-
.ProseMirror table * .is-empty::before {
opacity: 0;
}
.ProseMirror pre {
- background: rgba(var(--color-background-80));
- border-radius: 0.5rem;
- color: rgba(var(--color-text-100));
- font-family: "JetBrainsMono", monospace;
- padding: 0.75rem 1rem;
+ font-family: JetBrainsMono, monospace;
+ tab-size: 2;
}
.ProseMirror pre code {
@@ -214,3 +246,107 @@ div[data-type="horizontalRule"] {
.moveable-control-box {
z-index: 10 !important;
}
+
+/* Cursor styles for the inline code blocks */
+@keyframes blink {
+ 49% {
+ border-color: unset;
+ }
+
+ 50% {
+ border-color: transparent;
+ }
+
+ 99% {
+ border-color: transparent;
+ }
+}
+
+.no-cursor {
+ caret-color: transparent;
+}
+
+div:focus .fake-cursor,
+span:focus .fake-cursor {
+ margin-right: -1px;
+ border-left-width: 1.5px;
+ border-left-style: solid;
+ animation: blink 1s;
+ animation-iteration-count: infinite;
+ position: relative;
+ z-index: 1;
+}
+
+/* number, bulleted and to-do lists */
+.prose ol:where(.prose > :first-child):not(:where([class~="not-prose"], [class~="not-prose"] *)),
+.prose
+ ul:not([data-type="taskList"]):where(.prose > :first-child):not(:where([class~="not-prose"], [class~="not-prose"] *)),
+.prose ul[data-type="taskList"]:where(.prose > :first-child) {
+ margin-top: 0.25rem !important;
+ margin-bottom: 1px !important;
+}
+
+.prose ol:not(:where(.prose > :first-child):not(:where([class~="not-prose"], [class~="not-prose"] *))),
+.prose
+ ul:not([data-type="taskList"]):not(
+ :where(.prose > :first-child):not(:where([class~="not-prose"], [class~="not-prose"] *))
+ ),
+.prose ul[data-type="taskList"]:not(:where(.prose > :first-child)) {
+ margin-top: calc(0.25rem + 3px) !important;
+ margin-bottom: 1px !important;
+}
+
+ol ol,
+ol ul:not([data-type="taskList"]),
+ul:not([data-type="taskList"]) ul:not([data-type="taskList"]),
+ul:not([data-type="taskList"]) ol {
+ margin-top: 0.45rem !important;
+}
+
+ul[data-type="taskList"] ul[data-type="taskList"] {
+ margin-top: 0.6rem;
+}
+/* end number, bulleted and to-do lists */
+
+/* tailwind typography */
+.prose :where(h1):not(:where([class~="not-prose"], [class~="not-prose"] *)) {
+ margin-top: 2rem;
+ margin-bottom: 4px;
+ font-size: 1.875rem;
+ font-weight: 700;
+ line-height: 1.3;
+}
+
+.prose :where(h2):not(:where([class~="not-prose"], [class~="not-prose"] *)) {
+ margin-top: 1.4rem;
+ margin-bottom: 1px;
+ font-size: 1.5rem;
+ font-weight: 600;
+ line-height: 1.3;
+}
+
+.prose :where(h3):not(:where([class~="not-prose"], [class~="not-prose"] *)) {
+ margin-top: 1rem;
+ margin-bottom: 1px;
+ font-size: 1.25rem;
+ line-height: 1.3;
+}
+
+.prose :where(p):not(:where([class~="not-prose"], [class~="not-prose"] *)) {
+ margin-top: 0.25rem;
+ margin-bottom: 1px;
+ padding: 3px 2px;
+ font-size: 1rem;
+ line-height: 1.5;
+}
+
+.prose :where(ol):not(:where([class~="not-prose"], [class~="not-prose"] *)) li p,
+.prose :where(ul):not(:where([class~="not-prose"], [class~="not-prose"] *)) li p {
+ font-size: 1rem;
+ line-height: 1.5;
+}
+
+.prose :where(.prose > :first-child):not(:where([class~="not-prose"], [class~="not-prose"] *)) {
+ margin-top: 0;
+}
+/* end tailwind typography */
diff --git a/packages/editor/core/src/styles/table.css b/packages/editor/core/src/styles/table.css
index 3ba17ee1b2..433b77bfe5 100644
--- a/packages/editor/core/src/styles/table.css
+++ b/packages/editor/core/src/styles/table.css
@@ -1,23 +1,25 @@
-.tableWrapper {
+.table-wrapper {
overflow-x: auto;
- padding: 2px;
width: fit-content;
max-width: 100%;
}
-.tableWrapper table {
+.table-wrapper table {
border-collapse: collapse;
table-layout: fixed;
- margin: 0;
- margin-bottom: 1rem;
- border: 2px solid rgba(var(--color-border-300));
+ margin: 0.5rem 0 1rem 0;
+ border: 1px solid rgba(var(--color-border-200));
width: 100%;
}
-.tableWrapper table td,
-.tableWrapper table th {
+.table-wrapper table p {
+ font-size: 14px;
+}
+
+.table-wrapper table td,
+.table-wrapper table th {
min-width: 1em;
- border: 1px solid rgba(var(--color-border-300));
+ border: 1px solid rgba(var(--color-border-200));
padding: 10px 15px;
vertical-align: top;
box-sizing: border-box;
@@ -29,86 +31,45 @@
}
}
-.tableWrapper table td > *,
-.tableWrapper table th > * {
+.table-wrapper table td > *,
+.table-wrapper table th > * {
margin: 0 !important;
padding: 0.25rem 0 !important;
}
-.tableWrapper table td.has-focus,
-.tableWrapper table th.has-focus {
+.table-wrapper table td.has-focus,
+.table-wrapper table th.has-focus {
box-shadow: rgba(var(--color-primary-300), 0.1) 0px 0px 0px 2px inset !important;
}
-.tableWrapper table th {
- font-weight: bold;
+.table-wrapper table th {
+ font-weight: 500;
text-align: left;
- background-color: #d9e4ff;
- color: #171717;
+ background-color: rgba(var(--color-background-90));
}
-.tableWrapper table th * {
- font-weight: 600;
+.table-wrapper table .selectedCell {
+ border-color: rgba(var(--color-primary-100));
}
-.tableWrapper table .selectedCell:after {
- z-index: 2;
- position: absolute;
- content: "";
- left: 0;
- right: 0;
- top: 0;
- bottom: 0;
- background-color: rgba(var(--color-primary-300), 0.1);
- pointer-events: none;
-}
-
-.colorPicker {
- display: grid;
- padding: 8px 8px;
- grid-template-columns: repeat(6, 1fr);
- gap: 5px;
-}
-
-.colorPickerLabel {
- font-size: 0.85rem;
- color: #6b7280;
- padding: 8px 8px;
- padding-bottom: 0px;
-}
-
-.colorPickerItem {
- margin: 2px 0px;
- width: 24px;
- height: 24px;
- border-radius: 4px;
- border: none;
- cursor: pointer;
-}
-
-.divider {
- background-color: #e5e7eb;
- height: 1px;
- margin: 3px 0;
-}
-
-.tableWrapper table .column-resize-handle {
+/* table dropdown */
+.table-wrapper table .column-resize-handle {
position: absolute;
right: -2px;
top: 0;
- bottom: -2px;
- width: 4px;
+ width: 2px;
+ height: 100%;
z-index: 5;
- background-color: #d9e4ff;
+ background-color: rgba(var(--color-primary-100));
pointer-events: none;
}
-.tableWrapper .tableControls {
+.table-wrapper .table-controls {
position: absolute;
}
-.tableWrapper .tableControls .columnsControl,
-.tableWrapper .tableControls .rowsControl {
+.table-wrapper .table-controls .columns-control,
+.table-wrapper .table-controls .rows-control {
transition: opacity ease-in 100ms;
position: absolute;
z-index: 5;
@@ -117,49 +78,35 @@
align-items: center;
}
-.tableWrapper .tableControls .columnsControl {
+.table-wrapper .table-controls .columns-control {
height: 20px;
transform: translateY(-50%);
}
-.tableWrapper .tableControls .columnsControl .columnsControlDiv {
+.table-wrapper .table-controls .columns-control .columns-control-div {
color: white;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' d='M0 0h24v24H0z'/%3E%3Cpath fill='%238F95B2' d='M4.5 10.5c-.825 0-1.5.675-1.5 1.5s.675 1.5 1.5 1.5S6 12.825 6 12s-.675-1.5-1.5-1.5zm15 0c-.825 0-1.5.675-1.5 1.5s.675 1.5 1.5 1.5S21 12.825 21 12s-.675-1.5-1.5-1.5zm-7.5 0c-.825 0-1.5.675-1.5 1.5s.675 1.5 1.5 1.5 1.5-.675 1.5-1.5-.675-1.5-1.5-1.5z'/%3E%3C/svg%3E");
width: 30px;
height: 15px;
}
-.tableWrapper .tableControls .rowsControl {
+.table-wrapper .table-controls .rows-control {
width: 20px;
transform: translateX(-50%);
}
-.tableWrapper .tableControls .rowsControl .rowsControlDiv {
+.table-wrapper .table-controls .rows-control .rows-control-div {
color: white;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='24' height='24'%3E%3Cpath fill='none' d='M0 0h24v24H0z'/%3E%3Cpath fill='%238F95B2' d='M12 3c-.825 0-1.5.675-1.5 1.5S11.175 6 12 6s1.5-.675 1.5-1.5S12.825 3 12 3zm0 15c-.825 0-1.5.675-1.5 1.5S11.175 21 12 21s1.5-.675 1.5-1.5S12.825 18 12 18zm0-7.5c-.825 0-1.5.675-1.5 1.5s.675 1.5 1.5 1.5 1.5-.675 1.5-1.5-.675-1.5-1.5-1.5z'/%3E%3C/svg%3E");
height: 30px;
width: 15px;
}
-.tableWrapper .tableControls .rowsControlDiv {
- background-color: #d9e4ff;
- border: 1px solid rgba(var(--color-border-200));
- border-radius: 2px;
- background-size: 1.25rem;
- background-repeat: no-repeat;
- background-position: center;
- transition:
- transform ease-out 100ms,
- background-color ease-out 100ms;
- outline: none;
- box-shadow: #000 0px 2px 4px;
- cursor: pointer;
-}
-
-.tableWrapper .tableControls .columnsControlDiv {
- background-color: #d9e4ff;
- border: 1px solid rgba(var(--color-border-200));
- border-radius: 2px;
+.table-wrapper .table-controls .rows-control-div,
+.table-wrapper .table-controls .columns-control-div {
+ background-color: rgba(var(--color-background-80));
+ border: 0.5px solid rgba(var(--color-border-200));
+ border-radius: 4px;
background-size: 1.25rem;
background-repeat: no-repeat;
background-position: center;
@@ -167,74 +114,14 @@
transform ease-out 100ms,
background-color ease-out 100ms;
outline: none;
- box-shadow: #000 0px 2px 4px;
- cursor: pointer;
-}
-.tableWrapper .tableControls .tableToolbox,
-.tableWrapper .tableControls .tableColorPickerToolbox {
- border: 1px solid rgba(var(--color-border-300));
- background-color: rgba(var(--color-background-100));
- border-radius: 5px;
- box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
- padding: 0.25rem;
- display: flex;
- flex-direction: column;
- width: max-content;
- gap: 0.25rem;
-}
-
-.tableWrapper .tableControls .tableToolbox .toolboxItem,
-.tableWrapper .tableControls .tableColorPickerToolbox .toolboxItem {
- background-color: rgba(var(--color-background-100));
- display: flex;
- align-items: center;
- gap: 0.5rem;
- border: none;
- padding: 0.3rem 0.5rem 0.1rem 0.1rem;
- border-radius: 4px;
+ box-shadow: rgba(var(--color-shadow-2xs));
cursor: pointer;
- transition: all 0.2s;
-}
-
-.tableWrapper .tableControls .tableToolbox .toolboxItem:hover,
-.tableWrapper .tableControls .tableColorPickerToolbox .toolboxItem:hover {
- background-color: rgba(var(--color-background-80), 0.6);
-}
-
-.tableWrapper .tableControls .tableToolbox .toolboxItem .iconContainer,
-.tableWrapper .tableControls .tableColorPickerToolbox .toolboxItem .iconContainer,
-.tableWrapper .tableControls .tableToolbox .toolboxItem .colorContainer,
-.tableWrapper .tableControls .tableColorPickerToolbox .toolboxItem .colorContainer {
- padding: 4px 0px;
- display: flex;
- align-items: center;
- justify-content: center;
- width: 1.75rem;
- height: 1.75rem;
-}
-
-.tableWrapper .tableControls .tableToolbox .toolboxItem .iconContainer svg,
-.tableWrapper .tableControls .tableColorPickerToolbox .toolboxItem .iconContainer svg,
-.tableWrapper .tableControls .tableToolbox .toolboxItem .colorContainer svg,
-.tableWrapper .tableControls .tableColorPickerToolbox .toolboxItem .colorContainer svg {
- width: 1rem;
- height: 1rem;
-}
-
-.tableToolbox {
- background-color: rgba(var(--color-background-100));
-}
-
-.tableWrapper .tableControls .tableToolbox .toolboxItem .label,
-.tableWrapper .tableControls .tableColorPickerToolbox .toolboxItem .label {
- font-size: 0.85rem;
- color: rgba(var(--color-text-300));
}
-.resize-cursor .tableWrapper .tableControls .rowsControl,
-.tableWrapper.controls--disabled .tableControls .rowsControl,
-.resize-cursor .tableWrapper .tableControls .columnsControl,
-.tableWrapper.controls--disabled .tableControls .columnsControl {
+.resize-cursor .table-wrapper .table-controls .rows-control,
+.table-wrapper.controls--disabled .table-controls .rows-control,
+.resize-cursor .table-wrapper .table-controls .columns-control,
+.table-wrapper.controls--disabled .table-controls .columns-control {
opacity: 0;
pointer-events: none;
}
diff --git a/packages/editor/core/src/types/editor-ref-api.ts b/packages/editor/core/src/types/editor-ref-api.ts
new file mode 100644
index 0000000000..df5df2c7b4
--- /dev/null
+++ b/packages/editor/core/src/types/editor-ref-api.ts
@@ -0,0 +1,17 @@
+import { IMarking } from "src/helpers/scroll-to-node";
+import { EditorMenuItemNames } from "src/ui/menus/menu-items";
+
+export type EditorReadOnlyRefApi = {
+ getMarkDown: () => string;
+ clearEditor: () => void;
+ setEditorValue: (content: string) => void;
+ scrollSummary: (marking: IMarking) => void;
+};
+
+export interface EditorRefApi extends EditorReadOnlyRefApi {
+ setEditorValueAtCursorPosition: (content: string) => void;
+ executeMenuItemCommand: (itemName: EditorMenuItemNames) => void;
+ isMenuItemActive: (itemName: EditorMenuItemNames) => boolean;
+ onStateChange: (callback: () => void) => () => void;
+ setFocusAtPosition: (position: number) => void;
+}
diff --git a/packages/editor/core/src/types/mention-suggestion.ts b/packages/editor/core/src/types/mention-suggestion.ts
index dcaa3148d6..aa2ad4ba29 100644
--- a/packages/editor/core/src/types/mention-suggestion.ts
+++ b/packages/editor/core/src/types/mention-suggestion.ts
@@ -1,10 +1,18 @@
+import { Editor, Range } from "@tiptap/react";
export type IMentionSuggestion = {
id: string;
type: string;
+ entity_name: string;
+ entity_identifier: string;
avatar: string;
title: string;
subtitle: string;
redirect_uri: string;
};
+export type CommandProps = {
+ editor: Editor;
+ range: Range;
+};
+
export type IMentionHighlight = string;
diff --git a/packages/editor/core/src/ui/components/editor-container.tsx b/packages/editor/core/src/ui/components/editor-container.tsx
index 2d60815250..e7d272b9bb 100644
--- a/packages/editor/core/src/ui/components/editor-container.tsx
+++ b/packages/editor/core/src/ui/components/editor-container.tsx
@@ -4,13 +4,13 @@ import { cn } from "src/lib/utils";
interface EditorContainerProps {
editor: Editor | null;
- editorClassNames: string;
+ editorContainerClassName: string;
children: ReactNode;
hideDragHandle?: () => void;
}
export const EditorContainer: FC<EditorContainerProps> = (props) => {
- const { editor, editorClassNames, hideDragHandle, children } = props;
+ const { editor, editorContainerClassName, hideDragHandle, children } = props;
const handleContainerClick = () => {
if (!editor) return;
@@ -51,10 +51,14 @@ export const EditorContainer: FC<EditorContainerProps> = (props) => {
<div
id="editor-container"
onClick={handleContainerClick}
- onMouseLeave={() => {
- hideDragHandle?.();
- }}
- className={cn(`cursor-text`, { "active-editor": editor?.isFocused && editor?.isEditable }, editorClassNames)}
+ onMouseLeave={hideDragHandle}
+ className={cn(
+ "cursor-text relative",
+ {
+ "active-editor": editor?.isFocused && editor?.isEditable,
+ },
+ editorContainerClassName
+ )}
>
{children}
</div>
diff --git a/packages/editor/core/src/ui/components/editor-content.tsx b/packages/editor/core/src/ui/components/editor-content.tsx
index 7a6ce30f77..a2427265c1 100644
--- a/packages/editor/core/src/ui/components/editor-content.tsx
+++ b/packages/editor/core/src/ui/components/editor-content.tsx
@@ -4,22 +4,15 @@ import { ImageResizer } from "src/ui/extensions/image/image-resize";
interface EditorContentProps {
editor: Editor | null;
- editorContentCustomClassNames: string | undefined;
children?: ReactNode;
tabIndex?: number;
}
export const EditorContentWrapper: FC<EditorContentProps> = (props) => {
- const { editor, editorContentCustomClassNames = "", tabIndex, children } = props;
+ const { editor, tabIndex, children } = props;
return (
- <div
- className={`contentEditor ${editorContentCustomClassNames}`}
- tabIndex={tabIndex}
- onFocus={() => {
- editor?.chain().focus(undefined, { scrollIntoView: false }).run();
- }}
- >
+ <div tabIndex={tabIndex} onFocus={() => editor?.chain().focus(undefined, { scrollIntoView: false }).run()}>
<EditorContent editor={editor} />
{editor?.isActive("image") && editor?.isEditable && <ImageResizer editor={editor} />}
{children}
diff --git a/packages/editor/core/src/ui/extensions/code-inline/index.tsx b/packages/editor/core/src/ui/extensions/code-inline/index.tsx
index 1c5d341090..bc629160a8 100644
--- a/packages/editor/core/src/ui/extensions/code-inline/index.tsx
+++ b/packages/editor/core/src/ui/extensions/code-inline/index.tsx
@@ -32,7 +32,8 @@ export const CustomCodeInlineExtension = Mark.create<CodeOptions>({
addOptions() {
return {
HTMLAttributes: {
- class: "rounded-md bg-custom-primary-30 mx-1 px-1 py-[2px] font-mono font-medium text-custom-text-1000",
+ class:
+ "rounded bg-custom-background-80 px-1 py-[2px] font-mono font-medium text-orange-500 border-[0.5px] border-custom-border-200 text-sm",
spellcheck: "false",
},
};
diff --git a/packages/editor/core/src/ui/extensions/code/code-block-node-view.tsx b/packages/editor/core/src/ui/extensions/code/code-block-node-view.tsx
new file mode 100644
index 0000000000..f75da438e2
--- /dev/null
+++ b/packages/editor/core/src/ui/extensions/code/code-block-node-view.tsx
@@ -0,0 +1,56 @@
+import { useState } from "react";
+import { NodeViewWrapper, NodeViewContent } from "@tiptap/react";
+import { common, createLowlight } from "lowlight";
+import ts from "highlight.js/lib/languages/typescript";
+import { CopyIcon, CheckIcon } from "lucide-react";
+import { Node as ProseMirrorNode } from "@tiptap/pm/model";
+import { cn } from "src/lib/utils";
+
+// we just have ts support for now
+const lowlight = createLowlight(common);
+lowlight.register("ts", ts);
+
+interface CodeBlockComponentProps {
+ node: ProseMirrorNode;
+}
+
+export const CodeBlockComponent: React.FC<CodeBlockComponentProps> = ({ node }) => {
+ const [copied, setCopied] = useState(false);
+
+ const copyToClipboard = async (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
+ try {
+ await navigator.clipboard.writeText(node.textContent);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 1000);
+ } catch (error) {
+ setCopied(false);
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ };
+
+ return (
+ <NodeViewWrapper className="code-block relative">
+ <button
+ type="button"
+ className={cn(
+ "group absolute top-2 right-2 z-10 flex items-center justify-center w-8 h-8 rounded-md bg-custom-background-80 border border-custom-border-200 transition duration-150 ease-in-out",
+ {
+ "bg-green-500/10 hover:bg-green-500/10 active:bg-green-500/10": copied,
+ }
+ )}
+ onClick={copyToClipboard}
+ >
+ {copied ? (
+ <CheckIcon className="h-3 w-3 text-green-500" strokeWidth={3} />
+ ) : (
+ <CopyIcon className="h-3 w-3 text-custom-text-300 group-hover:text-custom-text-100" />
+ )}
+ </button>
+
+ <pre className="bg-custom-background-90 text-custom-text-100 rounded-lg p-8 pl-9 pr-4">
+ <NodeViewContent as="code" />
+ </pre>
+ </NodeViewWrapper>
+ );
+};
diff --git a/packages/editor/core/src/ui/extensions/code/index.tsx b/packages/editor/core/src/ui/extensions/code/index.tsx
index 64a1740cb2..d2851d3025 100644
--- a/packages/editor/core/src/ui/extensions/code/index.tsx
+++ b/packages/editor/core/src/ui/extensions/code/index.tsx
@@ -7,8 +7,14 @@ const lowlight = createLowlight(common);
lowlight.register("ts", ts);
import { Selection } from "@tiptap/pm/state";
+import { ReactNodeViewRenderer } from "@tiptap/react";
+import { CodeBlockComponent } from "./code-block-node-view";
export const CustomCodeBlockExtension = CodeBlockLowlight.extend({
+ addNodeView() {
+ return ReactNodeViewRenderer(CodeBlockComponent);
+ },
+
addKeyboardShortcuts() {
return {
Tab: ({ editor }) => {
diff --git a/packages/editor/core/src/ui/extensions/custom-code-inline/inline-code-plugin.ts b/packages/editor/core/src/ui/extensions/custom-code-inline/inline-code-plugin.ts
new file mode 100644
index 0000000000..3b3cfaab1e
--- /dev/null
+++ b/packages/editor/core/src/ui/extensions/custom-code-inline/inline-code-plugin.ts
@@ -0,0 +1,9 @@
+import { Extension } from "@tiptap/core";
+import codemark from "prosemirror-codemark";
+
+export const CustomCodeMarkPlugin = Extension.create({
+ name: "codemarkPlugin",
+ addProseMirrorPlugins() {
+ return codemark({ markType: this.editor.schema.marks.code });
+ },
+});
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers.ts
new file mode 100644
index 0000000000..330ebbc12c
--- /dev/null
+++ b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers.ts
@@ -0,0 +1,363 @@
+import { EditorState } from "@tiptap/pm/state";
+import { Editor, getNodeType, getNodeAtPosition, isAtEndOfNode, isAtStartOfNode, isNodeActive } from "@tiptap/core";
+import { Node, NodeType } from "@tiptap/pm/model";
+
+const findListItemPos = (typeOrName: string | NodeType, state: EditorState) => {
+ const { $from } = state.selection;
+ const nodeType = getNodeType(typeOrName, state.schema);
+
+ let currentNode = null;
+ let currentDepth = $from.depth;
+ let currentPos = $from.pos;
+ let targetDepth: number | null = null;
+
+ while (currentDepth > 0 && targetDepth === null) {
+ currentNode = $from.node(currentDepth);
+
+ if (currentNode.type === nodeType) {
+ targetDepth = currentDepth;
+ } else {
+ currentDepth -= 1;
+ currentPos -= 1;
+ }
+ }
+
+ if (targetDepth === null) {
+ return null;
+ }
+
+ return { $pos: state.doc.resolve(currentPos), depth: targetDepth };
+};
+
+const nextListIsDeeper = (typeOrName: string, state: EditorState) => {
+ const listDepth = getNextListDepth(typeOrName, state);
+ const listItemPos = findListItemPos(typeOrName, state);
+
+ if (!listItemPos || !listDepth) {
+ return false;
+ }
+
+ if (listDepth > listItemPos.depth) {
+ return true;
+ }
+
+ return false;
+};
+
+const getNextListDepth = (typeOrName: string, state: EditorState) => {
+ const listItemPos = findListItemPos(typeOrName, state);
+
+ if (!listItemPos) {
+ return false;
+ }
+
+ const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4);
+
+ return depth;
+};
+
+const getPrevListDepth = (typeOrName: string, state: EditorState) => {
+ const listItemPos = findListItemPos(typeOrName, state);
+
+ if (!listItemPos) {
+ return false;
+ }
+
+ let depth = 0;
+ const pos = listItemPos.$pos;
+
+ // Adjust the position to ensure we're within the list item, especially for edge cases
+ const resolvedPos = state.doc.resolve(Math.max(pos.pos - 1, 0));
+
+ // Traverse up the document structure from the adjusted position
+ for (let d = resolvedPos.depth; d > 0; d--) {
+ const node = resolvedPos.node(d);
+ if (node.type.name === "bulletList" || node.type.name === "orderedList") {
+ // Increment depth for each list ancestor found
+ depth++;
+ }
+ }
+
+ // Subtract 1 from the calculated depth to get the parent list's depth
+ // This adjustment is necessary because the depth calculation includes the current list
+ // By subtracting 1, we aim to get the depth of the parent list, which helps in identifying if the current list is a sublist
+ depth = depth > 0 ? depth - 1 : 0;
+
+ // Double the depth value to get results as 2, 4, 6, 8, etc.
+ depth = depth * 2;
+
+ return depth;
+};
+
+export const handleBackspace = (editor: Editor, name: string, parentListTypes: string[]) => {
+ // this is required to still handle the undo handling
+ if (editor.commands.undoInputRule()) {
+ return true;
+ }
+ // Check if a node range is selected, and if so, fall back to default backspace functionality
+ const { from, to } = editor.state.selection;
+ if (from !== to) {
+ // A range is selected, not just a cursor position; fall back to default behavior
+ return false; // Let the editor handle backspace by default
+ }
+
+ // if the current item is NOT inside a list item &
+ // the previous item is a list (orderedList or bulletList)
+ // move the cursor into the list and delete the current item
+ if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) {
+ const { $anchor } = editor.state.selection;
+
+ const $listPos = editor.state.doc.resolve($anchor.before() - 1);
+
+ const listDescendants: Array<{ node: Node; pos: number }> = [];
+
+ $listPos.node().descendants((node, pos) => {
+ if (node.type.name === name) {
+ listDescendants.push({ node, pos });
+ }
+ });
+
+ const lastItem = listDescendants.at(-1);
+
+ if (!lastItem) {
+ return false;
+ }
+
+ const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1);
+
+ // Check if positions are within the valid range
+ const startPos = $anchor.start() - 1;
+ const endPos = $anchor.end() + 1;
+ if (startPos < 0 || endPos > editor.state.doc.content.size) {
+ return false; // Invalid position, abort operation
+ }
+
+ return editor.chain().cut({ from: startPos, to: endPos }, $lastItemPos.end()).joinForward().run();
+ }
+
+ // if the cursor is not inside the current node type
+ // do nothing and proceed
+ if (!isNodeActive(editor.state, name)) {
+ return false;
+ }
+
+ // if the cursor is not at the start of a node
+ // do nothing and proceed
+ if (!isAtStartOfNode(editor.state)) {
+ return false;
+ }
+ const isParaSibling = isCurrentParagraphASibling(editor.state);
+ const isCurrentListItemSublist = prevListIsHigher(name, editor.state);
+ const listItemPos = findListItemPos(name, editor.state);
+ const nextListItemIsSibling = nextListIsSibling(name, editor.state);
+
+ if (!listItemPos) {
+ return false;
+ }
+
+ const currentNode = listItemPos.$pos.node(listItemPos.depth);
+ const currentListItemHasSubList = listItemHasSubList(name, editor.state, currentNode);
+
+ if (currentListItemHasSubList && isCurrentListItemSublist && isParaSibling) {
+ return false;
+ }
+
+ if (currentListItemHasSubList && isCurrentListItemSublist) {
+ editor.chain().liftListItem(name).run();
+ return editor.commands.joinItemBackward();
+ }
+
+ if (isCurrentListItemSublist && nextListItemIsSibling) {
+ return false;
+ }
+
+ if (isCurrentListItemSublist) {
+ return false;
+ }
+
+ if (currentListItemHasSubList) {
+ return false;
+ }
+
+ if (hasListItemBefore(name, editor.state)) {
+ return editor.chain().liftListItem(name).run();
+ }
+
+ if (!currentListItemHasSubList) {
+ return false;
+ }
+
+ // otherwise in the end, a backspace should
+ // always just lift the list item if
+ // joining / merging is not possible
+ return editor.chain().liftListItem(name).run();
+};
+
+export const handleDelete = (editor: Editor, name: string) => {
+ // if the cursor is not inside the current node type
+ // do nothing and proceed
+ if (!isNodeActive(editor.state, name)) {
+ return false;
+ }
+
+ // if the cursor is not at the end of a node
+ // do nothing and proceed
+ if (!isAtEndOfNode(editor.state, name)) {
+ return false;
+ }
+
+ // check if the next node is a list with a deeper depth
+ if (nextListIsDeeper(name, editor.state)) {
+ return editor
+ .chain()
+ .focus(editor.state.selection.from + 4)
+ .lift(name)
+ .joinBackward()
+ .run();
+ }
+
+ if (nextListIsHigher(name, editor.state)) {
+ return editor.chain().joinForward().joinBackward().run();
+ }
+
+ return editor.commands.joinItemForward();
+};
+
+const hasListBefore = (editorState: EditorState, name: string, parentListTypes: string[]) => {
+ const { $anchor } = editorState.selection;
+
+ const previousNodePos = Math.max(0, $anchor.pos - 2);
+
+ const previousNode = editorState.doc.resolve(previousNodePos).node();
+
+ if (!previousNode || !parentListTypes.includes(previousNode.type.name)) {
+ return false;
+ }
+
+ return true;
+};
+
+const prevListIsHigher = (typeOrName: string, state: EditorState) => {
+ const listDepth = getPrevListDepth(typeOrName, state);
+ const listItemPos = findListItemPos(typeOrName, state);
+
+ if (!listItemPos || !listDepth) {
+ return false;
+ }
+
+ if (listDepth < listItemPos.depth) {
+ return true;
+ }
+
+ return false;
+};
+
+const nextListIsSibling = (typeOrName: string, state: EditorState) => {
+ const listDepth = getNextListDepth(typeOrName, state);
+ const listItemPos = findListItemPos(typeOrName, state);
+
+ if (!listItemPos || !listDepth) {
+ return false;
+ }
+
+ if (listDepth === listItemPos.depth) {
+ return true;
+ }
+
+ return false;
+};
+
+export const nextListIsHigher = (typeOrName: string, state: EditorState) => {
+ const listDepth = getNextListDepth(typeOrName, state);
+ const listItemPos = findListItemPos(typeOrName, state);
+
+ if (!listItemPos || !listDepth) {
+ return false;
+ }
+
+ if (listDepth < listItemPos.depth) {
+ return true;
+ }
+
+ return false;
+};
+
+const listItemHasSubList = (typeOrName: string, state: EditorState, node?: Node) => {
+ if (!node) {
+ return false;
+ }
+
+ const nodeType = getNodeType(typeOrName, state.schema);
+
+ let hasSubList = false;
+
+ node.descendants((child) => {
+ if (child.type === nodeType) {
+ hasSubList = true;
+ }
+ });
+
+ return hasSubList;
+};
+
+const isCurrentParagraphASibling = (state: EditorState): boolean => {
+ const { $from } = state.selection;
+ const listItemNode = $from.node(-1); // Get the parent node of the current selection, assuming it's a list item.
+ const currentParagraphNode = $from.parent; // Get the current node where the selection is.
+
+ // Ensure we're in a paragraph and the parent is a list item.
+ if (currentParagraphNode.type.name === "paragraph" && listItemNode.type.name === "listItem") {
+ let paragraphNodesCount = 0;
+ listItemNode.forEach((child) => {
+ if (child.type.name === "paragraph") {
+ paragraphNodesCount++;
+ }
+ });
+
+ // If there are more than one paragraph nodes, the current paragraph is a sibling.
+ return paragraphNodesCount > 1;
+ }
+
+ return false;
+};
+
+export function isCursorInSubList(editor: Editor) {
+ const { selection } = editor.state;
+ const { $from } = selection;
+
+ // Check if the current node is a list item
+ const listItem = editor.schema.nodes.listItem;
+
+ // Traverse up the document tree from the current position
+ for (let depth = $from.depth; depth > 0; depth--) {
+ const node = $from.node(depth);
+ if (node.type === listItem) {
+ // If the parent of the list item is also a list, it's a sub-list
+ const parent = $from.node(depth - 1);
+ if (
+ parent &&
+ (parent.type === editor.schema.nodes.bulletList || parent.type === editor.schema.nodes.orderedList)
+ ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+const hasListItemBefore = (typeOrName: string, state: EditorState): boolean => {
+ const { $anchor } = state.selection;
+
+ const $targetPos = state.doc.resolve($anchor.pos - 2);
+
+ if ($targetPos.index() === 0) {
+ return false;
+ }
+
+ if ($targetPos.nodeBefore?.type.name !== typeOrName) {
+ return false;
+ }
+
+ return true;
+};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/find-list-item-pos.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/find-list-item-pos.ts
deleted file mode 100644
index 3bbfd9c937..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/find-list-item-pos.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { getNodeType } from "@tiptap/core";
-import { NodeType } from "@tiptap/pm/model";
-import { EditorState } from "@tiptap/pm/state";
-
-export const findListItemPos = (typeOrName: string | NodeType, state: EditorState) => {
- const { $from } = state.selection;
- const nodeType = getNodeType(typeOrName, state.schema);
-
- let currentNode = null;
- let currentDepth = $from.depth;
- let currentPos = $from.pos;
- let targetDepth: number | null = null;
-
- while (currentDepth > 0 && targetDepth === null) {
- currentNode = $from.node(currentDepth);
-
- if (currentNode.type === nodeType) {
- targetDepth = currentDepth;
- } else {
- currentDepth -= 1;
- currentPos -= 1;
- }
- }
-
- if (targetDepth === null) {
- return null;
- }
-
- return { $pos: state.doc.resolve(currentPos), depth: targetDepth };
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/get-next-list-depth.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/get-next-list-depth.ts
deleted file mode 100644
index 2e4f5fbaa5..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/get-next-list-depth.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { getNodeAtPosition } from "@tiptap/core";
-import { EditorState } from "@tiptap/pm/state";
-
-import { findListItemPos } from "src/ui/extensions/custom-list-keymap/list-helpers/find-list-item-pos";
-
-export const getNextListDepth = (typeOrName: string, state: EditorState) => {
- const listItemPos = findListItemPos(typeOrName, state);
-
- if (!listItemPos) {
- return false;
- }
-
- const [, depth] = getNodeAtPosition(state, typeOrName, listItemPos.$pos.pos + 4);
-
- return depth;
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/handle-backspace.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/handle-backspace.ts
deleted file mode 100644
index a4f2d5db94..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/handle-backspace.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { Editor, isAtStartOfNode, isNodeActive } from "@tiptap/core";
-import { Node } from "@tiptap/pm/model";
-
-import { findListItemPos } from "src/ui/extensions/custom-list-keymap/list-helpers/find-list-item-pos";
-import { hasListBefore } from "src/ui/extensions/custom-list-keymap/list-helpers/has-list-before";
-
-export const handleBackspace = (editor: Editor, name: string, parentListTypes: string[]) => {
- // this is required to still handle the undo handling
- if (editor.commands.undoInputRule()) {
- return true;
- }
-
- // if the cursor is not at the start of a node
- // do nothing and proceed
- if (!isAtStartOfNode(editor.state)) {
- return false;
- }
-
- // if the current item is NOT inside a list item &
- // the previous item is a list (orderedList or bulletList)
- // move the cursor into the list and delete the current item
- if (!isNodeActive(editor.state, name) && hasListBefore(editor.state, name, parentListTypes)) {
- const { $anchor } = editor.state.selection;
-
- const $listPos = editor.state.doc.resolve($anchor.before() - 1);
-
- const listDescendants: Array<{ node: Node; pos: number }> = [];
-
- $listPos.node().descendants((node, pos) => {
- if (node.type.name === name) {
- listDescendants.push({ node, pos });
- }
- });
-
- const lastItem = listDescendants.at(-1);
-
- if (!lastItem) {
- return false;
- }
-
- const $lastItemPos = editor.state.doc.resolve($listPos.start() + lastItem.pos + 1);
-
- return editor
- .chain()
- .cut({ from: $anchor.start() - 1, to: $anchor.end() + 1 }, $lastItemPos.end())
- .joinForward()
- .run();
- }
-
- // if the cursor is not inside the current node type
- // do nothing and proceed
- if (!isNodeActive(editor.state, name)) {
- return false;
- }
-
- const listItemPos = findListItemPos(name, editor.state);
-
- if (!listItemPos) {
- return false;
- }
-
- // if current node is a list item and cursor it at start of a list node,
- // simply lift the list item i.e. remove it as a list item (task/bullet/ordered)
- // irrespective of above node being a list or not
- return editor.chain().liftListItem(name).run();
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/handle-delete.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/handle-delete.ts
deleted file mode 100644
index 9179e0f201..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/handle-delete.ts
+++ /dev/null
@@ -1,34 +0,0 @@
-import { Editor, isAtEndOfNode, isNodeActive } from "@tiptap/core";
-
-import { nextListIsDeeper } from "src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-deeper";
-import { nextListIsHigher } from "src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-higher";
-
-export const handleDelete = (editor: Editor, name: string) => {
- // if the cursor is not inside the current node type
- // do nothing and proceed
- if (!isNodeActive(editor.state, name)) {
- return false;
- }
-
- // if the cursor is not at the end of a node
- // do nothing and proceed
- if (!isAtEndOfNode(editor.state, name)) {
- return false;
- }
-
- // check if the next node is a list with a deeper depth
- if (nextListIsDeeper(name, editor.state)) {
- return editor
- .chain()
- .focus(editor.state.selection.from + 4)
- .lift(name)
- .joinBackward()
- .run();
- }
-
- if (nextListIsHigher(name, editor.state)) {
- return editor.chain().joinForward().joinBackward().run();
- }
-
- return editor.commands.joinItemForward();
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-before.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-before.ts
deleted file mode 100644
index fb6b95b6a7..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-before.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import { EditorState } from "@tiptap/pm/state";
-
-export const hasListBefore = (editorState: EditorState, name: string, parentListTypes: string[]) => {
- const { $anchor } = editorState.selection;
-
- const previousNodePos = Math.max(0, $anchor.pos - 2);
-
- const previousNode = editorState.doc.resolve(previousNodePos).node();
-
- if (!previousNode || !parentListTypes.includes(previousNode.type.name)) {
- return false;
- }
-
- return true;
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-item-after.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-item-after.ts
deleted file mode 100644
index 4e538ac47f..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-item-after.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { EditorState } from "@tiptap/pm/state";
-
-export const hasListItemAfter = (typeOrName: string, state: EditorState): boolean => {
- const { $anchor } = state.selection;
-
- const $targetPos = state.doc.resolve($anchor.pos - $anchor.parentOffset - 2);
-
- if ($targetPos.index() === $targetPos.parent.childCount - 1) {
- return false;
- }
-
- if ($targetPos.nodeAfter?.type.name !== typeOrName) {
- return false;
- }
-
- return true;
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-item-before.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-item-before.ts
deleted file mode 100644
index 91fda9bf4c..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/has-list-item-before.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import { EditorState } from "@tiptap/pm/state";
-
-export const hasListItemBefore = (typeOrName: string, state: EditorState): boolean => {
- const { $anchor } = state.selection;
-
- const $targetPos = state.doc.resolve($anchor.pos - 2);
-
- if ($targetPos.index() === 0) {
- return false;
- }
-
- if ($targetPos.nodeBefore?.type.name !== typeOrName) {
- return false;
- }
-
- return true;
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/index.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/index.ts
deleted file mode 100644
index 644953b92b..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-export * from "./find-list-item-pos";
-export * from "./get-next-list-depth";
-export * from "./handle-backspace";
-export * from "./handle-delete";
-export * from "./has-list-before";
-export * from "./has-list-item-after";
-export * from "./has-list-item-before";
-export * from "./next-list-is-deeper";
-export * from "./next-list-is-higher";
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-deeper.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-deeper.ts
deleted file mode 100644
index 7cd1a63f7e..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-deeper.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { EditorState } from "@tiptap/pm/state";
-
-import { findListItemPos } from "src/ui/extensions/custom-list-keymap/list-helpers/find-list-item-pos";
-import { getNextListDepth } from "src/ui/extensions/custom-list-keymap/list-helpers/get-next-list-depth";
-
-export const nextListIsDeeper = (typeOrName: string, state: EditorState) => {
- const listDepth = getNextListDepth(typeOrName, state);
- const listItemPos = findListItemPos(typeOrName, state);
-
- if (!listItemPos || !listDepth) {
- return false;
- }
-
- if (listDepth > listItemPos.depth) {
- return true;
- }
-
- return false;
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-higher.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-higher.ts
deleted file mode 100644
index 3364c3b87c..0000000000
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-helpers/next-list-is-higher.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { EditorState } from "@tiptap/pm/state";
-
-import { findListItemPos } from "src/ui/extensions/custom-list-keymap/list-helpers/find-list-item-pos";
-import { getNextListDepth } from "src/ui/extensions/custom-list-keymap/list-helpers/get-next-list-depth";
-
-export const nextListIsHigher = (typeOrName: string, state: EditorState) => {
- const listDepth = getNextListDepth(typeOrName, state);
- const listItemPos = findListItemPos(typeOrName, state);
-
- if (!listItemPos || !listDepth) {
- return false;
- }
-
- if (listDepth < listItemPos.depth) {
- return true;
- }
-
- return false;
-};
diff --git a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-keymap.ts b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-keymap.ts
index aabd836d2e..dba6b1f46c 100644
--- a/packages/editor/core/src/ui/extensions/custom-list-keymap/list-keymap.ts
+++ b/packages/editor/core/src/ui/extensions/custom-list-keymap/list-keymap.ts
@@ -29,6 +29,22 @@ export const ListKeymap = Extension.create<ListKeymapOptions>({
addKeyboardShortcuts() {
return {
+ Tab: () => {
+ if (this.editor.commands.sinkListItem("listItem")) {
+ return true;
+ } else if (this.editor.commands.sinkListItem("taskItem")) {
+ return true;
+ }
+ return true;
+ },
+ "Shift-Tab": () => {
+ if (this.editor.commands.liftListItem("listItem")) {
+ return true;
+ } else if (this.editor.commands.liftListItem("taskItem")) {
+ return true;
+ }
+ return true;
+ },
Delete: ({ editor }) => {
let handled = false;
diff --git a/packages/editor/core/src/ui/extensions/image/image-resize.tsx b/packages/editor/core/src/ui/extensions/image/image-resize.tsx
index 400938785b..7f61cc9cbd 100644
--- a/packages/editor/core/src/ui/extensions/image/image-resize.tsx
+++ b/packages/editor/core/src/ui/extensions/image/image-resize.tsx
@@ -7,10 +7,19 @@ export const ImageResizer = ({ editor }: { editor: Editor }) => {
const imageInfo = document.querySelector(".ProseMirror-selectednode") as HTMLImageElement;
if (imageInfo) {
const selection = editor.state.selection;
+
+ // Use the style width/height if available, otherwise fall back to the element's natural width/height
+ const width = imageInfo.style.width
+ ? Number(imageInfo.style.width.replace("px", ""))
+ : imageInfo.getAttribute("width");
+ const height = imageInfo.style.height
+ ? Number(imageInfo.style.height.replace("px", ""))
+ : imageInfo.getAttribute("height");
+
editor.commands.setImage({
src: imageInfo.src,
- width: Number(imageInfo.style.width.replace("px", "")),
- height: Number(imageInfo.style.height.replace("px", "")),
+ width: width,
+ height: height,
} as any);
editor.commands.setNodeSelection(selection.from);
}
@@ -21,7 +30,7 @@ export const ImageResizer = ({ editor }: { editor: Editor }) => {
return (
<>
<Moveable
- target={document.querySelector(".ProseMirror-selectednode") as any}
+ target={document.querySelector(".ProseMirror-selectednode") as HTMLElement}
container={null}
origin={false}
edge={false}
@@ -37,27 +46,29 @@ export const ImageResizer = ({ editor }: { editor: Editor }) => {
setAspectRatio(originalWidth / originalHeight);
}
}}
- onResize={({ target, width, height, delta }: any) => {
- if (delta[0]) {
- const newWidth = Math.max(width, 100);
- const newHeight = newWidth / aspectRatio;
- target!.style.width = `${newWidth}px`;
- target!.style.height = `${newHeight}px`;
- }
- if (delta[1]) {
- const newHeight = Math.max(height, 100);
- const newWidth = newHeight * aspectRatio;
- target!.style.height = `${newHeight}px`;
- target!.style.width = `${newWidth}px`;
+ onResize={({ target, width, height, delta }) => {
+ if (delta[0] || delta[1]) {
+ let newWidth, newHeight;
+ if (delta[0]) {
+ // Width change detected
+ newWidth = Math.max(width, 100);
+ newHeight = newWidth / aspectRatio;
+ } else if (delta[1]) {
+ // Height change detected
+ newHeight = Math.max(height, 100);
+ newWidth = newHeight * aspectRatio;
+ }
+ target.style.width = `${newWidth}px`;
+ target.style.height = `${newHeight}px`;
}
}}
onResizeEnd={() => {
updateMediaSize();
}}
scalable
- renderDirections={["w", "e"]}
- onScale={({ target, transform }: any) => {
- target!.style.transform = transform;
+ renderDirections={["se"]}
+ onScale={({ target, transform }) => {
+ target.style.transform = transform;
}}
/>
</>
diff --git a/packages/editor/core/src/ui/extensions/index.tsx b/packages/editor/core/src/ui/extensions/index.tsx
index 1a932d6d51..1a68ee46ee 100644
--- a/packages/editor/core/src/ui/extensions/index.tsx
+++ b/packages/editor/core/src/ui/extensions/index.tsx
@@ -1,4 +1,3 @@
-import { Color } from "@tiptap/extension-color";
import TaskItem from "@tiptap/extension-task-item";
import TaskList from "@tiptap/extension-task-list";
import TextStyle from "@tiptap/extension-text-style";
@@ -22,17 +21,18 @@ import { CustomKeymap } from "src/ui/extensions/keymap";
import { CustomQuoteExtension } from "src/ui/extensions/quote";
import { DeleteImage } from "src/types/delete-image";
-import { IMentionSuggestion } from "src/types/mention-suggestion";
+import { IMentionHighlight, IMentionSuggestion } from "src/types/mention-suggestion";
import { RestoreImage } from "src/types/restore-image";
import { CustomLinkExtension } from "src/ui/extensions/custom-link";
import { CustomCodeInlineExtension } from "src/ui/extensions/code-inline";
import { CustomTypographyExtension } from "src/ui/extensions/typography";
import { CustomHorizontalRule } from "src/ui/extensions/horizontal-rule/horizontal-rule";
+import { CustomCodeMarkPlugin } from "./custom-code-inline/inline-code-plugin";
export const CoreEditorExtensions = (
mentionConfig: {
- mentionSuggestions: IMentionSuggestion[];
- mentionHighlights: string[];
+ mentionSuggestions?: () => Promise<IMentionSuggestion[]>;
+ mentionHighlights?: () => Promise<IMentionHighlight[]>;
},
deleteFile: DeleteImage,
restoreFile: RestoreImage,
@@ -41,17 +41,17 @@ export const CoreEditorExtensions = (
StarterKit.configure({
bulletList: {
HTMLAttributes: {
- class: "list-disc list-outside leading-3 -mt-2",
+ class: "list-disc pl-7 space-y-2",
},
},
orderedList: {
HTMLAttributes: {
- class: "list-decimal list-outside leading-3 -mt-2",
+ class: "list-decimal pl-7 space-y-2",
},
},
listItem: {
HTMLAttributes: {
- class: "leading-normal -mb-2",
+ class: "not-prose space-y-2",
},
},
code: false,
@@ -60,14 +60,17 @@ export const CoreEditorExtensions = (
blockquote: false,
dropcursor: {
color: "rgba(var(--color-text-100))",
- width: 2,
+ width: 1,
},
}),
- CustomQuoteExtension.configure({
- HTMLAttributes: { className: "border-l-4 border-custom-border-300" },
- }),
+ // BulletList,
+ // OrderedList,
+ // ListItem,
+ CustomQuoteExtension,
CustomHorizontalRule.configure({
- HTMLAttributes: { class: "mt-4 mb-4" },
+ HTMLAttributes: {
+ class: "my-4",
+ },
}),
CustomKeymap,
ListKeymap,
@@ -85,33 +88,40 @@ export const CoreEditorExtensions = (
CustomTypographyExtension,
ImageExtension(deleteFile, restoreFile, cancelUploadImage).configure({
HTMLAttributes: {
- class: "rounded-lg border border-custom-border-300",
+ class: "rounded-md",
},
}),
TiptapUnderline,
TextStyle,
- Color,
TaskList.configure({
HTMLAttributes: {
- class: "not-prose pl-2",
+ class: "not-prose pl-2 space-y-2",
},
}),
TaskItem.configure({
HTMLAttributes: {
- class: "flex items-start my-4",
+ class: "flex",
},
nested: true,
}),
- CustomCodeBlockExtension,
+ CustomCodeBlockExtension.configure({
+ HTMLAttributes: {
+ class: "",
+ },
+ }),
+ CustomCodeMarkPlugin,
CustomCodeInlineExtension,
Markdown.configure({
html: true,
- transformCopiedText: true,
transformPastedText: true,
}),
Table,
TableHeader,
TableCell,
TableRow,
- Mentions(mentionConfig.mentionSuggestions, mentionConfig.mentionHighlights, false),
+ Mentions({
+ mentionSuggestions: mentionConfig.mentionSuggestions,
+ mentionHighlights: mentionConfig.mentionHighlights,
+ readonly: false,
+ }),
];
diff --git a/packages/editor/core/src/ui/extensions/keymap.tsx b/packages/editor/core/src/ui/extensions/keymap.tsx
index 0caa194cd4..2e0bdd1fe9 100644
--- a/packages/editor/core/src/ui/extensions/keymap.tsx
+++ b/packages/editor/core/src/ui/extensions/keymap.tsx
@@ -1,4 +1,7 @@
import { Extension } from "@tiptap/core";
+import { Plugin, PluginKey, Transaction } from "@tiptap/pm/state";
+import { canJoin } from "@tiptap/pm/transform";
+import { NodeType } from "@tiptap/pm/model";
declare module "@tiptap/core" {
// eslint-disable-next-line no-unused-vars
@@ -12,6 +15,51 @@ declare module "@tiptap/core" {
}
}
+function autoJoin(tr: Transaction, newTr: Transaction, nodeType: NodeType) {
+ if (!tr.isGeneric) return false;
+
+ // Find all ranges where we might want to join.
+ const ranges: Array<number> = [];
+ for (let i = 0; i < tr.mapping.maps.length; i++) {
+ const map = tr.mapping.maps[i];
+ for (let j = 0; j < ranges.length; j++) ranges[j] = map.map(ranges[j]);
+ map.forEach((_s, _e, from, to) => ranges.push(from, to));
+ }
+
+ // Figure out which joinable points exist inside those ranges,
+ // by checking all node boundaries in their parent nodes.
+ const joinable = [];
+ for (let i = 0; i < ranges.length; i += 2) {
+ const from = ranges[i],
+ to = ranges[i + 1];
+ const $from = tr.doc.resolve(from),
+ depth = $from.sharedDepth(to),
+ parent = $from.node(depth);
+ for (let index = $from.indexAfter(depth), pos = $from.after(depth + 1); pos <= to; ++index) {
+ const after = parent.maybeChild(index);
+ if (!after) break;
+ if (index && joinable.indexOf(pos) == -1) {
+ const before = parent.child(index - 1);
+ if (before.type == after.type && before.type === nodeType) joinable.push(pos);
+ }
+ pos += after.nodeSize;
+ }
+ }
+
+ let joined = false;
+
+ // Join the joinable points
+ joinable.sort((a, b) => a - b);
+ for (let i = joinable.length - 1; i >= 0; i--) {
+ if (canJoin(tr.doc, joinable[i])) {
+ newTr.join(joinable[i]);
+ joined = true;
+ }
+ }
+
+ return joined;
+}
+
export const CustomKeymap = Extension.create({
name: "CustomKeymap",
@@ -32,6 +80,42 @@ export const CustomKeymap = Extension.create({
};
},
+ addProseMirrorPlugins() {
+ return [
+ new Plugin({
+ key: new PluginKey("ordered-list-merging"),
+ appendTransaction(transactions, oldState, newState) {
+ // Create a new transaction.
+ const newTr = newState.tr;
+
+ let joined = false;
+ for (const transaction of transactions) {
+ const anotherJoin = autoJoin(transaction, newTr, newState.schema.nodes["orderedList"]);
+ joined = anotherJoin || joined;
+ }
+ if (joined) {
+ return newTr;
+ }
+ },
+ }),
+ new Plugin({
+ key: new PluginKey("unordered-list-merging"),
+ appendTransaction(transactions, oldState, newState) {
+ // Create a new transaction.
+ const newTr = newState.tr;
+
+ let joined = false;
+ for (const transaction of transactions) {
+ const anotherJoin = autoJoin(transaction, newTr, newState.schema.nodes["bulletList"]);
+ joined = anotherJoin || joined;
+ }
+ if (joined) {
+ return newTr;
+ }
+ },
+ }),
+ ];
+ },
addKeyboardShortcuts() {
return {
"Mod-a": ({ editor }) => {
diff --git a/packages/editor/core/src/ui/extensions/table/table/icons.ts b/packages/editor/core/src/ui/extensions/table/table/icons.ts
index f73c55c09f..51c7784113 100644
--- a/packages/editor/core/src/ui/extensions/table/table/icons.ts
+++ b/packages/editor/core/src/ui/extensions/table/table/icons.ts
@@ -1,10 +1,10 @@
export const icons = {
colorPicker: `<svg xmlns="http://www.w3.org/2000/svg" length="24" viewBox="0 0 24 24" style="transform: ;msFilter:;"><path fill="rgb(var(--color-text-300))" d="M20 14c-.092.064-2 2.083-2 3.5 0 1.494.949 2.448 2 2.5.906.044 2-.891 2-2.5 0-1.5-1.908-3.436-2-3.5zM9.586 20c.378.378.88.586 1.414.586s1.036-.208 1.414-.586l7-7-.707-.707L11 4.586 8.707 2.293 7.293 3.707 9.586 6 4 11.586c-.378.378-.586.88-.586 1.414s.208 1.036.586 1.414L9.586 20zM11 7.414 16.586 13H5.414L11 7.414z"></path></svg>`,
- deleteColumn: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-2"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>`,
- deleteRow: `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-2"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>`,
+ deleteColumn: `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-2"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>`,
+ deleteRow: `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-trash-2"><path d="M3 6h18"/><path d="M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"/><path d="M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"/><line x1="10" x2="10" y1="11" y2="17"/><line x1="14" x2="14" y1="11" y2="17"/></svg>`,
insertLeftTableIcon: `<svg
xmlns="http://www.w3.org/2000/svg"
- length={24}
+ length={12}
viewBox="0 -960 960 960"
>
<path
@@ -15,7 +15,7 @@ export const icons = {
`,
insertRightTableIcon: `<svg
xmlns="http://www.w3.org/2000/svg"
- length={24}
+ length={12}
viewBox="0 -960 960 960"
>
<path
@@ -35,8 +35,8 @@ export const icons = {
/>
</svg>
`,
- toggleColumnHeader: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="rgb(var(--color-text-300))" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-toggle-right"><rect width="20" height="12" x="2" y="6" rx="6" ry="6"/><circle cx="16" cy="12" r="2"/></svg>`,
- toggleRowHeader: `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="rgb(var(--color-text-300))" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-toggle-right"><rect width="20" height="12" x="2" y="6" rx="6" ry="6"/><circle cx="16" cy="12" r="2"/></svg>`,
+ toggleColumnHeader: `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="rgb(var(--color-text-300))" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-toggle-right"><rect width="20" height="12" x="2" y="6" rx="6" ry="6"/><circle cx="16" cy="12" r="2"/></svg>`,
+ toggleRowHeader: `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="rgb(var(--color-text-300))" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-toggle-right"><rect width="20" height="12" x="2" y="6" rx="6" ry="6"/><circle cx="16" cy="12" r="2"/></svg>`,
insertBottomTableIcon: `<svg
xmlns="http://www.w3.org/2000/svg"
length={24}
diff --git a/packages/editor/core/src/ui/extensions/table/table/table-controls.ts b/packages/editor/core/src/ui/extensions/table/table/table-controls.ts
index 9311d4c990..34ad93fce5 100644
--- a/packages/editor/core/src/ui/extensions/table/table/table-controls.ts
+++ b/packages/editor/core/src/ui/extensions/table/table/table-controls.ts
@@ -20,7 +20,7 @@ export function tableControls() {
mousemove: (view, event) => {
const pluginState = key.getState(view.state);
- if (!(event.target as HTMLElement).closest(".tableWrapper") && pluginState.values.hoveredTable) {
+ if (!(event.target as HTMLElement).closest(".table-wrapper") && pluginState.values.hoveredTable) {
return view.dispatch(
view.state.tr.setMeta(key, {
setHoveredTable: null,
@@ -34,7 +34,7 @@ export function tableControls() {
top: event.clientY,
});
- if (!pos) return;
+ if (!pos || pos.pos < 0 || pos.pos > view.state.doc.content.size) return;
const table = findParentNode((node) => node.type.name === "table")(
TextSelection.create(view.state.doc, pos.pos)
diff --git a/packages/editor/core/src/ui/extensions/table/table/table-view.tsx b/packages/editor/core/src/ui/extensions/table/table/table-view.tsx
index 75b6bcb127..d4dfcf5c7c 100644
--- a/packages/editor/core/src/ui/extensions/table/table/table-view.tsx
+++ b/packages/editor/core/src/ui/extensions/table/table/table-view.tsx
@@ -177,7 +177,7 @@ const rowsToolboxItems: ToolboxItem[] = [
action: (args: any) => {}, // Placeholder action; actual color picking is handled in `createToolbox`
},
{
- label: "Delete Row",
+ label: "Delete row",
icon: icons.deleteRow,
action: ({ editor }: { editor: Editor }) => editor.chain().focus().deleteRow().run(),
},
@@ -189,7 +189,7 @@ function createToolbox({
tippyOptions,
onSelectColor,
onClickItem,
- colors = {},
+ colors,
}: {
triggerButton: Element | null;
items: ToolboxItem[];
@@ -202,38 +202,44 @@ function createToolbox({
const toolbox = tippy(triggerButton, {
content: h(
"div",
- { className: "tableToolbox" },
- items.map((item, index) => {
+ {
+ className:
+ "rounded-md border-[0.5px] border-custom-border-300 bg-custom-background-100 px-2 py-2.5 text-xs shadow-custom-shadow-rg min-w-[12rem] whitespace-nowrap",
+ },
+ items.map((item) => {
if (item.label === "Pick color") {
return h("div", { className: "flex flex-col" }, [
- h("div", { className: "divider" }),
- h("div", { className: "colorPickerLabel" }, item.label),
+ h("hr", { className: "my-2 border-custom-border-200" }),
+ h("div", { className: "text-custom-text-200 text-sm" }, item.label),
h(
"div",
- { className: "colorPicker grid" },
+ { className: "grid grid-cols-6 gap-x-1 gap-y-2.5 mt-2" },
Object.entries(colors).map(([colorName, colorValue]) =>
h("div", {
- className: "colorPickerItem flex items-center justify-center",
- style: `background-color: ${colorValue.backgroundColor};
- color: ${colorValue.textColor || "inherit"};`,
+ className: "grid place-items-center size-6 rounded cursor-pointer",
+ style: `background-color: ${colorValue.backgroundColor};color: ${colorValue.textColor || "inherit"};`,
innerHTML:
colorValue.icon ?? `<span class="text-md" style:"color: ${colorValue.backgroundColor}>A</span>`,
onClick: () => onSelectColor(colorValue),
})
)
),
- h("div", { className: "divider" }),
+ h("hr", { className: "my-2 border-custom-border-200" }),
]);
} else {
return h(
"div",
{
- className: "toolboxItem",
+ className:
+ "flex items-center gap-2 px-1 py-1.5 bg-custom-background-100 hover:bg-custom-background-80 text-sm text-custom-text-200 rounded cursor-pointer",
itemType: "div",
onClick: () => onClickItem(item),
},
[
- h("div", { className: "iconContainer", innerHTML: item.icon }),
+ h("span", {
+ className: "h-3 w-3 flex-shrink-0",
+ innerHTML: item.icon,
+ }),
h("div", { className: "label" }, item.label),
]
);
@@ -290,27 +296,27 @@ export class TableView implements NodeView {
if (editor.isEditable) {
this.rowsControl = h(
"div",
- { className: "rowsControl" },
+ { className: "rows-control" },
h("div", {
itemType: "button",
- className: "rowsControlDiv",
+ className: "rows-control-div",
onClick: () => this.selectRow(),
})
);
this.columnsControl = h(
"div",
- { className: "columnsControl" },
+ { className: "columns-control" },
h("div", {
itemType: "button",
- className: "columnsControlDiv",
+ className: "columns-control-div",
onClick: () => this.selectColumn(),
})
);
this.controls = h(
"div",
- { className: "tableControls", contentEditable: "false" },
+ { className: "table-controls", contentEditable: "false" },
this.rowsControl,
this.columnsControl
);
@@ -331,7 +337,7 @@ export class TableView implements NodeView {
};
this.columnsToolbox = createToolbox({
- triggerButton: this.columnsControl.querySelector(".columnsControlDiv"),
+ triggerButton: this.columnsControl.querySelector(".columns-control-div"),
items: columnsToolboxItems,
colors: columnColors,
onSelectColor: (color) => setCellsBackgroundColor(this.editor, color),
@@ -380,7 +386,7 @@ export class TableView implements NodeView {
this.root = h(
"div",
{
- className: "tableWrapper controls--disabled",
+ className: "table-wrapper horizontal-scrollbar scrollbar-md controls--disabled",
},
this.controls,
this.table
diff --git a/packages/editor/core/src/ui/mentions/custom.tsx b/packages/editor/core/src/ui/mentions/custom.tsx
index e723ca0d7f..8bab796667 100644
--- a/packages/editor/core/src/ui/mentions/custom.tsx
+++ b/packages/editor/core/src/ui/mentions/custom.tsx
@@ -5,7 +5,7 @@ import { MentionNodeView } from "src/ui/mentions/mention-node-view";
import { IMentionHighlight } from "src/types/mention-suggestion";
export interface CustomMentionOptions extends MentionOptions {
- mentionHighlights: IMentionHighlight[];
+ mentionHighlights: () => Promise<IMentionHighlight[]>;
readonly?: boolean;
}
@@ -32,6 +32,12 @@ export const CustomMention = Mention.extend<CustomMentionOptions>({
redirect_uri: {
default: "/",
},
+ entity_identifier: {
+ default: null,
+ },
+ entity_name: {
+ default: null,
+ },
};
},
@@ -43,17 +49,6 @@ export const CustomMention = Mention.extend<CustomMentionOptions>({
return [
{
tag: "mention-component",
- getAttrs: (node: string | HTMLElement) => {
- if (typeof node === "string") {
- return null;
- }
- return {
- id: node.getAttribute("data-mention-id") || "",
- target: node.getAttribute("data-mention-target") || "",
- label: node.innerText.slice(1) || "",
- redirect_uri: node.getAttribute("redirect_uri"),
- };
- },
},
];
},
diff --git a/packages/editor/core/src/ui/mentions/index.tsx b/packages/editor/core/src/ui/mentions/index.tsx
index f6d3e5b1fc..838622cbba 100644
--- a/packages/editor/core/src/ui/mentions/index.tsx
+++ b/packages/editor/core/src/ui/mentions/index.tsx
@@ -1,15 +1,90 @@
-// @ts-nocheck
-
-import { Suggestion } from "src/ui/mentions/suggestion";
import { CustomMention } from "src/ui/mentions/custom";
-import { IMentionHighlight } from "src/types/mention-suggestion";
+import { IMentionHighlight, IMentionSuggestion } from "src/types/mention-suggestion";
+import { ReactRenderer } from "@tiptap/react";
+import { Editor } from "@tiptap/core";
+import tippy from "tippy.js";
+
+import { MentionList } from "src/ui/mentions/mention-list";
-export const Mentions = (mentionSuggestions: IMentionSuggestion[], mentionHighlights: IMentionHighlight[], readonly) =>
+export const Mentions = ({
+ mentionHighlights,
+ mentionSuggestions,
+ readonly,
+}: {
+ mentionSuggestions?: () => Promise<IMentionSuggestion[]>;
+ mentionHighlights?: () => Promise<IMentionHighlight[]>;
+ readonly: boolean;
+}) =>
CustomMention.configure({
HTMLAttributes: {
class: "mention",
},
readonly: readonly,
mentionHighlights: mentionHighlights,
- suggestion: Suggestion(mentionSuggestions),
+ suggestion: {
+ // @ts-expect-error - Tiptap types are incorrect
+ render: () => {
+ if (!mentionSuggestions) return;
+ let component: ReactRenderer | null = null;
+ let popup: any | null = null;
+
+ return {
+ onStart: (props: { editor: Editor; clientRect: DOMRect }) => {
+ if (!props.clientRect) {
+ return;
+ }
+ component = new ReactRenderer(MentionList, {
+ props: { ...props, mentionSuggestions },
+ editor: props.editor,
+ });
+ props.editor.storage.mentionsOpen = true;
+ // @ts-expect-error - Tippy types are incorrect
+ popup = tippy("body", {
+ getReferenceClientRect: props.clientRect,
+ appendTo: () => document.querySelector(".active-editor") ?? document.querySelector("#editor-container"),
+ content: component.element,
+ showOnCreate: true,
+ interactive: true,
+ trigger: "manual",
+ placement: "bottom-start",
+ });
+ },
+ onUpdate: (props: { editor: Editor; clientRect: DOMRect }) => {
+ component?.updateProps(props);
+
+ if (!props.clientRect) {
+ return;
+ }
+
+ popup &&
+ popup[0].setProps({
+ getReferenceClientRect: props.clientRect,
+ });
+ },
+
+ onKeyDown: (props: { event: KeyboardEvent }) => {
+ if (props.event.key === "Escape") {
+ popup?.[0].hide();
+
+ return true;
+ }
+
+ const navigationKeys = ["ArrowUp", "ArrowDown", "Enter"];
+
+ if (navigationKeys.includes(props.event.key)) {
+ // @ts-expect-error - Tippy types are incorrect
+ component?.ref?.onKeyDown(props);
+ event?.stopPropagation();
+ return true;
+ }
+ return false;
+ },
+ onExit: (props: { editor: Editor; event: KeyboardEvent }) => {
+ props.editor.storage.mentionsOpen = false;
+ popup?.[0].destroy();
+ component?.destroy();
+ },
+ };
+ },
+ },
});
diff --git a/packages/editor/core/src/ui/mentions/mention-list.tsx b/packages/editor/core/src/ui/mentions/mention-list.tsx
index afbf109702..cd0bf83547 100644
--- a/packages/editor/core/src/ui/mentions/mention-list.tsx
+++ b/packages/editor/core/src/ui/mentions/mention-list.tsx
@@ -1,36 +1,106 @@
import { Editor } from "@tiptap/react";
-import { forwardRef, useEffect, useImperativeHandle, useState } from "react";
+import { forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef, useState } from "react";
+import { cn } from "src/lib/utils";
import { IMentionSuggestion } from "src/types/mention-suggestion";
+import { v4 as uuidv4 } from "uuid";
+import { Avatar } from "@plane/ui";
interface MentionListProps {
- items: IMentionSuggestion[];
- command: (item: { id: string; label: string; target: string; redirect_uri: string }) => void;
+ command: (item: {
+ id: string;
+ label: string;
+ entity_name: string;
+ entity_identifier: string;
+ target: string;
+ redirect_uri: string;
+ }) => void;
+ query: string;
editor: Editor;
+ mentionSuggestions: () => Promise<IMentionSuggestion[]>;
}
-// eslint-disable-next-line react/display-name
export const MentionList = forwardRef((props: MentionListProps, ref) => {
+ const { query, mentionSuggestions } = props;
+ const [items, setItems] = useState<IMentionSuggestion[]>([]);
const [selectedIndex, setSelectedIndex] = useState(0);
+ const [isLoading, setIsLoading] = useState(false);
+
+ useEffect(() => {
+ const fetchSuggestions = async () => {
+ setIsLoading(true);
+ try {
+ const suggestions = await mentionSuggestions();
+ const mappedSuggestions: IMentionSuggestion[] = suggestions.map((suggestion): IMentionSuggestion => {
+ const transactionId = uuidv4();
+ return {
+ ...suggestion,
+ id: transactionId,
+ };
+ });
+
+ const filteredSuggestions = mappedSuggestions.filter((suggestion) =>
+ suggestion.title.toLowerCase().startsWith(query.toLowerCase())
+ );
+
+ setItems(filteredSuggestions);
+ } catch (error) {
+ console.error("Failed to fetch suggestions:", error);
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ fetchSuggestions();
+ }, [query, mentionSuggestions]);
const selectItem = (index: number) => {
- const item = props.items[index];
-
- if (item) {
- props.command({
- id: item.id,
- label: item.title,
- target: "users",
- redirect_uri: item.redirect_uri,
- });
+ try {
+ const item = items[index];
+
+ if (item) {
+ props.command({
+ id: item.id,
+ label: item.title,
+ entity_identifier: item.entity_identifier,
+ entity_name: item.entity_name,
+ target: "users",
+ redirect_uri: item.redirect_uri,
+ });
+ }
+ } catch (error) {
+ console.error("Error selecting item:", error);
}
};
+ const commandListContainer = useRef<HTMLDivElement>(null);
+
+ useLayoutEffect(() => {
+ const container = commandListContainer?.current;
+
+ const item = container?.children[selectedIndex] as HTMLElement;
+
+ if (item && container) updateScrollView(container, item);
+ }, [selectedIndex]);
+
+ const updateScrollView = (container: HTMLElement, item: HTMLElement) => {
+ const containerHeight = container.offsetHeight;
+ const itemHeight = item ? item.offsetHeight : 0;
+
+ const top = item.offsetTop;
+ const bottom = top + itemHeight;
+
+ if (top < container.scrollTop) {
+ container.scrollTop -= container.scrollTop - top + 5;
+ } else if (bottom > containerHeight + container.scrollTop) {
+ container.scrollTop += bottom - containerHeight - container.scrollTop + 5;
+ }
+ };
const upHandler = () => {
- setSelectedIndex((selectedIndex + props.items.length - 1) % props.items.length);
+ setSelectedIndex((selectedIndex + items.length - 1) % items.length);
};
const downHandler = () => {
- setSelectedIndex((selectedIndex + 1) % props.items.length);
+ setSelectedIndex((selectedIndex + 1) % items.length);
};
const enterHandler = () => {
@@ -39,7 +109,7 @@ export const MentionList = forwardRef((props: MentionListProps, ref) => {
useEffect(() => {
setSelectedIndex(0);
- }, [props.items]);
+ }, [items]);
useImperativeHandle(ref, () => ({
onKeyDown: ({ event }: { event: KeyboardEvent }) => {
@@ -62,38 +132,33 @@ export const MentionList = forwardRef((props: MentionListProps, ref) => {
},
}));
- return props.items && props.items.length !== 0 ? (
- <div className="mentions absolute max-h-40 w-48 space-y-0.5 overflow-y-auto rounded-md bg-custom-background-100 p-1 text-sm text-custom-text-300 shadow-custom-shadow-sm">
- {props.items.length ? (
- props.items.map((item, index) => (
+ return (
+ <div
+ ref={commandListContainer}
+ className="mentions absolute max-h-48 min-w-[12rem] rounded-md bg-custom-background-100 border-[0.5px] border-custom-border-300 px-2 py-2.5 text-xs shadow-custom-shadow-rg overflow-y-scroll"
+ >
+ {isLoading ? (
+ <div className="text-center text-custom-text-400">Loading...</div>
+ ) : items.length ? (
+ items.map((item, index) => (
<div
key={item.id}
- className={`flex cursor-pointer items-center gap-2 rounded p-1 hover:bg-custom-background-80 ${
- index === selectedIndex ? "bg-custom-background-80" : ""
- }`}
+ className={cn(
+ "flex cursor-pointer items-center gap-2 rounded px-1 py-1.5 hover:bg-custom-background-80 text-custom-text-200",
+ {
+ "bg-custom-background-80": index === selectedIndex,
+ }
+ )}
onClick={() => selectItem(index)}
>
- <div className="grid h-4 w-4 flex-shrink-0 place-items-center overflow-hidden">
- {item.avatar && item.avatar.trim() !== "" ? (
- <img src={item.avatar} className="h-full w-full rounded-sm object-cover" alt={item.title} />
- ) : (
- <div className="grid h-full w-full place-items-center rounded-sm bg-gray-700 text-xs capitalize text-white">
- {item.title[0]}
- </div>
- )}
- </div>
- <div className="flex-grow space-y-1 truncate">
- <p className="truncate text-sm font-medium">{item.title}</p>
- {/* <p className="text-xs text-gray-400">{item.subtitle}</p> */}
- </div>
+ <Avatar name={item?.title} src={item?.avatar} />
+ <span className="flex-grow truncate">{item.title}</span>
</div>
))
) : (
- <div className="item">No result</div>
+ <div className="text-center text-custom-text-400">No results</div>
)}
</div>
- ) : (
- <></>
);
});
diff --git a/packages/editor/core/src/ui/mentions/mention-node-view.tsx b/packages/editor/core/src/ui/mentions/mention-node-view.tsx
index 1c3755f6c6..0a1f1b5e0c 100644
--- a/packages/editor/core/src/ui/mentions/mention-node-view.tsx
+++ b/packages/editor/core/src/ui/mentions/mention-node-view.tsx
@@ -4,11 +4,21 @@ import { NodeViewWrapper } from "@tiptap/react";
import { cn } from "src/lib/utils";
import { useRouter } from "next/router";
import { IMentionHighlight } from "src/types/mention-suggestion";
+import { useEffect, useState } from "react";
// eslint-disable-next-line import/no-anonymous-default-export
export const MentionNodeView = (props) => {
const router = useRouter();
- const highlights = props.extension.options.mentionHighlights as IMentionHighlight[];
+ const [highlightsState, setHighlightsState] = useState<IMentionHighlight[]>();
+
+ useEffect(() => {
+ if (!props.extension.options.mentionHighlights) return;
+ const hightlights = async () => {
+ const userId = await props.extension.options.mentionHighlights();
+ setHighlightsState(userId);
+ };
+ hightlights();
+ }, [props.extension.options]);
const handleClick = () => {
if (!props.extension.options.readonly) {
@@ -20,13 +30,12 @@ export const MentionNodeView = (props) => {
<NodeViewWrapper className="mention-component inline w-fit">
<span
className={cn("mention rounded bg-custom-primary-100/20 px-1 py-0.5 font-medium text-custom-primary-100", {
- "bg-yellow-500/20 text-yellow-500": highlights ? highlights.includes(props.node.attrs.id) : false,
+ "bg-yellow-500/20 text-yellow-500": highlightsState
+ ? highlightsState.includes(props.node.attrs.entity_identifier)
+ : false,
"cursor-pointer": !props.extension.options.readonly,
- // "hover:bg-custom-primary-300" : !props.extension.options.readonly && !highlights.includes(props.node.attrs.id)
})}
onClick={handleClick}
- data-mention-target={props.node.attrs.target}
- data-mention-id={props.node.attrs.id}
>
@{props.node.attrs.label}
</span>
diff --git a/packages/editor/core/src/ui/mentions/suggestion.ts b/packages/editor/core/src/ui/mentions/suggestion.ts
index 3f1b8eeecc..8eaf0982f4 100644
--- a/packages/editor/core/src/ui/mentions/suggestion.ts
+++ b/packages/editor/core/src/ui/mentions/suggestion.ts
@@ -1,66 +1,17 @@
-import { ReactRenderer } from "@tiptap/react";
-import { Editor } from "@tiptap/core";
-import tippy from "tippy.js";
-
-import { MentionList } from "src/ui/mentions/mention-list";
+import { v4 as uuidv4 } from "uuid";
import { IMentionSuggestion } from "src/types/mention-suggestion";
-export const Suggestion = (suggestions: IMentionSuggestion[]) => ({
- items: ({ query }: { query: string }) =>
- suggestions.filter((suggestion) => suggestion.title.toLowerCase().startsWith(query.toLowerCase())).slice(0, 5),
- render: () => {
- let reactRenderer: ReactRenderer | null = null;
- let popup: any | null = null;
-
- return {
- onStart: (props: { editor: Editor; clientRect: DOMRect }) => {
- props.editor.storage.mentionsOpen = true;
- reactRenderer = new ReactRenderer(MentionList, {
- props,
- editor: props.editor,
- });
- // @ts-ignore
- popup = tippy("body", {
- getReferenceClientRect: props.clientRect,
- appendTo: () => document.querySelector(".active-editor") ?? document.querySelector("#editor-container"),
- content: reactRenderer.element,
- showOnCreate: true,
- interactive: true,
- trigger: "manual",
- placement: "bottom-start",
- });
- },
-
- onUpdate: (props: { editor: Editor; clientRect: DOMRect }) => {
- reactRenderer?.updateProps(props);
-
- popup &&
- popup[0].setProps({
- getReferenceClientRect: props.clientRect,
- });
- },
- onKeyDown: (props: { event: KeyboardEvent }) => {
- if (props.event.key === "Escape") {
- popup?.[0].hide();
-
- return true;
- }
-
- const navigationKeys = ["ArrowUp", "ArrowDown", "Enter"];
-
- if (navigationKeys.includes(props.event.key)) {
- // @ts-ignore
- reactRenderer?.ref?.onKeyDown(props);
- event?.stopPropagation();
- return true;
- }
- return false;
- },
- onExit: (props: { editor: Editor; event: KeyboardEvent }) => {
- props.editor.storage.mentionsOpen = false;
- popup?.[0].destroy();
- reactRenderer?.destroy();
- },
- };
- },
-});
+export const getSuggestionItems =
+ (suggestions: IMentionSuggestion[]) =>
+ ({ query }: { query: string }) => {
+ const mappedSuggestions: IMentionSuggestion[] = suggestions.map((suggestion): IMentionSuggestion => {
+ const transactionId = uuidv4();
+ return {
+ ...suggestion,
+ id: transactionId,
+ };
+ });
+ return mappedSuggestions
+ .filter((suggestion) => suggestion.title.toLowerCase().startsWith(query.toLowerCase()))
+ .slice(0, 5);
+ };
diff --git a/packages/editor/core/src/ui/menus/menu-items/index.tsx b/packages/editor/core/src/ui/menus/menu-items/index.tsx
index f60febc59d..66736e0ea7 100644
--- a/packages/editor/core/src/ui/menus/menu-items/index.tsx
+++ b/packages/editor/core/src/ui/menus/menu-items/index.tsx
@@ -33,6 +33,7 @@ import {
} from "src/lib/editor-commands";
import { LucideIconType } from "src/types/lucide-icon";
import { UploadImage } from "src/types/upload-image";
+import { Selection } from "@tiptap/pm/state";
export interface EditorMenuItem {
name: string;
@@ -41,104 +42,142 @@ export interface EditorMenuItem {
icon: LucideIconType;
}
-export const HeadingOneItem = (editor: Editor): EditorMenuItem => ({
- name: "H1",
- isActive: () => editor.isActive("heading", { level: 1 }),
- command: () => toggleHeadingOne(editor),
- icon: Heading1,
-});
-
-export const HeadingTwoItem = (editor: Editor): EditorMenuItem => ({
- name: "H2",
- isActive: () => editor.isActive("heading", { level: 2 }),
- command: () => toggleHeadingTwo(editor),
- icon: Heading2,
-});
-
-export const HeadingThreeItem = (editor: Editor): EditorMenuItem => ({
- name: "H3",
- isActive: () => editor.isActive("heading", { level: 3 }),
- command: () => toggleHeadingThree(editor),
- icon: Heading3,
-});
-
-export const BoldItem = (editor: Editor): EditorMenuItem => ({
- name: "bold",
- isActive: () => editor?.isActive("bold"),
- command: () => toggleBold(editor),
- icon: BoldIcon,
-});
-
-export const ItalicItem = (editor: Editor): EditorMenuItem => ({
- name: "italic",
- isActive: () => editor?.isActive("italic"),
- command: () => toggleItalic(editor),
- icon: ItalicIcon,
-});
-
-export const UnderLineItem = (editor: Editor): EditorMenuItem => ({
- name: "underline",
- isActive: () => editor?.isActive("underline"),
- command: () => toggleUnderline(editor),
- icon: UnderlineIcon,
-});
-
-export const StrikeThroughItem = (editor: Editor): EditorMenuItem => ({
- name: "strike",
- isActive: () => editor?.isActive("strike"),
- command: () => toggleStrike(editor),
- icon: StrikethroughIcon,
-});
-
-export const BulletListItem = (editor: Editor): EditorMenuItem => ({
- name: "bullet-list",
- isActive: () => editor?.isActive("bulletList"),
- command: () => toggleBulletList(editor),
- icon: ListIcon,
-});
-
-export const TodoListItem = (editor: Editor): EditorMenuItem => ({
- name: "To-do List",
- isActive: () => editor.isActive("taskItem"),
- command: () => toggleTaskList(editor),
- icon: CheckSquare,
-});
-
-export const CodeItem = (editor: Editor): EditorMenuItem => ({
- name: "code",
- isActive: () => editor?.isActive("code") || editor?.isActive("codeBlock"),
- command: () => toggleCodeBlock(editor),
- icon: CodeIcon,
-});
-
-export const NumberedListItem = (editor: Editor): EditorMenuItem => ({
- name: "ordered-list",
- isActive: () => editor?.isActive("orderedList"),
- command: () => toggleOrderedList(editor),
- icon: ListOrderedIcon,
-});
-
-export const QuoteItem = (editor: Editor): EditorMenuItem => ({
- name: "quote",
- isActive: () => editor?.isActive("blockquote"),
- command: () => toggleBlockquote(editor),
- icon: QuoteIcon,
-});
-
-export const TableItem = (editor: Editor): EditorMenuItem => ({
- name: "table",
- isActive: () => editor?.isActive("table"),
- command: () => insertTableCommand(editor),
- icon: TableIcon,
-});
-
-export const ImageItem = (
- editor: Editor,
- uploadFile: UploadImage,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
-): EditorMenuItem => ({
- name: "image",
- isActive: () => editor?.isActive("image"),
- command: () => insertImageCommand(editor, uploadFile, setIsSubmitting),
- icon: ImageIcon,
-});
+export const HeadingOneItem = (editor: Editor) =>
+ ({
+ name: "H1",
+ isActive: () => editor.isActive("heading", { level: 1 }),
+ command: () => toggleHeadingOne(editor),
+ icon: Heading1,
+ }) as const satisfies EditorMenuItem;
+
+export const HeadingTwoItem = (editor: Editor) =>
+ ({
+ name: "H2",
+ isActive: () => editor.isActive("heading", { level: 2 }),
+ command: () => toggleHeadingTwo(editor),
+ icon: Heading2,
+ }) as const satisfies EditorMenuItem;
+
+export const HeadingThreeItem = (editor: Editor) =>
+ ({
+ name: "H3",
+ isActive: () => editor.isActive("heading", { level: 3 }),
+ command: () => toggleHeadingThree(editor),
+ icon: Heading3,
+ }) as const satisfies EditorMenuItem;
+
+export const BoldItem = (editor: Editor) =>
+ ({
+ name: "bold",
+ isActive: () => editor?.isActive("bold"),
+ command: () => toggleBold(editor),
+ icon: BoldIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const ItalicItem = (editor: Editor) =>
+ ({
+ name: "italic",
+ isActive: () => editor?.isActive("italic"),
+ command: () => toggleItalic(editor),
+ icon: ItalicIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const UnderLineItem = (editor: Editor) =>
+ ({
+ name: "underline",
+ isActive: () => editor?.isActive("underline"),
+ command: () => toggleUnderline(editor),
+ icon: UnderlineIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const StrikeThroughItem = (editor: Editor) =>
+ ({
+ name: "strike",
+ isActive: () => editor?.isActive("strike"),
+ command: () => toggleStrike(editor),
+ icon: StrikethroughIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const BulletListItem = (editor: Editor) =>
+ ({
+ name: "bullet-list",
+ isActive: () => editor?.isActive("bulletList"),
+ command: () => toggleBulletList(editor),
+ icon: ListIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const TodoListItem = (editor: Editor) =>
+ ({
+ name: "To-do List",
+ isActive: () => editor.isActive("taskItem"),
+ command: () => toggleTaskList(editor),
+ icon: CheckSquare,
+ }) as const satisfies EditorMenuItem;
+
+export const CodeItem = (editor: Editor) =>
+ ({
+ name: "code",
+ isActive: () => editor?.isActive("code") || editor?.isActive("codeBlock"),
+ command: () => toggleCodeBlock(editor),
+ icon: CodeIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const NumberedListItem = (editor: Editor) =>
+ ({
+ name: "ordered-list",
+ isActive: () => editor?.isActive("orderedList"),
+ command: () => toggleOrderedList(editor),
+ icon: ListOrderedIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const QuoteItem = (editor: Editor) =>
+ ({
+ name: "quote",
+ isActive: () => editor?.isActive("blockquote"),
+ command: () => toggleBlockquote(editor),
+ icon: QuoteIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const TableItem = (editor: Editor) =>
+ ({
+ name: "table",
+ isActive: () => editor?.isActive("table"),
+ command: () => insertTableCommand(editor),
+ icon: TableIcon,
+ }) as const satisfies EditorMenuItem;
+
+export const ImageItem = (editor: Editor, uploadFile: UploadImage) =>
+ ({
+ name: "image",
+ isActive: () => editor?.isActive("image"),
+ command: (savedSelection: Selection | null) => insertImageCommand(editor, uploadFile, savedSelection),
+ icon: ImageIcon,
+ }) as const;
+
+export function getEditorMenuItems(editor: Editor | null, uploadFile: UploadImage) {
+ if (!editor) {
+ return [];
+ }
+ return [
+ HeadingOneItem(editor),
+ HeadingTwoItem(editor),
+ HeadingThreeItem(editor),
+ BoldItem(editor),
+ ItalicItem(editor),
+ UnderLineItem(editor),
+ StrikeThroughItem(editor),
+ BulletListItem(editor),
+ TodoListItem(editor),
+ CodeItem(editor),
+ NumberedListItem(editor),
+ QuoteItem(editor),
+ TableItem(editor),
+ ImageItem(editor, uploadFile),
+ ];
+}
+
+export type EditorMenuItemNames = ReturnType<typeof getEditorMenuItems> extends (infer U)[]
+ ? U extends { name: infer N }
+ ? N
+ : never
+ : never;
diff --git a/packages/editor/core/src/ui/plugins/delete-image.tsx b/packages/editor/core/src/ui/plugins/delete-image.tsx
index afe13730ae..03b4dbd10f 100644
--- a/packages/editor/core/src/ui/plugins/delete-image.tsx
+++ b/packages/editor/core/src/ui/plugins/delete-image.tsx
@@ -57,10 +57,7 @@ export const TrackImageDeletionPlugin = (deleteImage: DeleteImage): Plugin =>
export async function onNodeDeleted(src: string, deleteImage: DeleteImage): Promise<void> {
try {
const assetUrlWithWorkspaceId = new URL(src).pathname.substring(1);
- const resStatus = await deleteImage(assetUrlWithWorkspaceId);
- if (resStatus === 204) {
- console.log("Image deleted successfully");
- }
+ await deleteImage(assetUrlWithWorkspaceId);
} catch (error) {
console.error("Error deleting image: ", error);
}
@@ -69,10 +66,7 @@ export async function onNodeDeleted(src: string, deleteImage: DeleteImage): Prom
export async function onNodeRestored(src: string, restoreImage: RestoreImage): Promise<void> {
try {
const assetUrlWithWorkspaceId = new URL(src).pathname.substring(1);
- const resStatus = await restoreImage(assetUrlWithWorkspaceId);
- if (resStatus === 204) {
- console.log("Image restored successfully");
- }
+ await restoreImage(assetUrlWithWorkspaceId);
} catch (error) {
console.error("Error restoring image: ", error);
}
diff --git a/packages/editor/core/src/ui/plugins/upload-image.tsx b/packages/editor/core/src/ui/plugins/upload-image.tsx
index 738653d713..3f6a40bf99 100644
--- a/packages/editor/core/src/ui/plugins/upload-image.tsx
+++ b/packages/editor/core/src/ui/plugins/upload-image.tsx
@@ -21,7 +21,7 @@ export const UploadImagesPlugin = (cancelUploadImage?: () => any) =>
const placeholder = document.createElement("div");
placeholder.setAttribute("class", "img-placeholder");
const image = document.createElement("img");
- image.setAttribute("class", "opacity-10 rounded-lg border border-custom-border-300");
+ image.setAttribute("class", "opacity-60 rounded-lg border border-custom-border-300");
image.src = src;
placeholder.appendChild(image);
@@ -73,13 +73,7 @@ const removePlaceholder = (view: EditorView, id: {}) => {
view.dispatch(removePlaceholderTr);
};
-export async function startImageUpload(
- file: File,
- view: EditorView,
- pos: number,
- uploadFile: UploadImage,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
-) {
+export async function startImageUpload(file: File, view: EditorView, pos: number, uploadFile: UploadImage) {
if (!file) {
alert("No file selected. Please select a file to upload.");
return;
@@ -120,7 +114,7 @@ export async function startImageUpload(
return;
};
- setIsSubmitting?.("submitting");
+ // setIsSubmitting?.("submitting");
try {
const src = await UploadImageHandler(file, uploadFile);
@@ -134,6 +128,7 @@ export async function startImageUpload(
const transaction = view.state.tr.insert(pos - 1, node).setMeta(uploadKey, { remove: { id } });
view.dispatch(transaction);
+ view.focus();
} catch (error) {
console.error("Upload error: ", error);
removePlaceholder(view, id);
diff --git a/packages/editor/core/src/ui/props.tsx b/packages/editor/core/src/ui/props.tsx
index 1846efe475..aa88fa042e 100644
--- a/packages/editor/core/src/ui/props.tsx
+++ b/packages/editor/core/src/ui/props.tsx
@@ -1,15 +1,15 @@
import { EditorProps } from "@tiptap/pm/view";
-import { findTableAncestor } from "src/lib/utils";
+import { cn, findTableAncestor } from "src/lib/utils";
import { UploadImage } from "src/types/upload-image";
import { startImageUpload } from "src/ui/plugins/upload-image";
-export function CoreEditorProps(
- uploadFile: UploadImage,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
-): EditorProps {
+export function CoreEditorProps(uploadFile: UploadImage, editorClassName: string): EditorProps {
return {
attributes: {
- class: `prose prose-brand max-w-full prose-headings:font-display font-default focus:outline-none`,
+ class: cn(
+ "prose prose-brand max-w-full prose-headings:font-display font-default focus:outline-none",
+ editorClassName
+ ),
},
handleDOMEvents: {
keydown: (_view, event) => {
@@ -36,7 +36,7 @@ export function CoreEditorProps(
event.preventDefault();
const file = event.clipboardData.files[0];
const pos = view.state.selection.from;
- startImageUpload(file, view, pos, uploadFile, setIsSubmitting);
+ startImageUpload(file, view, pos, uploadFile);
return true;
}
return false;
@@ -50,7 +50,7 @@ export function CoreEditorProps(
top: event.clientY,
});
if (coordinates) {
- startImageUpload(file, view, coordinates.pos - 1, uploadFile, setIsSubmitting);
+ startImageUpload(file, view, coordinates.pos - 1, uploadFile);
}
return true;
}
diff --git a/packages/editor/core/src/ui/read-only/extensions.tsx b/packages/editor/core/src/ui/read-only/extensions.tsx
index 93e1b38872..cf12880f8d 100644
--- a/packages/editor/core/src/ui/read-only/extensions.tsx
+++ b/packages/editor/core/src/ui/read-only/extensions.tsx
@@ -14,7 +14,7 @@ import { TableRow } from "src/ui/extensions/table/table-row/table-row";
import { ReadOnlyImageExtension } from "src/ui/extensions/image/read-only-image";
import { isValidHttpUrl } from "src/lib/utils";
import { Mentions } from "src/ui/mentions";
-import { IMentionSuggestion } from "src/types/mention-suggestion";
+import { IMentionHighlight } from "src/types/mention-suggestion";
import { CustomLinkExtension } from "src/ui/extensions/custom-link";
import { CustomHorizontalRule } from "src/ui/extensions/horizontal-rule/horizontal-rule";
import { CustomQuoteExtension } from "src/ui/extensions/quote";
@@ -23,23 +23,22 @@ import { CustomCodeBlockExtension } from "src/ui/extensions/code";
import { CustomCodeInlineExtension } from "src/ui/extensions/code-inline";
export const CoreReadOnlyEditorExtensions = (mentionConfig: {
- mentionSuggestions: IMentionSuggestion[];
- mentionHighlights: string[];
+ mentionHighlights?: () => Promise<IMentionHighlight[]>;
}) => [
StarterKit.configure({
bulletList: {
HTMLAttributes: {
- class: "list-disc list-outside leading-3 -mt-2",
+ class: "list-disc pl-7 space-y-2",
},
},
orderedList: {
HTMLAttributes: {
- class: "list-decimal list-outside leading-3 -mt-2",
+ class: "list-decimal pl-7 space-y-2",
},
},
listItem: {
HTMLAttributes: {
- class: "leading-normal -mb-2",
+ class: "not-prose space-y-2",
},
},
code: false,
@@ -49,11 +48,9 @@ export const CoreReadOnlyEditorExtensions = (mentionConfig: {
dropcursor: false,
gapcursor: false,
}),
- CustomQuoteExtension.configure({
- HTMLAttributes: { className: "border-l-4 border-custom-border-300" },
- }),
+ CustomQuoteExtension,
CustomHorizontalRule.configure({
- HTMLAttributes: { class: "mt-4 mb-4" },
+ HTMLAttributes: { class: "my-4" },
}),
CustomLinkExtension.configure({
openOnClick: true,
@@ -69,7 +66,7 @@ export const CoreReadOnlyEditorExtensions = (mentionConfig: {
CustomTypographyExtension,
ReadOnlyImageExtension.configure({
HTMLAttributes: {
- class: "rounded-lg border border-custom-border-300",
+ class: "rounded-md",
},
}),
TiptapUnderline,
@@ -77,16 +74,20 @@ export const CoreReadOnlyEditorExtensions = (mentionConfig: {
Color,
TaskList.configure({
HTMLAttributes: {
- class: "not-prose pl-2",
+ class: "not-prose pl-2 space-y-2",
},
}),
TaskItem.configure({
HTMLAttributes: {
- class: "flex items-start my-4",
+ class: "flex pointer-events-none",
},
nested: true,
}),
- CustomCodeBlockExtension,
+ CustomCodeBlockExtension.configure({
+ HTMLAttributes: {
+ class: "bg-custom-background-90 text-custom-text-100 rounded-lg p-8 pl-9 pr-4",
+ },
+ }),
CustomCodeInlineExtension,
Markdown.configure({
html: true,
@@ -96,5 +97,8 @@ export const CoreReadOnlyEditorExtensions = (mentionConfig: {
TableHeader,
TableCell,
TableRow,
- Mentions(mentionConfig.mentionSuggestions, mentionConfig.mentionHighlights, true),
+ Mentions({
+ mentionHighlights: mentionConfig.mentionHighlights,
+ readonly: true,
+ }),
];
diff --git a/packages/editor/core/src/ui/read-only/props.tsx b/packages/editor/core/src/ui/read-only/props.tsx
index 79f9fcb0db..bd9b6713bd 100644
--- a/packages/editor/core/src/ui/read-only/props.tsx
+++ b/packages/editor/core/src/ui/read-only/props.tsx
@@ -1,7 +1,11 @@
import { EditorProps } from "@tiptap/pm/view";
+import { cn } from "src/lib/utils";
-export const CoreReadOnlyEditorProps: EditorProps = {
+export const CoreReadOnlyEditorProps = (editorClassName: string): EditorProps => ({
attributes: {
- class: `prose prose-brand max-w-full prose-headings:font-display font-default focus:outline-none`,
+ class: cn(
+ "prose prose-brand max-w-full prose-headings:font-display font-default focus:outline-none",
+ editorClassName
+ ),
},
-};
+});
diff --git a/packages/editor/document-editor/src/hooks/use-editor-markings.tsx b/packages/editor/document-editor/src/hooks/use-editor-markings.tsx
index 1eb72eaab5..88f125a269 100644
--- a/packages/editor/document-editor/src/hooks/use-editor-markings.tsx
+++ b/packages/editor/document-editor/src/hooks/use-editor-markings.tsx
@@ -1,33 +1,30 @@
-import { useState } from "react";
+import { useCallback, useState } from "react";
import { IMarking } from "src/types/editor-types";
export const useEditorMarkings = () => {
const [markings, setMarkings] = useState<IMarking[]>([]);
- const updateMarkings = (json: any) => {
- const nodes = json.content as any[];
+ const updateMarkings = useCallback((html: string) => {
+ const parser = new DOMParser();
+ const doc = parser.parseFromString(html, "text/html");
+ const headings = doc.querySelectorAll("h1, h2, h3");
const tempMarkings: IMarking[] = [];
let h1Sequence: number = 0;
let h2Sequence: number = 0;
let h3Sequence: number = 0;
- if (nodes) {
- nodes.forEach((node) => {
- if (
- node.type === "heading" &&
- (node.attrs.level === 1 || node.attrs.level === 2 || node.attrs.level === 3) &&
- node.content
- ) {
- tempMarkings.push({
- type: "heading",
- level: node.attrs.level,
- text: node.content[0].text,
- sequence: node.attrs.level === 1 ? ++h1Sequence : node.attrs.level === 2 ? ++h2Sequence : ++h3Sequence,
- });
- }
+
+ headings.forEach((heading) => {
+ const level = parseInt(heading.tagName[1]); // Extract the number from h1, h2, h3
+ tempMarkings.push({
+ type: "heading",
+ level: level,
+ text: heading.textContent || "",
+ sequence: level === 1 ? ++h1Sequence : level === 2 ? ++h2Sequence : ++h3Sequence,
});
- }
+ });
+
setMarkings(tempMarkings);
- };
+ }, []);
return {
updateMarkings,
diff --git a/packages/editor/document-editor/src/index.ts b/packages/editor/document-editor/src/index.ts
index c074009f49..f8eea14ce7 100644
--- a/packages/editor/document-editor/src/index.ts
+++ b/packages/editor/document-editor/src/index.ts
@@ -1,3 +1,9 @@
export { DocumentEditor, DocumentEditorWithRef } from "src/ui";
export { DocumentReadOnlyEditor, DocumentReadOnlyEditorWithRef } from "src/ui/readonly";
-export { FixedMenu } from "src/ui/menu/fixed-menu";
+
+// hooks
+export { useEditorMarkings } from "src/hooks/use-editor-markings";
+
+export type { EditorRefApi, EditorReadOnlyRefApi, EditorMenuItem, EditorMenuItemNames } from "@plane/editor-core";
+
+export type { IMarking } from "src/types/editor-types";
diff --git a/packages/editor/document-editor/src/types/editor-types.ts b/packages/editor/document-editor/src/types/editor-types.ts
index 5a28daf9e2..476642103c 100644
--- a/packages/editor/document-editor/src/types/editor-types.ts
+++ b/packages/editor/document-editor/src/types/editor-types.ts
@@ -1,10 +1,3 @@
-export interface DocumentDetails {
- title: string;
- created_by: string;
- created_on: Date;
- last_updated_by: string;
- last_updated_at: Date;
-}
export interface IMarking {
type: "heading";
level: number;
diff --git a/packages/editor/document-editor/src/ui/components/alert-label.tsx b/packages/editor/document-editor/src/ui/components/alert-label.tsx
deleted file mode 100644
index 69b6dd02d0..0000000000
--- a/packages/editor/document-editor/src/ui/components/alert-label.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { LucideIconType } from "@plane/editor-core";
-
-interface IAlertLabelProps {
- Icon?: LucideIconType;
- backgroundColor: string;
- textColor?: string;
- label: string;
-}
-export const AlertLabel = (props: IAlertLabelProps) => {
- const { Icon, backgroundColor, textColor, label } = props;
-
- return (
- <div
- className={`flex h-7 items-center gap-2 rounded-full px-3 py-0.5 text-xs font-medium ${backgroundColor} ${textColor}`}
- >
- {Icon && <Icon className="h-3 w-3" />}
- <span>{label}</span>
- </div>
- );
-};
diff --git a/packages/editor/document-editor/src/ui/components/content-browser.tsx b/packages/editor/document-editor/src/ui/components/content-browser.tsx
deleted file mode 100644
index 926d9a53de..0000000000
--- a/packages/editor/document-editor/src/ui/components/content-browser.tsx
+++ /dev/null
@@ -1,40 +0,0 @@
-import { HeadingComp, HeadingThreeComp, SubheadingComp } from "src/ui/components/heading-component";
-import { IMarking } from "src/types/editor-types";
-import { Editor } from "@tiptap/react";
-import { scrollSummary } from "src/utils/editor-summary-utils";
-
-interface ContentBrowserProps {
- editor: Editor;
- markings: IMarking[];
- setSidePeekVisible?: (sidePeekState: boolean) => void;
-}
-
-export const ContentBrowser = (props: ContentBrowserProps) => {
- const { editor, markings, setSidePeekVisible } = props;
-
- const handleOnClick = (marking: IMarking) => {
- scrollSummary(editor, marking);
- if (setSidePeekVisible) setSidePeekVisible(false);
- };
-
- return (
- <div className="flex h-full flex-col overflow-hidden">
- <h2 className="font-medium">Outline</h2>
- <div className="h-full overflow-y-auto">
- {markings.length !== 0 ? (
- markings.map((marking) =>
- marking.level === 1 ? (
- <HeadingComp onClick={() => handleOnClick(marking)} heading={marking.text} />
- ) : marking.level === 2 ? (
- <SubheadingComp onClick={() => handleOnClick(marking)} subHeading={marking.text} />
- ) : (
- <HeadingThreeComp heading={marking.text} onClick={() => handleOnClick(marking)} />
- )
- )
- ) : (
- <p className="mt-3 text-xs text-custom-text-400">Headings will be displayed here for navigation</p>
- )}
- </div>
- </div>
- );
-};
diff --git a/packages/editor/document-editor/src/ui/components/editor-header.tsx b/packages/editor/document-editor/src/ui/components/editor-header.tsx
deleted file mode 100644
index 33ac4a0dc6..0000000000
--- a/packages/editor/document-editor/src/ui/components/editor-header.tsx
+++ /dev/null
@@ -1,99 +0,0 @@
-import { Editor } from "@tiptap/react";
-import { Archive, RefreshCw, Lock } from "lucide-react";
-import { IMarking, DocumentDetails } from "src/types/editor-types";
-import { FixedMenu } from "src/ui/menu";
-import { UploadImage } from "@plane/editor-core";
-import { AlertLabel } from "src/ui/components/alert-label";
-import { IVerticalDropdownItemProps, VerticalDropdownMenu } from "src/ui/components/vertical-dropdown-menu";
-import { SummaryPopover } from "src/ui/components/summary-popover";
-import { InfoPopover } from "src/ui/components/info-popover";
-import { getDate } from "src/utils/date-utils";
-
-interface IEditorHeader {
- editor: Editor;
- KanbanMenuOptions: IVerticalDropdownItemProps[];
- sidePeekVisible: boolean;
- setSidePeekVisible: (sidePeekState: boolean) => void;
- markings: IMarking[];
- isLocked: boolean;
- isArchived: boolean;
- archivedAt?: Date;
- readonly: boolean;
- uploadFile?: UploadImage;
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
- documentDetails: DocumentDetails;
- isSubmitting?: "submitting" | "submitted" | "saved";
-}
-
-export const EditorHeader = (props: IEditorHeader) => {
- const {
- documentDetails,
- archivedAt,
- editor,
- sidePeekVisible,
- readonly,
- setSidePeekVisible,
- markings,
- uploadFile,
- setIsSubmitting,
- KanbanMenuOptions,
- isArchived,
- isLocked,
- isSubmitting,
- } = props;
-
- return (
- <div className="flex items-center border-b border-custom-border-200 md:px-5 px-3 py-2">
- <div className="md:w-56 flex-shrink-0 lg:w-72 w-fit">
- <SummaryPopover
- editor={editor}
- markings={markings}
- sidePeekVisible={sidePeekVisible}
- setSidePeekVisible={setSidePeekVisible}
- />
- </div>
-
- <div className="flex-shrink-0 hidden md:flex">
- {!readonly && uploadFile && (
- <FixedMenu editor={editor} uploadFile={uploadFile} setIsSubmitting={setIsSubmitting} />
- )}
- </div>
-
- <div className="flex flex-grow items-center justify-end gap-3">
- {isLocked && (
- <AlertLabel
- Icon={Lock}
- backgroundColor="bg-custom-background-80"
- textColor="text-custom-text-300"
- label="Locked"
- />
- )}
- {isArchived && archivedAt && (
- <AlertLabel
- Icon={Archive}
- backgroundColor="bg-blue-500/20"
- textColor="text-blue-500"
- label={`Archived at ${getDate(archivedAt)?.toLocaleString()}`}
- />
- )}
-
- {!isLocked && !isArchived ? (
- <div
- className={`absolute right-[120px] flex items-center gap-x-2 transition-all duration-300 ${
- isSubmitting === "saved" ? "fadeOut" : "fadeIn"
- }`}
- >
- {isSubmitting !== "submitted" && isSubmitting !== "saved" && (
- <RefreshCw className="h-4 w-4 stroke-custom-text-300" />
- )}
- <span className="text-sm text-custom-text-300">
- {isSubmitting === "submitting" ? "Saving..." : "Saved"}
- </span>
- </div>
- ) : null}
- {!isArchived && <InfoPopover documentDetails={documentDetails} />}
- <VerticalDropdownMenu items={KanbanMenuOptions} />
- </div>
- </div>
- );
-};
diff --git a/packages/editor/document-editor/src/ui/components/heading-component.tsx b/packages/editor/document-editor/src/ui/components/heading-component.tsx
deleted file mode 100644
index ce3489418f..0000000000
--- a/packages/editor/document-editor/src/ui/components/heading-component.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-export const HeadingComp = ({
- heading,
- onClick,
-}: {
- heading: string;
- onClick: (event: React.MouseEvent<HTMLParagraphElement, MouseEvent>) => void;
-}) => (
- <h3
- onClick={onClick}
- className="ml-4 mt-3 cursor-pointer text-sm font-medium leading-[125%] tracking-tight hover:text-custom-primary max-md:ml-2.5"
- role="button"
- >
- {heading}
- </h3>
-);
-
-export const SubheadingComp = ({
- subHeading,
- onClick,
-}: {
- subHeading: string;
- onClick: (event: React.MouseEvent<HTMLParagraphElement, MouseEvent>) => void;
-}) => (
- <p
- onClick={onClick}
- className="ml-6 mt-2 cursor-pointer text-xs font-medium tracking-tight text-gray-400 hover:text-custom-primary"
- role="button"
- >
- {subHeading}
- </p>
-);
-
-export const HeadingThreeComp = ({
- heading,
- onClick,
-}: {
- heading: string;
- onClick: (event: React.MouseEvent<HTMLParagraphElement, MouseEvent>) => void;
-}) => (
- <p
- onClick={onClick}
- className="ml-8 mt-2 cursor-pointer text-xs font-medium tracking-tight text-gray-400 hover:text-custom-primary"
- role="button"
- >
- {heading}
- </p>
-);
diff --git a/packages/editor/document-editor/src/ui/components/index.ts b/packages/editor/document-editor/src/ui/components/index.ts
index 1496a3cf4f..4d2d76baac 100644
--- a/packages/editor/document-editor/src/ui/components/index.ts
+++ b/packages/editor/document-editor/src/ui/components/index.ts
@@ -1,9 +1 @@
-export * from "./alert-label";
-export * from "./content-browser";
-export * from "./editor-header";
-export * from "./heading-component";
-export * from "./info-popover";
export * from "./page-renderer";
-export * from "./summary-popover";
-export * from "./summary-side-bar";
-export * from "./vertical-dropdown-menu";
diff --git a/packages/editor/document-editor/src/ui/components/links/link-edit-view.tsx b/packages/editor/document-editor/src/ui/components/links/link-edit-view.tsx
index 9719154399..0cee059dfe 100644
--- a/packages/editor/document-editor/src/ui/components/links/link-edit-view.tsx
+++ b/packages/editor/document-editor/src/ui/components/links/link-edit-view.tsx
@@ -115,11 +115,6 @@ export const LinkEditView = ({
const removeLink = () => {
editor.view.dispatch(editor.state.tr.removeMark(from, to, editor.schema.marks.link));
linkRemoved.current = true;
- viewProps.onActionCompleteHandler({
- title: "Link successfully removed",
- message: "The link was removed from the text.",
- type: "success",
- });
viewProps.closeLinkView();
};
diff --git a/packages/editor/document-editor/src/ui/components/links/link-preview.tsx b/packages/editor/document-editor/src/ui/components/links/link-preview.tsx
index ff3fd0263b..0bb719d93a 100644
--- a/packages/editor/document-editor/src/ui/components/links/link-preview.tsx
+++ b/packages/editor/document-editor/src/ui/components/links/link-preview.tsx
@@ -12,21 +12,11 @@ export const LinkPreview = ({
const removeLink = () => {
editor.view.dispatch(editor.state.tr.removeMark(from, to, editor.schema.marks.link));
- viewProps.onActionCompleteHandler({
- title: "Link successfully removed",
- message: "The link was removed from the text.",
- type: "success",
- });
viewProps.closeLinkView();
};
const copyLinkToClipboard = () => {
navigator.clipboard.writeText(url);
- viewProps.onActionCompleteHandler({
- title: "Link successfully copied",
- message: "The link was copied to the clipboard.",
- type: "success",
- });
viewProps.closeLinkView();
};
diff --git a/packages/editor/document-editor/src/ui/components/links/link-view.tsx b/packages/editor/document-editor/src/ui/components/links/link-view.tsx
index f1d22a68e2..9befc514cf 100644
--- a/packages/editor/document-editor/src/ui/components/links/link-view.tsx
+++ b/packages/editor/document-editor/src/ui/components/links/link-view.tsx
@@ -11,11 +11,6 @@ export interface LinkViewProps {
to: number;
url: string;
closeLinkView: () => void;
- onActionCompleteHandler: (action: {
- title: string;
- message: string;
- type: "success" | "error" | "warning" | "info";
- }) => void;
}
export const LinkView = (props: LinkViewProps & { style: CSSProperties }) => {
diff --git a/packages/editor/document-editor/src/ui/components/page-renderer.tsx b/packages/editor/document-editor/src/ui/components/page-renderer.tsx
index 7c2717e807..a6b5eb5e8a 100644
--- a/packages/editor/document-editor/src/ui/components/page-renderer.tsx
+++ b/packages/editor/document-editor/src/ui/components/page-renderer.tsx
@@ -1,9 +1,8 @@
+import { useCallback, useRef, useState } from "react";
import { EditorContainer, EditorContentWrapper } from "@plane/editor-core";
import { Node } from "@tiptap/pm/model";
import { EditorView } from "@tiptap/pm/view";
import { Editor, ReactRenderer } from "@tiptap/react";
-import { useCallback, useRef, useState } from "react";
-import { DocumentDetails } from "src/types/editor-types";
import { LinkView, LinkViewProps } from "./links/link-view";
import {
autoUpdate,
@@ -15,40 +14,22 @@ import {
useFloating,
useInteractions,
} from "@floating-ui/react";
+import BlockMenu from "../menu//block-menu";
type IPageRenderer = {
- documentDetails: DocumentDetails;
- updatePageTitle: (title: string) => void;
editor: Editor;
- onActionCompleteHandler: (action: {
- title: string;
- message: string;
- type: "success" | "error" | "warning" | "info";
- }) => void;
- editorClassNames: string;
- editorContentCustomClassNames?: string;
+ editorContainerClassName: string;
hideDragHandle?: () => void;
- readonly: boolean;
tabIndex?: number;
};
export const PageRenderer = (props: IPageRenderer) => {
- const {
- documentDetails,
- tabIndex,
- editor,
- editorClassNames,
- editorContentCustomClassNames,
- updatePageTitle,
- readonly,
- hideDragHandle,
- } = props;
-
- const [pageTitle, setPagetitle] = useState(documentDetails.title);
-
+ const { tabIndex, editor, hideDragHandle, editorContainerClassName } = props;
+ // states
const [linkViewProps, setLinkViewProps] = useState<LinkViewProps>();
const [isOpen, setIsOpen] = useState(false);
const [coordinates, setCoordinates] = useState<{ x: number; y: number }>();
+ const [cleanup, setCleanup] = useState(() => () => {});
const { refs, floatingStyles, context } = useFloating({
open: isOpen,
@@ -63,18 +44,9 @@ export const PageRenderer = (props: IPageRenderer) => {
const { getFloatingProps } = useInteractions([dismiss]);
- const handlePageTitleChange = (title: string) => {
- setPagetitle(title);
- updatePageTitle(title);
- };
-
- const [cleanup, setcleanup] = useState(() => () => {});
-
const floatingElementRef = useRef<HTMLElement | null>(null);
- const closeLinkView = () => {
- setIsOpen(false);
- };
+ const closeLinkView = () => setIsOpen(false);
const handleLinkHover = useCallback(
(event: React.MouseEvent) => {
@@ -137,7 +109,6 @@ export const PageRenderer = (props: IPageRenderer) => {
setCoordinates({ x: x - 300, y: y - 50 });
setIsOpen(true);
setLinkViewProps({
- onActionCompleteHandler: props.onActionCompleteHandler,
closeLinkView: closeLinkView,
view: "LinkPreview",
url: href,
@@ -148,45 +119,32 @@ export const PageRenderer = (props: IPageRenderer) => {
});
});
- setcleanup(cleanupFunc);
+ setCleanup(cleanupFunc);
},
[editor, cleanup]
);
return (
- <div className="w-full h-full pb-20 pl-7 pt-5 page-renderer">
- {!readonly ? (
- <input
- onChange={(e) => handlePageTitleChange(e.target.value)}
- className="-mt-2 w-full break-words border-none bg-custom-background pr-5 text-4xl font-bold outline-none"
- value={pageTitle}
- />
- ) : (
- <input
- onChange={(e) => handlePageTitleChange(e.target.value)}
- className="-mt-2 w-full overflow-x-clip break-words border-none bg-custom-background pr-5 text-4xl font-bold outline-none"
- value={pageTitle}
- disabled
- />
- )}
- <div className="flex relative h-full w-full flex-col pr-5 editor-renderer" onMouseOver={handleLinkHover}>
- <EditorContainer hideDragHandle={hideDragHandle} editor={editor} editorClassNames={editorClassNames}>
- <EditorContentWrapper
- tabIndex={tabIndex}
- editor={editor}
- editorContentCustomClassNames={editorContentCustomClassNames}
- />
+ <>
+ <div className="frame-renderer flex-grow w-full -mx-5" onMouseOver={handleLinkHover}>
+ <EditorContainer
+ editor={editor}
+ hideDragHandle={hideDragHandle}
+ editorContainerClassName={editorContainerClassName}
+ >
+ <EditorContentWrapper tabIndex={tabIndex} editor={editor} />
+ {editor && editor.isEditable && <BlockMenu editor={editor} />}
</EditorContainer>
</div>
{isOpen && linkViewProps && coordinates && (
<div
style={{ ...floatingStyles, left: `${coordinates.x}px`, top: `${coordinates.y}px` }}
- className={`absolute`}
+ className="absolute"
ref={refs.setFloating}
>
<LinkView {...linkViewProps} style={floatingStyles} {...getFloatingProps()} />
</div>
)}
- </div>
+ </>
);
};
diff --git a/packages/editor/document-editor/src/ui/components/summary-side-bar.tsx b/packages/editor/document-editor/src/ui/components/summary-side-bar.tsx
deleted file mode 100644
index 44ede3e8d5..0000000000
--- a/packages/editor/document-editor/src/ui/components/summary-side-bar.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { Editor } from "@tiptap/react";
-import { IMarking } from "src/types/editor-types";
-import { ContentBrowser } from "src/ui/components/content-browser";
-
-interface ISummarySideBarProps {
- editor: Editor;
- markings: IMarking[];
- sidePeekVisible: boolean;
-}
-
-export const SummarySideBar = ({ editor, markings, sidePeekVisible }: ISummarySideBarProps) => (
- <div
- className={`h-full transform overflow-hidden p-5 transition-all duration-200 ${
- sidePeekVisible ? "translate-x-0" : "-translate-x-full"
- }`}
- >
- <ContentBrowser editor={editor} markings={markings} />
- </div>
-);
diff --git a/packages/editor/document-editor/src/ui/components/vertical-dropdown-menu.tsx b/packages/editor/document-editor/src/ui/components/vertical-dropdown-menu.tsx
deleted file mode 100644
index 43843e5071..0000000000
--- a/packages/editor/document-editor/src/ui/components/vertical-dropdown-menu.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import { LucideIconType } from "@plane/editor-core";
-import { CustomMenu } from "@plane/ui";
-import { MoreVertical } from "lucide-react";
-
-type TMenuItems =
- | "archive_page"
- | "unarchive_page"
- | "lock_page"
- | "unlock_page"
- | "copy_markdown"
- | "close_page"
- | "copy_page_link"
- | "duplicate_page";
-
-export interface IVerticalDropdownItemProps {
- key: number;
- type: TMenuItems;
- Icon: LucideIconType;
- label: string;
- action: () => Promise<void> | void;
-}
-
-export interface IVerticalDropdownMenuProps {
- items: IVerticalDropdownItemProps[];
-}
-
-const VerticalDropdownItem = ({ Icon, label, action }: IVerticalDropdownItemProps) => (
- <CustomMenu.MenuItem onClick={action} className="flex items-center gap-2">
- <Icon className="h-3 w-3" />
- <div className="text-custom-text-300">{label}</div>
- </CustomMenu.MenuItem>
-);
-
-export const VerticalDropdownMenu = ({ items }: IVerticalDropdownMenuProps) => (
- <CustomMenu
- maxHeight={"md"}
- className={"h-4.5 mt-1"}
- placement={"bottom-start"}
- optionsClassName={"border-custom-border border-r border-solid transition-all duration-200 ease-in-out "}
- customButton={<MoreVertical size={14} />}
- >
- {items.map((item) => (
- <VerticalDropdownItem key={item.key} type={item.type} Icon={item.Icon} label={item.label} action={item.action} />
- ))}
- </CustomMenu>
-);
diff --git a/packages/editor/document-editor/src/ui/extensions/index.tsx b/packages/editor/document-editor/src/ui/extensions/index.tsx
index cedc3ed809..6c106176b7 100644
--- a/packages/editor/document-editor/src/ui/extensions/index.tsx
+++ b/packages/editor/document-editor/src/ui/extensions/index.tsx
@@ -6,17 +6,17 @@ import { UploadImage } from "@plane/editor-core";
export const DocumentEditorExtensions = (
uploadFile: UploadImage,
- setHideDragHandle?: (hideDragHandlerFromDragDrop: () => void) => void,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
+ setHideDragHandle?: (hideDragHandlerFromDragDrop: () => void) => void
) => [
- SlashCommand(uploadFile, setIsSubmitting),
+ SlashCommand(uploadFile),
DragAndDrop(setHideDragHandle),
Placeholder.configure({
- placeholder: ({ node }) => {
+ placeholder: ({ editor, node }) => {
if (node.type.name === "heading") {
return `Heading ${node.attrs.level}`;
}
- if (node.type.name === "image" || node.type.name === "table") {
+
+ if (editor.isActive("table") || editor.isActive("codeBlock") || editor.isActive("image")) {
return "";
}
diff --git a/packages/editor/document-editor/src/ui/index.tsx b/packages/editor/document-editor/src/ui/index.tsx
index eb54a204bd..24e712d67b 100644
--- a/packages/editor/document-editor/src/ui/index.tsx
+++ b/packages/editor/document-editor/src/ui/index.tsx
@@ -1,187 +1,97 @@
-"use client";
import React, { useState } from "react";
-import { UploadImage, DeleteImage, RestoreImage, getEditorClassNames, useEditor } from "@plane/editor-core";
+import {
+ UploadImage,
+ DeleteImage,
+ RestoreImage,
+ getEditorClassNames,
+ useEditor,
+ EditorRefApi,
+ IMentionHighlight,
+ IMentionSuggestion,
+} from "@plane/editor-core";
import { DocumentEditorExtensions } from "src/ui/extensions";
-import { IDuplicationConfig, IPageArchiveConfig, IPageLockConfig } from "src/types/menu-actions";
-import { EditorHeader } from "src/ui/components/editor-header";
-import { useEditorMarkings } from "src/hooks/use-editor-markings";
-import { SummarySideBar } from "src/ui/components/summary-side-bar";
-import { DocumentDetails } from "src/types/editor-types";
import { PageRenderer } from "src/ui/components/page-renderer";
-import { getMenuOptions } from "src/utils/menu-options";
-import { useRouter } from "next/router";
-import { FixedMenu } from "src";
interface IDocumentEditor {
- // document info
- documentDetails: DocumentDetails;
- value: string;
- rerenderOnPropsChange?: {
- id: string;
- description_html: string;
+ initialValue: string;
+ value?: string;
+ fileHandler: {
+ cancel: () => void;
+ delete: DeleteImage;
+ upload: UploadImage;
+ restore: RestoreImage;
+ };
+ handleEditorReady?: (value: boolean) => void;
+ containerClassName?: string;
+ editorClassName?: string;
+ onChange: (json: object, html: string) => void;
+ forwardedRef?: React.MutableRefObject<EditorRefApi | null>;
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
+ suggestions: () => Promise<IMentionSuggestion[]>;
};
-
- // file operations
- uploadFile: UploadImage;
- deleteFile: DeleteImage;
- restoreFile: RestoreImage;
- cancelUploadImage: () => any;
-
- // editor state managers
- onActionCompleteHandler: (action: {
- title: string;
- message: string;
- type: "success" | "error" | "warning" | "info";
- }) => void;
- customClassName?: string;
- editorContentCustomClassNames?: string;
- onChange: (json: any, html: string) => void;
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
- setShouldShowAlert?: (showAlert: boolean) => void;
- forwardedRef?: any;
- updatePageTitle: (title: string) => void;
- debouncedUpdatesEnabled?: boolean;
- isSubmitting: "submitting" | "submitted" | "saved";
-
- // embed configuration
- duplicationConfig?: IDuplicationConfig;
- pageLockConfig?: IPageLockConfig;
- pageArchiveConfig?: IPageArchiveConfig;
-
tabIndex?: number;
}
-interface DocumentEditorProps extends IDocumentEditor {
- forwardedRef?: React.Ref<EditorHandle>;
-}
-
-interface EditorHandle {
- clearEditor: () => void;
- setEditorValue: (content: string) => void;
- setEditorValueAtCursorPosition: (content: string) => void;
-}
-const DocumentEditor = ({
- documentDetails,
- onChange,
- debouncedUpdatesEnabled,
- setIsSubmitting,
- setShouldShowAlert,
- editorContentCustomClassNames,
- value,
- uploadFile,
- deleteFile,
- restoreFile,
- isSubmitting,
- customClassName,
- forwardedRef,
- duplicationConfig,
- pageLockConfig,
- pageArchiveConfig,
- updatePageTitle,
- cancelUploadImage,
- onActionCompleteHandler,
- rerenderOnPropsChange,
- tabIndex,
-}: IDocumentEditor) => {
- const { markings, updateMarkings } = useEditorMarkings();
- const [sidePeekVisible, setSidePeekVisible] = useState(true);
- const router = useRouter();
-
- const [hideDragHandleOnMouseLeave, setHideDragHandleOnMouseLeave] = React.useState<() => void>(() => {});
+const DocumentEditor = (props: IDocumentEditor) => {
+ const {
+ onChange,
+ initialValue,
+ value,
+ fileHandler,
+ containerClassName,
+ editorClassName = "",
+ mentionHandler,
+ handleEditorReady,
+ forwardedRef,
+ tabIndex,
+ } = props;
+ // states
+ const [hideDragHandleOnMouseLeave, setHideDragHandleOnMouseLeave] = useState<() => void>(() => {});
// this essentially sets the hideDragHandle function from the DragAndDrop extension as the Plugin
// loads such that we can invoke it from react when the cursor leaves the container
const setHideDragHandleFunction = (hideDragHandlerFromDragDrop: () => void) => {
setHideDragHandleOnMouseLeave(() => hideDragHandlerFromDragDrop);
};
-
+ // use editor
const editor = useEditor({
onChange(json, html) {
- updateMarkings(json);
onChange(json, html);
},
- onStart(json) {
- updateMarkings(json);
- },
- debouncedUpdatesEnabled,
- restoreFile,
- setIsSubmitting,
- setShouldShowAlert,
+ editorClassName,
+ restoreFile: fileHandler.restore,
+ uploadFile: fileHandler.upload,
+ deleteFile: fileHandler.delete,
+ cancelUploadImage: fileHandler.cancel,
+ initialValue,
value,
- uploadFile,
- deleteFile,
- cancelUploadImage,
- rerenderOnPropsChange,
+ handleEditorReady,
forwardedRef,
- extensions: DocumentEditorExtensions(uploadFile, setHideDragHandleFunction, setIsSubmitting),
- });
-
- if (!editor) {
- return null;
- }
-
- const KanbanMenuOptions = getMenuOptions({
- editor: editor,
- router: router,
- duplicationConfig: duplicationConfig,
- pageLockConfig: pageLockConfig,
- pageArchiveConfig: pageArchiveConfig,
- onActionCompleteHandler,
+ mentionHandler,
+ extensions: DocumentEditorExtensions(fileHandler.upload, setHideDragHandleFunction),
});
- const editorClassNames = getEditorClassNames({
+ const editorContainerClassNames = getEditorClassNames({
noBorder: true,
borderOnFocus: false,
- customClassName,
+ containerClassName,
});
if (!editor) return null;
return (
- <div className="flex h-full w-full flex-col overflow-hidden">
- <EditorHeader
- readonly={false}
- KanbanMenuOptions={KanbanMenuOptions}
- editor={editor}
- sidePeekVisible={sidePeekVisible}
- setSidePeekVisible={(val) => setSidePeekVisible(val)}
- markings={markings}
- uploadFile={uploadFile}
- setIsSubmitting={setIsSubmitting}
- isLocked={!pageLockConfig ? false : pageLockConfig.is_locked}
- isArchived={!pageArchiveConfig ? false : pageArchiveConfig.is_archived}
- archivedAt={pageArchiveConfig && pageArchiveConfig.archived_at}
- documentDetails={documentDetails}
- isSubmitting={isSubmitting}
- />
- <div className="flex-shrink-0 md:hidden border-b border-custom-border-200 pl-3 py-2">
- {uploadFile && <FixedMenu editor={editor} uploadFile={uploadFile} setIsSubmitting={setIsSubmitting} />}
- </div>
- <div className="flex h-full w-full overflow-y-auto frame-renderer">
- <div className="sticky top-0 h-full w-56 flex-shrink-0 lg:w-72 hidden md:block">
- <SummarySideBar editor={editor} markings={markings} sidePeekVisible={sidePeekVisible} />
- </div>
- <div className="h-full w-full md:w-[calc(100%-14rem)] lg:w-[calc(100%-18rem-18rem)] page-renderer">
- <PageRenderer
- tabIndex={tabIndex}
- onActionCompleteHandler={onActionCompleteHandler}
- hideDragHandle={hideDragHandleOnMouseLeave}
- readonly={false}
- editor={editor}
- editorContentCustomClassNames={editorContentCustomClassNames}
- editorClassNames={editorClassNames}
- documentDetails={documentDetails}
- updatePageTitle={updatePageTitle}
- />
- </div>
- <div className="hidden w-56 flex-shrink-0 lg:block lg:w-72" />
- </div>
- </div>
+ <PageRenderer
+ tabIndex={tabIndex}
+ editor={editor}
+ editorContainerClassName={editorContainerClassNames}
+ hideDragHandle={hideDragHandleOnMouseLeave}
+ />
);
};
-const DocumentEditorWithRef = React.forwardRef<EditorHandle, IDocumentEditor>((props, ref) => (
- <DocumentEditor {...props} forwardedRef={ref} />
+const DocumentEditorWithRef = React.forwardRef<EditorRefApi, IDocumentEditor>((props, ref) => (
+ <DocumentEditor {...props} forwardedRef={ref as React.MutableRefObject<EditorRefApi | null>} />
));
DocumentEditorWithRef.displayName = "DocumentEditorWithRef";
diff --git a/packages/editor/document-editor/src/ui/menu/block-menu.tsx b/packages/editor/document-editor/src/ui/menu/block-menu.tsx
new file mode 100644
index 0000000000..9703113f77
--- /dev/null
+++ b/packages/editor/document-editor/src/ui/menu/block-menu.tsx
@@ -0,0 +1,149 @@
+import { useCallback, useEffect, useRef } from "react";
+import tippy, { Instance } from "tippy.js";
+import { Copy, LucideIcon, Trash2 } from "lucide-react";
+import { Editor } from "@tiptap/react";
+
+interface BlockMenuProps {
+ editor: Editor;
+}
+
+export default function BlockMenu(props: BlockMenuProps) {
+ const { editor } = props;
+ const menuRef = useRef<HTMLDivElement>(null);
+ const popup = useRef<Instance | null>(null);
+
+ const handleClickDragHandle = useCallback((event: MouseEvent) => {
+ const target = event.target as HTMLElement;
+ if (target.matches(".drag-handle-dots") || target.matches(".drag-handle-dot")) {
+ event.preventDefault();
+
+ popup.current?.setProps({
+ getReferenceClientRect: () => target.getBoundingClientRect(),
+ });
+
+ popup.current?.show();
+ return;
+ }
+
+ popup.current?.hide();
+ return;
+ }, []);
+
+ useEffect(() => {
+ if (menuRef.current) {
+ menuRef.current.remove();
+ menuRef.current.style.visibility = "visible";
+
+ // @ts-expect-error - tippy types are incorrect
+ popup.current = tippy(document.body, {
+ getReferenceClientRect: null,
+ content: menuRef.current,
+ appendTo: () => document.querySelector(".frame-renderer"),
+ trigger: "manual",
+ interactive: true,
+ arrow: false,
+ placement: "left-start",
+ animation: "shift-away",
+ maxWidth: 500,
+ hideOnClick: true,
+ onShown: () => {
+ menuRef.current?.focus();
+ },
+ });
+ }
+
+ return () => {
+ popup.current?.destroy();
+ popup.current = null;
+ };
+ }, []);
+
+ useEffect(() => {
+ const handleKeyDown = () => {
+ popup.current?.hide();
+ };
+
+ const handleScroll = () => {
+ popup.current?.hide();
+ };
+ document.addEventListener("click", handleClickDragHandle);
+ document.addEventListener("keydown", handleKeyDown);
+ document.addEventListener("scroll", handleScroll, true); // Using capture phase
+
+ return () => {
+ document.removeEventListener("click", handleClickDragHandle);
+ document.removeEventListener("keydown", handleKeyDown);
+ document.removeEventListener("scroll", handleScroll, true);
+ };
+ }, [handleClickDragHandle]);
+
+ const MENU_ITEMS: {
+ icon: LucideIcon;
+ key: string;
+ label: string;
+ onClick: (e: React.MouseEvent) => void;
+ isDisabled?: boolean;
+ }[] = [
+ {
+ icon: Trash2,
+ key: "delete",
+ label: "Delete",
+ onClick: (e) => {
+ editor.chain().deleteSelection().focus().run();
+ popup.current?.hide();
+ e.preventDefault();
+ e.stopPropagation();
+ },
+ },
+ {
+ icon: Copy,
+ key: "duplicate",
+ label: "Duplicate",
+ isDisabled: editor.state.selection.content().content.firstChild?.type.name === "image",
+ onClick: (e) => {
+ const { view } = editor;
+ const { state } = view;
+ const { selection } = state;
+
+ editor
+ .chain()
+ .insertContentAt(selection.to, selection.content().content.firstChild!.toJSON(), {
+ updateSelection: true,
+ })
+ .focus(selection.to + 1, { scrollIntoView: false })
+ .run();
+
+ popup.current?.hide();
+ e.preventDefault();
+ e.stopPropagation();
+ },
+ },
+ ];
+
+ return (
+ <div
+ ref={menuRef}
+ className="z-10 max-h-60 min-w-[7rem] overflow-y-scroll rounded-md border-[0.5px] border-custom-border-300 bg-custom-background-100 px-2 py-2.5 shadow-custom-shadow-rg"
+ >
+ {MENU_ITEMS.map((item) => {
+ // Skip rendering the button if it should be disabled
+ if (item.isDisabled && item.key === "duplicate") {
+ return null;
+ }
+
+ return (
+ <button
+ key={item.key}
+ type="button"
+ className="flex w-full items-center gap-2 truncate rounded px-1 py-1.5 text-xs text-custom-text-200 hover:bg-custom-background-80"
+ onClick={item.onClick}
+ disabled={item.isDisabled}
+ >
+ <item.icon className="h-3 w-3" />
+ {item.label}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/packages/editor/document-editor/src/ui/menu/fixed-menu.tsx b/packages/editor/document-editor/src/ui/menu/fixed-menu.tsx
deleted file mode 100644
index 397e8c576d..0000000000
--- a/packages/editor/document-editor/src/ui/menu/fixed-menu.tsx
+++ /dev/null
@@ -1,141 +0,0 @@
-import { Editor } from "@tiptap/react";
-import {
- BoldItem,
- BulletListItem,
- isCellSelection,
- cn,
- CodeItem,
- ImageItem,
- ItalicItem,
- NumberedListItem,
- QuoteItem,
- StrikeThroughItem,
- TableItem,
- UnderLineItem,
- HeadingOneItem,
- HeadingTwoItem,
- HeadingThreeItem,
- findTableAncestor,
- EditorMenuItem,
- UploadImage,
-} from "@plane/editor-core";
-
-export type BubbleMenuItem = EditorMenuItem;
-
-type EditorBubbleMenuProps = {
- editor: Editor;
- uploadFile: UploadImage;
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
-};
-
-export const FixedMenu = (props: EditorBubbleMenuProps) => {
- const { editor, uploadFile, setIsSubmitting } = props;
-
- const basicMarkItems: BubbleMenuItem[] = [
- HeadingOneItem(editor),
- HeadingTwoItem(editor),
- HeadingThreeItem(editor),
- BoldItem(editor),
- ItalicItem(editor),
- UnderLineItem(editor),
- StrikeThroughItem(editor),
- ];
-
- const listItems: BubbleMenuItem[] = [BulletListItem(editor), NumberedListItem(editor)];
-
- const userActionItems: BubbleMenuItem[] = [QuoteItem(editor), CodeItem(editor)];
-
- function getComplexItems(): BubbleMenuItem[] {
- const items: BubbleMenuItem[] = [TableItem(editor)];
-
- items.push(ImageItem(editor, uploadFile, setIsSubmitting));
- return items;
- }
-
- const complexItems: BubbleMenuItem[] = getComplexItems();
-
- return (
- <div className="flex flex-wrap items-center divide-x divide-custom-border-200">
- <div className="flex items-center gap-0.5 pr-2">
- {basicMarkItems.map((item) => (
- <button
- key={item.name}
- type="button"
- onClick={item.command}
- className={cn(
- "grid h-7 w-7 place-items-center rounded text-custom-text-300 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon className="h-4 w-4" />
- </button>
- ))}
- </div>
- <div className="flex items-center gap-0.5 px-2">
- {listItems.map((item) => (
- <button
- key={item.name}
- type="button"
- onClick={item.command}
- className={cn(
- "grid h-7 w-7 place-items-center rounded text-custom-text-300 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon
- className={cn("h-4 w-4", {
- "text-custom-text-100": item.isActive(),
- })}
- />
- </button>
- ))}
- </div>
- <div className="flex items-center gap-0.5 px-2">
- {userActionItems.map((item) => (
- <button
- key={item.name}
- type="button"
- onClick={item.command}
- className={cn(
- "grid h-7 w-7 place-items-center rounded text-custom-text-300 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon
- className={cn("h-4 w-4", {
- "text-custom-text-100": item.isActive(),
- })}
- />
- </button>
- ))}
- </div>
- <div className="flex items-center gap-0.5 pl-2">
- {complexItems.map((item) => (
- <button
- key={item.name}
- type="button"
- onClick={item.command}
- className={cn(
- "grid h-7 w-7 place-items-center rounded text-custom-text-300 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon
- className={cn("h-4 w-4", {
- "text-custom-text-100": item.isActive(),
- })}
- />
- </button>
- ))}
- </div>
- </div>
- );
-};
diff --git a/packages/editor/document-editor/src/ui/menu/index.tsx b/packages/editor/document-editor/src/ui/menu/index.tsx
deleted file mode 100644
index 1c411fabfe..0000000000
--- a/packages/editor/document-editor/src/ui/menu/index.tsx
+++ /dev/null
@@ -1 +0,0 @@
-export { FixedMenu } from "./fixed-menu";
diff --git a/packages/editor/document-editor/src/ui/readonly/index.tsx b/packages/editor/document-editor/src/ui/readonly/index.tsx
index 22099281ec..0e75c2db49 100644
--- a/packages/editor/document-editor/src/ui/readonly/index.tsx
+++ b/packages/editor/document-editor/src/ui/readonly/index.tsx
@@ -1,132 +1,53 @@
-import { getEditorClassNames, useReadOnlyEditor } from "@plane/editor-core";
-import { useRouter } from "next/router";
-import { useState, forwardRef, useEffect } from "react";
-import { EditorHeader } from "src/ui/components/editor-header";
+import { forwardRef, MutableRefObject } from "react";
+import { EditorReadOnlyRefApi, getEditorClassNames, IMentionHighlight, useReadOnlyEditor } from "@plane/editor-core";
+// components
import { PageRenderer } from "src/ui/components/page-renderer";
-import { SummarySideBar } from "src/ui/components/summary-side-bar";
-import { useEditorMarkings } from "src/hooks/use-editor-markings";
-import { DocumentDetails } from "src/types/editor-types";
-import { IPageArchiveConfig, IPageLockConfig, IDuplicationConfig } from "src/types/menu-actions";
-import { getMenuOptions } from "src/utils/menu-options";
import { IssueWidgetPlaceholder } from "../extensions/widgets/issue-embed-widget";
interface IDocumentReadOnlyEditor {
- value: string;
- rerenderOnPropsChange?: {
- id: string;
- description_html: string;
- };
- noBorder: boolean;
- borderOnFocus: boolean;
- customClassName: string;
- documentDetails: DocumentDetails;
- pageLockConfig?: IPageLockConfig;
- pageArchiveConfig?: IPageArchiveConfig;
- pageDuplicationConfig?: IDuplicationConfig;
- onActionCompleteHandler: (action: {
- title: string;
- message: string;
- type: "success" | "error" | "warning" | "info";
- }) => void;
+ initialValue: string;
+ containerClassName: string;
+ editorClassName?: string;
tabIndex?: number;
+ handleEditorReady?: (value: boolean) => void;
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
+ };
+ forwardedRef?: React.MutableRefObject<EditorReadOnlyRefApi | null>;
}
-interface DocumentReadOnlyEditorProps extends IDocumentReadOnlyEditor {
- forwardedRef?: React.Ref<EditorHandle>;
-}
-
-interface EditorHandle {
- clearEditor: () => void;
- setEditorValue: (content: string) => void;
-}
-
-const DocumentReadOnlyEditor = ({
- noBorder,
- borderOnFocus,
- customClassName,
- value,
- documentDetails,
- forwardedRef,
- pageDuplicationConfig,
- pageLockConfig,
- pageArchiveConfig,
- rerenderOnPropsChange,
- onActionCompleteHandler,
- tabIndex,
-}: DocumentReadOnlyEditorProps) => {
- const router = useRouter();
- const [sidePeekVisible, setSidePeekVisible] = useState(true);
- const { markings, updateMarkings } = useEditorMarkings();
-
+const DocumentReadOnlyEditor = (props: IDocumentReadOnlyEditor) => {
+ const {
+ containerClassName,
+ editorClassName = "",
+ initialValue,
+ forwardedRef,
+ tabIndex,
+ handleEditorReady,
+ mentionHandler,
+ } = props;
const editor = useReadOnlyEditor({
- value,
+ initialValue,
+ editorClassName,
+ mentionHandler,
forwardedRef,
- rerenderOnPropsChange,
+ handleEditorReady,
extensions: [IssueWidgetPlaceholder()],
});
- useEffect(() => {
- if (editor) {
- updateMarkings(editor.getJSON());
- }
- }, [editor]);
-
if (!editor) {
return null;
}
- const editorClassNames = getEditorClassNames({
- noBorder,
- borderOnFocus,
- customClassName,
- });
-
- const KanbanMenuOptions = getMenuOptions({
- editor: editor,
- router: router,
- pageArchiveConfig: pageArchiveConfig,
- pageLockConfig: pageLockConfig,
- duplicationConfig: pageDuplicationConfig,
- onActionCompleteHandler,
+ const editorContainerClassName = getEditorClassNames({
+ containerClassName,
});
- return (
- <div className="flex h-full w-full flex-col overflow-hidden">
- <EditorHeader
- isLocked={!pageLockConfig ? false : pageLockConfig.is_locked}
- isArchived={!pageArchiveConfig ? false : pageArchiveConfig.is_archived}
- readonly
- editor={editor}
- sidePeekVisible={sidePeekVisible}
- setSidePeekVisible={setSidePeekVisible}
- KanbanMenuOptions={KanbanMenuOptions}
- markings={markings}
- documentDetails={documentDetails}
- archivedAt={pageArchiveConfig && pageArchiveConfig.archived_at}
- />
- <div className="flex h-full w-full overflow-y-auto frame-renderer">
- <div className="sticky top-0 h-full w-56 flex-shrink-0 lg:w-80">
- <SummarySideBar editor={editor} markings={markings} sidePeekVisible={sidePeekVisible} />
- </div>
- <div className="h-full w-[calc(100%-14rem)] lg:w-[calc(100%-18rem-18rem)] page-renderer">
- <PageRenderer
- tabIndex={tabIndex}
- onActionCompleteHandler={onActionCompleteHandler}
- updatePageTitle={() => Promise.resolve()}
- readonly
- editor={editor}
- editorClassNames={editorClassNames}
- documentDetails={documentDetails}
- />
- </div>
- <div className="hidden w-56 flex-shrink-0 lg:block lg:w-80" />
- </div>
- </div>
- );
+ return <PageRenderer tabIndex={tabIndex} editor={editor} editorContainerClassName={editorContainerClassName} />;
};
-const DocumentReadOnlyEditorWithRef = forwardRef<EditorHandle, IDocumentReadOnlyEditor>((props, ref) => (
- <DocumentReadOnlyEditor {...props} forwardedRef={ref} />
+const DocumentReadOnlyEditorWithRef = forwardRef<EditorReadOnlyRefApi, IDocumentReadOnlyEditor>((props, ref) => (
+ <DocumentReadOnlyEditor {...props} forwardedRef={ref as MutableRefObject<EditorReadOnlyRefApi | null>} />
));
DocumentReadOnlyEditorWithRef.displayName = "DocumentReadOnlyEditorWithRef";
diff --git a/packages/editor/document-editor/src/utils/menu-actions.ts b/packages/editor/document-editor/src/utils/menu-actions.ts
deleted file mode 100644
index 24eda5a057..0000000000
--- a/packages/editor/document-editor/src/utils/menu-actions.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { Editor } from "@tiptap/core";
-
-export const copyMarkdownToClipboard = (editor: Editor | null) => {
- const markdownOutput = editor?.storage.markdown.getMarkdown();
- navigator.clipboard.writeText(markdownOutput);
-};
-
-export const CopyPageLink = () => {
- if (window) {
- navigator.clipboard.writeText(window.location.toString());
- }
-};
diff --git a/packages/editor/document-editor/src/utils/menu-options.ts b/packages/editor/document-editor/src/utils/menu-options.ts
deleted file mode 100644
index befed424db..0000000000
--- a/packages/editor/document-editor/src/utils/menu-options.ts
+++ /dev/null
@@ -1,153 +0,0 @@
-import { Editor } from "@tiptap/react";
-import { Archive, ArchiveRestoreIcon, ClipboardIcon, Copy, Link, Lock, Unlock } from "lucide-react";
-import { NextRouter } from "next/router";
-import { IVerticalDropdownItemProps } from "src/ui/components/vertical-dropdown-menu";
-import { IDuplicationConfig, IPageArchiveConfig, IPageLockConfig } from "src/types/menu-actions";
-import { copyMarkdownToClipboard, CopyPageLink } from "src/utils/menu-actions";
-
-export interface MenuOptionsProps {
- editor: Editor;
- router: NextRouter;
- duplicationConfig?: IDuplicationConfig;
- pageLockConfig?: IPageLockConfig;
- pageArchiveConfig?: IPageArchiveConfig;
- onActionCompleteHandler: (action: {
- title: string;
- message: string;
- type: "success" | "error" | "warning" | "info";
- }) => void;
-}
-
-export const getMenuOptions = ({
- editor,
- router,
- duplicationConfig,
- pageLockConfig,
- pageArchiveConfig,
- onActionCompleteHandler,
-}: MenuOptionsProps) => {
- const KanbanMenuOptions: IVerticalDropdownItemProps[] = [
- {
- key: 1,
- type: "copy_markdown",
- Icon: ClipboardIcon,
- action: () => {
- onActionCompleteHandler({
- title: "Markdown Copied",
- message: "Page Copied as Markdown",
- type: "success",
- });
- copyMarkdownToClipboard(editor);
- },
- label: "Copy markdown",
- },
- // {
- // key: 2,
- // type: "close_page",
- // Icon: XCircle,
- // action: () => router.back(),
- // label: "Close page",
- // },
- {
- key: 3,
- type: "copy_page_link",
- Icon: Link,
- action: () => {
- onActionCompleteHandler({
- title: "Link Copied",
- message: "Link to the page has been copied to clipboard",
- type: "success",
- });
- CopyPageLink();
- },
- label: "Copy page link",
- },
- ];
-
- // If duplicateConfig is given, page duplication will be allowed
- if (duplicationConfig) {
- KanbanMenuOptions.push({
- key: KanbanMenuOptions.length++,
- type: "duplicate_page",
- Icon: Copy,
- action: () => {
- duplicationConfig
- .action()
- .then(() => {
- onActionCompleteHandler({
- title: "Page Copied",
- message: "Page has been copied as 'Copy of' followed by page title",
- type: "success",
- });
- })
- .catch(() => {
- onActionCompleteHandler({
- title: "Copy Failed",
- message: "Sorry, page cannot be copied, please try again later.",
- type: "error",
- });
- });
- },
- label: "Make a copy",
- });
- }
- // If Lock Configuration is given then, lock page option will be available in the kanban menu
- if (pageLockConfig) {
- KanbanMenuOptions.push({
- key: KanbanMenuOptions.length++,
- type: pageLockConfig.is_locked ? "unlock_page" : "lock_page",
- Icon: pageLockConfig.is_locked ? Unlock : Lock,
- label: pageLockConfig.is_locked ? "Unlock page" : "Lock page",
- action: () => {
- const state = pageLockConfig.is_locked ? "Unlocked" : "Locked";
- pageLockConfig
- .action()
- .then(() => {
- onActionCompleteHandler({
- title: `Page ${state}`,
- message: `Page has been ${state}, no one will be able to change the state of lock except you.`,
- type: "success",
- });
- })
- .catch(() => {
- onActionCompleteHandler({
- title: `Page cannot be ${state}`,
- message: `Sorry, page cannot be ${state}, please try again later`,
- type: "error",
- });
- });
- },
- });
- }
-
- // Archiving will be visible in the menu bar config once the pageArchiveConfig is given.
- if (pageArchiveConfig) {
- KanbanMenuOptions.push({
- key: KanbanMenuOptions.length++,
- type: pageArchiveConfig.is_archived ? "unarchive_page" : "archive_page",
- Icon: pageArchiveConfig.is_archived ? ArchiveRestoreIcon : Archive,
- label: pageArchiveConfig.is_archived ? "Restore page" : "Archive page",
- action: () => {
- const state = pageArchiveConfig.is_archived ? "Unarchived" : "Archived";
- pageArchiveConfig
- .action()
- .then(() => {
- onActionCompleteHandler({
- title: `Page ${state}`,
- message: `Page has been ${state}, you can checkout all archived tab and can restore the page later.`,
- type: "success",
- });
- })
- .catch(() => {
- onActionCompleteHandler({
- title: `Page cannot be ${state}`,
- message: `Sorry, page cannot be ${state}, please try again later.`,
- type: "success",
- });
- });
- },
- });
- }
-
- return KanbanMenuOptions;
-};
diff --git a/packages/editor/extensions/package.json b/packages/editor/extensions/package.json
index 711ab8a969..a57e4f78bf 100644
--- a/packages/editor/extensions/package.json
+++ b/packages/editor/extensions/package.json
@@ -29,6 +29,7 @@
},
"dependencies": {
"@plane/editor-core": "*",
+ "@plane/ui": "*",
"@tiptap/core": "^2.1.13",
"@tiptap/pm": "^2.1.13",
"@tiptap/react": "^2.1.13",
diff --git a/packages/editor/extensions/src/extensions/drag-drop.tsx b/packages/editor/extensions/src/extensions/drag-drop.tsx
index ce4088413c..1c24274185 100644
--- a/packages/editor/extensions/src/extensions/drag-drop.tsx
+++ b/packages/editor/extensions/src/extensions/drag-drop.tsx
@@ -1,9 +1,18 @@
import { Extension } from "@tiptap/core";
-import { PluginKey, NodeSelection, Plugin } from "@tiptap/pm/state";
-// @ts-ignore
+import { NodeSelection, Plugin, PluginKey, TextSelection } from "@tiptap/pm/state";
+import { Fragment, Slice, Node } from "@tiptap/pm/model";
+// @ts-expect-error __serializeForClipboard's is not exported
import { __serializeForClipboard, EditorView } from "@tiptap/pm/view";
-import React from "react";
+
+export interface DragHandleOptions {
+ dragHandleWidth: number;
+ setHideDragHandle?: (hideDragHandlerFromDragDrop: () => void) => void;
+ scrollThreshold: {
+ up: number;
+ down: number;
+ };
+}
function createDragHandleElement(): HTMLElement {
const dragHandleElement = document.createElement("div");
@@ -29,13 +38,8 @@ function createDragHandleElement(): HTMLElement {
return dragHandleElement;
}
-export interface DragHandleOptions {
- dragHandleWidth: number;
- setHideDragHandle?: (hideDragHandlerFromDragDrop: () => void) => void;
-}
-
function absoluteRect(node: Element) {
- const data = node?.getBoundingClientRect();
+ const data = node.getBoundingClientRect();
return {
top: data.top,
@@ -57,55 +61,77 @@ function nodeDOMAtCoords(coords: { x: number; y: number }) {
"pre",
"blockquote",
"h1, h2, h3",
+ ".table-wrapper",
"[data-type=horizontalRule]",
- ".tableWrapper",
].join(", ")
)
);
}
-function nodePosAtDOM(node: Element, view: EditorView) {
- const boundingRect = node?.getBoundingClientRect();
-
- if (node.nodeName === "IMG") {
- return view.posAtCoords({
- left: boundingRect.left + 1,
- top: boundingRect.top + 1,
- })?.pos;
- }
-
- if (node.nodeName === "PRE") {
- return (
- view.posAtCoords({
- left: boundingRect.left + 1,
- top: boundingRect.top + 1,
- })?.pos! - 1
- );
- }
+function nodePosAtDOM(node: Element, view: EditorView, options: DragHandleOptions) {
+ const boundingRect = node.getBoundingClientRect();
return view.posAtCoords({
- left: boundingRect.left + 1,
+ left: boundingRect.left + 50 + options.dragHandleWidth,
top: boundingRect.top + 1,
})?.inside;
}
+function calcNodePos(pos: number, view: EditorView) {
+ const $pos = view.state.doc.resolve(pos);
+ if ($pos.depth > 1) return $pos.before($pos.depth);
+ return pos;
+}
+
function DragHandle(options: DragHandleOptions) {
+ let listType = "";
function handleDragStart(event: DragEvent, view: EditorView) {
view.focus();
if (!event.dataTransfer) return;
const node = nodeDOMAtCoords({
- x: event.clientX + options.dragHandleWidth + 50,
+ x: event.clientX + 50 + options.dragHandleWidth,
y: event.clientY,
});
if (!(node instanceof Element)) return;
- const nodePos = nodePosAtDOM(node, view);
- if (nodePos === null || nodePos === undefined || nodePos < 0) return;
+ let draggedNodePos = nodePosAtDOM(node, view, options);
+ if (draggedNodePos == null || draggedNodePos < 0) return;
+ draggedNodePos = calcNodePos(draggedNodePos, view);
+
+ const { from, to } = view.state.selection;
+ const diff = from - to;
+
+ const fromSelectionPos = calcNodePos(from, view);
+ let differentNodeSelected = false;
+
+ const nodePos = view.state.doc.resolve(fromSelectionPos);
+
+ // Check if nodePos points to the top level node
+ if (nodePos.node().type.name === "doc") differentNodeSelected = true;
+ else {
+ const nodeSelection = NodeSelection.create(view.state.doc, nodePos.before());
+ // Check if the node where the drag event started is part of the current selection
+ differentNodeSelected = !(
+ draggedNodePos + 1 >= nodeSelection.$from.pos && draggedNodePos <= nodeSelection.$to.pos
+ );
+ }
+
+ if (!differentNodeSelected && diff !== 0 && !(view.state.selection instanceof NodeSelection)) {
+ const endSelection = NodeSelection.create(view.state.doc, to - 1);
+ const multiNodeSelection = TextSelection.create(view.state.doc, draggedNodePos, endSelection.$to.pos);
+ view.dispatch(view.state.tr.setSelection(multiNodeSelection));
+ } else {
+ const nodeSelection = NodeSelection.create(view.state.doc, draggedNodePos);
+ view.dispatch(view.state.tr.setSelection(nodeSelection));
+ }
- view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, nodePos)));
+ // If the selected node is a list item, we need to save the type of the wrapping list e.g. OL or UL
+ if (view.state.selection instanceof NodeSelection && view.state.selection.node.type.name === "listItem") {
+ listType = node.parentElement!.tagName;
+ }
const slice = view.state.selection.content();
const { dom, text } = __serializeForClipboard(view, slice);
@@ -123,8 +149,6 @@ function DragHandle(options: DragHandleOptions) {
function handleClick(event: MouseEvent, view: EditorView) {
view.focus();
- view.dom.classList.remove("dragging");
-
const node = nodeDOMAtCoords({
x: event.clientX + 50 + options.dragHandleWidth,
y: event.clientY,
@@ -132,11 +156,18 @@ function DragHandle(options: DragHandleOptions) {
if (!(node instanceof Element)) return;
- const nodePos = nodePosAtDOM(node, view);
+ let nodePos = nodePosAtDOM(node, view, options);
+
+ if (nodePos === null || nodePos === undefined) return;
- if (nodePos === null || nodePos === undefined || nodePos < 0) return;
+ // Adjust the nodePos to point to the start of the node, ensuring NodeSelection can be applied
+ nodePos = calcNodePos(nodePos, view);
- view.dispatch(view.state.tr.setSelection(NodeSelection.create(view.state.doc, nodePos)));
+ // Use NodeSelection to select the node at the calculated position
+ const nodeSelection = NodeSelection.create(view.state.doc, nodePos);
+
+ // Dispatch the transaction to update the selection
+ view.dispatch(view.state.tr.setSelection(nodeSelection));
}
let dragHandleElement: HTMLElement | null = null;
@@ -166,11 +197,15 @@ function DragHandle(options: DragHandleOptions) {
handleClick(e, view);
});
- dragHandleElement.addEventListener("dragstart", (e) => {
- handleDragStart(e, view);
- });
- dragHandleElement.addEventListener("click", (e) => {
- handleClick(e, view);
+ dragHandleElement.addEventListener("drag", (e) => {
+ hideDragHandle();
+ const a = document.querySelector(".frame-renderer");
+ if (!a) return;
+ if (e.clientY < options.scrollThreshold.up) {
+ a.scrollBy({ top: -70, behavior: "smooth" });
+ } else if (window.innerHeight - e.clientY < options.scrollThreshold.down) {
+ a.scrollBy({ top: 70, behavior: "smooth" });
+ }
});
hideDragHandle();
@@ -192,11 +227,11 @@ function DragHandle(options: DragHandleOptions) {
}
const node = nodeDOMAtCoords({
- x: event.clientX + options.dragHandleWidth,
+ x: event.clientX + 50 + options.dragHandleWidth,
y: event.clientY,
});
- if (!(node instanceof Element)) {
+ if (!(node instanceof Element) || node.matches("ul, ol")) {
hideDragHandle();
return;
}
@@ -207,32 +242,74 @@ function DragHandle(options: DragHandleOptions) {
const rect = absoluteRect(node);
- rect.top += (lineHeight - 24) / 2;
+ rect.top += (lineHeight - 20) / 2;
rect.top += paddingTop;
// Li markers
if (node.matches("ul:not([data-type=taskList]) li, ol li")) {
- rect.left -= options.dragHandleWidth;
+ rect.top += 4;
+ rect.left -= 18;
}
rect.width = options.dragHandleWidth;
if (!dragHandleElement) return;
dragHandleElement.style.left = `${rect.left - rect.width}px`;
- dragHandleElement.style.top = `${rect.top + 3}px`;
+ dragHandleElement.style.top = `${rect.top}px`;
showDragHandle();
},
keydown: () => {
hideDragHandle();
},
- wheel: () => {
+ mousewheel: () => {
hideDragHandle();
},
- // dragging className is used for CSS
- dragstart: (view) => {
+ dragenter: (view) => {
view.dom.classList.add("dragging");
+ hideDragHandle();
},
- drop: (view) => {
+ drop: (view, event) => {
view.dom.classList.remove("dragging");
+ hideDragHandle();
+ let droppedNode: Node | null = null;
+ const dropPos = view.posAtCoords({
+ left: event.clientX,
+ top: event.clientY,
+ });
+
+ if (!dropPos) return;
+
+ if (view.state.selection instanceof NodeSelection) {
+ droppedNode = view.state.selection.node;
+ }
+ if (!droppedNode) return;
+
+ const resolvedPos = view.state.doc.resolve(dropPos.pos);
+ let isDroppedInsideList = false;
+
+ // Traverse up the document tree to find if we're inside a list item
+ for (let i = resolvedPos.depth; i > 0; i--) {
+ if (resolvedPos.node(i).type.name === "listItem") {
+ isDroppedInsideList = true;
+ break;
+ }
+ }
+
+ // If the selected node is a list item and is not dropped inside a list, we need to wrap it inside <ol> tag otherwise ol list items will be transformed into ul list item when dropped
+ if (
+ view.state.selection instanceof NodeSelection &&
+ view.state.selection.node.type.name === "listItem" &&
+ !isDroppedInsideList &&
+ listType == "OL"
+ ) {
+ const text = droppedNode.textContent;
+ if (!text) return;
+ const paragraph = view.state.schema.nodes.paragraph?.createAndFill({}, view.state.schema.text(text));
+ const listItem = view.state.schema.nodes.listItem?.createAndFill({}, paragraph);
+
+ const newList = view.state.schema.nodes.orderedList?.createAndFill(null, listItem);
+ const slice = new Slice(Fragment.from(newList), 0, 0);
+ view.dragging = { slice, move: event.ctrlKey };
+ }
},
dragend: (view) => {
view.dom.classList.remove("dragging");
@@ -250,6 +327,7 @@ export const DragAndDrop = (setHideDragHandle?: (hideDragHandlerFromDragDrop: ()
return [
DragHandle({
dragHandleWidth: 24,
+ scrollThreshold: { up: 300, down: 100 },
setHideDragHandle,
}),
];
diff --git a/packages/editor/extensions/src/extensions/index.ts b/packages/editor/extensions/src/extensions/index.ts
new file mode 100644
index 0000000000..9ceeb64936
--- /dev/null
+++ b/packages/editor/extensions/src/extensions/index.ts
@@ -0,0 +1,2 @@
+export * from "./drag-drop";
+export * from "./slash-commands";
diff --git a/packages/editor/extensions/src/extensions/slash-commands.tsx b/packages/editor/extensions/src/extensions/slash-commands.tsx
index c52178b818..049accb278 100644
--- a/packages/editor/extensions/src/extensions/slash-commands.tsx
+++ b/packages/editor/extensions/src/extensions/slash-commands.tsx
@@ -54,7 +54,20 @@ const Command = Extension.create<SlashCommandOptions>({
props.command({ editor, range });
},
allow({ editor }: { editor: Editor }) {
- return !editor.isActive("table");
+ const { selection } = editor.state;
+
+ const parentNode = selection.$from.node(selection.$from.depth);
+ const blockType = parentNode.type.name;
+
+ if (blockType === "codeBlock") {
+ return false;
+ }
+
+ if (editor.isActive("table")) {
+ return false;
+ }
+
+ return true;
},
allowSpaces: true,
},
@@ -71,11 +84,7 @@ const Command = Extension.create<SlashCommandOptions>({
});
const getSuggestionItems =
- (
- uploadFile: UploadImage,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void,
- additionalOptions?: Array<ISlashCommandItem>
- ) =>
+ (uploadFile: UploadImage, additionalOptions?: Array<ISlashCommandItem>) =>
({ query }: { query: string }) => {
let slashCommands: ISlashCommandItem[] = [
{
@@ -186,7 +195,7 @@ const getSuggestionItems =
searchTerms: ["img", "photo", "picture", "media"],
icon: <ImageIcon className="h-3.5 w-3.5" />,
command: ({ editor, range }: CommandProps) => {
- insertImageCommand(editor, uploadFile, setIsSubmitting, range);
+ insertImageCommand(editor, uploadFile, null, range);
},
},
{
@@ -300,9 +309,9 @@ const CommandList = ({ items, command }: { items: CommandItemProps[]; command: a
<button
key={item.key}
className={cn(
- `flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-custom-text-100 hover:bg-custom-primary-100/5`,
+ `flex w-full items-center gap-2 rounded-md px-2.5 py-1.5 text-sm text-custom-text-100 hover:bg-custom-background-80`,
{
- "bg-custom-primary-100/5": index === selectedIndex,
+ "bg-custom-background-80": index === selectedIndex,
}
)}
onClick={() => selectItem(index)}
@@ -315,19 +324,21 @@ const CommandList = ({ items, command }: { items: CommandItemProps[]; command: a
) : null;
};
+interface CommandListInstance {
+ onKeyDown: (props: { event: KeyboardEvent }) => boolean;
+}
+
const renderItems = () => {
- let component: ReactRenderer | null = null;
+ let component: ReactRenderer<CommandListInstance, typeof CommandList> | null = null;
let popup: any | null = null;
-
return {
onStart: (props: { editor: Editor; clientRect?: (() => DOMRect | null) | null }) => {
component = new ReactRenderer(CommandList, {
props,
- // @ts-ignore
editor: props.editor,
});
- // @ts-ignore
+ // @ts-expect-error Tippy overloads are messed up
popup = tippy("body", {
getReferenceClientRect: props.clientRect,
appendTo: () => document.querySelector(".active-editor") ?? document.querySelector("#editor-container"),
@@ -353,8 +364,10 @@ const renderItems = () => {
return true;
}
- // @ts-ignore
- return component?.ref?.onKeyDown(props);
+ if (component?.ref?.onKeyDown(props)) {
+ return true;
+ }
+ return false;
},
onExit: () => {
popup?.[0].destroy();
@@ -363,14 +376,10 @@ const renderItems = () => {
};
};
-export const SlashCommand = (
- uploadFile: UploadImage,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void,
- additionalOptions?: Array<ISlashCommandItem>
-) =>
+export const SlashCommand = (uploadFile: UploadImage, additionalOptions?: Array<ISlashCommandItem>) =>
Command.configure({
suggestion: {
- items: getSuggestionItems(uploadFile, setIsSubmitting, additionalOptions),
+ items: getSuggestionItems(uploadFile, additionalOptions),
render: renderItems,
},
});
diff --git a/packages/editor/extensions/src/index.ts b/packages/editor/extensions/src/index.ts
index c0532c5940..440de1351b 100644
--- a/packages/editor/extensions/src/index.ts
+++ b/packages/editor/extensions/src/index.ts
@@ -1,4 +1,3 @@
import "src/styles/drag-drop.css";
-export { SlashCommand } from "src/extensions/slash-commands";
-export { DragAndDrop } from "src/extensions/drag-drop";
+export { DragAndDrop, SlashCommand } from "src/extensions";
diff --git a/packages/editor/extensions/src/styles/drag-drop.css b/packages/editor/extensions/src/styles/drag-drop.css
index d95a8654bd..d46d26ecca 100644
--- a/packages/editor/extensions/src/styles/drag-drop.css
+++ b/packages/editor/extensions/src/styles/drag-drop.css
@@ -1,25 +1,30 @@
+/* drag handle */
.drag-handle {
position: fixed;
opacity: 1;
transition: opacity ease-in 0.2s;
- height: 18px;
+ height: 20px;
width: 15px;
display: grid;
place-items: center;
- z-index: 10;
+ z-index: 5;
cursor: grab;
border-radius: 2px;
- background-color: rgb(var(--color-background-90));
-}
-
-.drag-handle:hover {
- background-color: rgb(var(--color-background-80));
transition: background-color 0.2s;
-}
-.drag-handle.hidden {
- opacity: 0;
- pointer-events: none;
+ &:hover {
+ background-color: rgba(var(--color-background-80));
+ }
+
+ &:active {
+ background-color: rgba(var(--color-background-80));
+ cursor: grabbing;
+ }
+
+ &.hidden {
+ opacity: 0;
+ pointer-events: none;
+ }
}
@media screen and (max-width: 600px) {
@@ -32,7 +37,6 @@
.drag-handle-container {
height: 15px;
width: 15px;
- cursor: grab;
display: grid;
place-items: center;
}
@@ -46,8 +50,46 @@
}
.drag-handle-dot {
- height: 2.75px;
- width: 3px;
- background-color: rgba(var(--color-text-200));
+ height: 2.5px;
+ width: 2.5px;
+ background-color: rgba(var(--color-text-300));
border-radius: 50%;
}
+/* end drag handle */
+
+.ProseMirror:not(.dragging) .ProseMirror-selectednode {
+ position: relative;
+ cursor: grab;
+ outline: none !important;
+ box-shadow: none;
+}
+
+.ProseMirror:not(.dragging) .ProseMirror-selectednode::after {
+ content: "";
+ position: absolute;
+ top: 0;
+ left: -5px;
+ height: 100%;
+ width: 100%;
+ background-color: rgba(var(--color-primary-100), 0.2);
+ border-radius: 4px;
+}
+
+.ProseMirror img {
+ transition: filter 0.1s ease-in-out;
+ cursor: pointer;
+
+ &:hover {
+ filter: brightness(90%);
+ }
+
+ &.ProseMirror-selectednode {
+ filter: brightness(90%);
+ }
+}
+
+:not(.dragging) .ProseMirror-selectednode.table-wrapper {
+ padding: 4px 2px;
+ background-color: rgba(var(--color-primary-300), 0.1) !important;
+ box-shadow: rgba(var(--color-primary-100)) 0px 0px 0px 2px inset !important;
+}
diff --git a/packages/editor/lite-text-editor/src/index.ts b/packages/editor/lite-text-editor/src/index.ts
index c37d45039f..3ca8c71db3 100644
--- a/packages/editor/lite-text-editor/src/index.ts
+++ b/packages/editor/lite-text-editor/src/index.ts
@@ -1,3 +1,7 @@
export { LiteTextEditor, LiteTextEditorWithRef } from "src/ui";
-export { LiteReadOnlyEditor, LiteReadOnlyEditorWithRef } from "src/ui/read-only";
+export { LiteTextReadOnlyEditor, LiteTextReadOnlyEditorWithRef } from "src/ui/read-only";
export type { IMentionSuggestion, IMentionHighlight } from "@plane/editor-core";
+
+export type { ILiteTextEditor } from "src/ui";
+export type { ILiteTextReadOnlyEditor } from "src/ui/read-only";
+export type { EditorRefApi, EditorReadOnlyRefApi, EditorMenuItem, EditorMenuItemNames } from "@plane/editor-core";
diff --git a/packages/editor/lite-text-editor/src/ui/index.tsx b/packages/editor/lite-text-editor/src/ui/index.tsx
index 7986e0c6b3..e610d071e1 100644
--- a/packages/editor/lite-text-editor/src/ui/index.tsx
+++ b/packages/editor/lite-text-editor/src/ui/index.tsx
@@ -8,124 +8,79 @@ import {
EditorContentWrapper,
getEditorClassNames,
useEditor,
+ IMentionHighlight,
+ EditorRefApi,
} from "@plane/editor-core";
-import { FixedMenu } from "src/ui/menus/fixed-menu";
import { LiteTextEditorExtensions } from "src/ui/extensions";
-interface ILiteTextEditor {
- value: string;
- uploadFile: UploadImage;
- deleteFile: DeleteImage;
- restoreFile: RestoreImage;
-
- noBorder?: boolean;
- borderOnFocus?: boolean;
- customClassName?: string;
- editorContentCustomClassNames?: string;
- onChange?: (json: any, html: string) => void;
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
- setShouldShowAlert?: (showAlert: boolean) => void;
- forwardedRef?: any;
- debouncedUpdatesEnabled?: boolean;
- commentAccessSpecifier?: {
- accessValue: string;
- onAccessChange: (accessKey: string) => void;
- showAccessSpecifier: boolean;
- commentAccess: {
- icon: any;
- key: string;
- label: "Private" | "Public";
- }[];
+export interface ILiteTextEditor {
+ initialValue: string;
+ value?: string | null;
+ fileHandler: {
+ cancel: () => void;
+ delete: DeleteImage;
+ upload: UploadImage;
+ restore: RestoreImage;
};
+ containerClassName?: string;
+ editorClassName?: string;
+ onChange?: (json: object, html: string) => void;
+ forwardedRef?: React.MutableRefObject<EditorRefApi | null>;
onEnterKeyPress?: (e?: any) => void;
- cancelUploadImage?: () => any;
- mentionHighlights?: string[];
- mentionSuggestions?: IMentionSuggestion[];
- submitButton?: React.ReactNode;
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
+ suggestions?: () => Promise<IMentionSuggestion[]>;
+ };
tabIndex?: number;
}
-interface LiteTextEditorProps extends ILiteTextEditor {
- forwardedRef?: React.Ref<EditorHandle>;
-}
-
-interface EditorHandle {
- clearEditor: () => void;
- setEditorValue: (content: string) => void;
-}
-
-const LiteTextEditor = (props: LiteTextEditorProps) => {
+const LiteTextEditor = (props: ILiteTextEditor) => {
const {
onChange,
- cancelUploadImage,
- debouncedUpdatesEnabled,
- setIsSubmitting,
- setShouldShowAlert,
- editorContentCustomClassNames,
+ initialValue,
+ fileHandler,
value,
- uploadFile,
- deleteFile,
- restoreFile,
- noBorder,
- borderOnFocus,
- customClassName,
+ containerClassName,
+ editorClassName = "",
forwardedRef,
- commentAccessSpecifier,
onEnterKeyPress,
- mentionHighlights,
- mentionSuggestions,
- submitButton,
tabIndex,
+ mentionHandler,
} = props;
const editor = useEditor({
onChange,
- cancelUploadImage,
- debouncedUpdatesEnabled,
- setIsSubmitting,
- setShouldShowAlert,
+ initialValue,
value,
- uploadFile,
- deleteFile,
- restoreFile,
+ editorClassName,
+ restoreFile: fileHandler.restore,
+ uploadFile: fileHandler.upload,
+ deleteFile: fileHandler.delete,
+ cancelUploadImage: fileHandler.cancel,
forwardedRef,
extensions: LiteTextEditorExtensions(onEnterKeyPress),
- mentionHighlights,
- mentionSuggestions,
+ mentionHandler,
});
- const editorClassNames = getEditorClassNames({
- noBorder,
- borderOnFocus,
- customClassName,
+ const editorContainerClassName = getEditorClassNames({
+ noBorder: true,
+ borderOnFocus: false,
+ containerClassName,
});
if (!editor) return null;
return (
- <EditorContainer editor={editor} editorClassNames={editorClassNames}>
+ <EditorContainer editor={editor} editorContainerClassName={editorContainerClassName}>
<div className="flex flex-col">
- <EditorContentWrapper
- tabIndex={tabIndex}
- editor={editor}
- editorContentCustomClassNames={editorContentCustomClassNames}
- />
- <div className="mt-4 w-full">
- <FixedMenu
- editor={editor}
- uploadFile={uploadFile}
- setIsSubmitting={setIsSubmitting}
- commentAccessSpecifier={commentAccessSpecifier}
- submitButton={submitButton}
- />
- </div>
+ <EditorContentWrapper tabIndex={tabIndex} editor={editor} />
</div>
</EditorContainer>
);
};
-const LiteTextEditorWithRef = React.forwardRef<EditorHandle, ILiteTextEditor>((props, ref) => (
- <LiteTextEditor {...props} forwardedRef={ref} />
+const LiteTextEditorWithRef = React.forwardRef<EditorRefApi, ILiteTextEditor>((props, ref) => (
+ <LiteTextEditor {...props} forwardedRef={ref as React.MutableRefObject<EditorRefApi | null>} />
));
LiteTextEditorWithRef.displayName = "LiteTextEditorWithRef";
diff --git a/packages/editor/lite-text-editor/src/ui/menus/fixed-menu/icon.tsx b/packages/editor/lite-text-editor/src/ui/menus/fixed-menu/icon.tsx
deleted file mode 100644
index 7ddc768436..0000000000
--- a/packages/editor/lite-text-editor/src/ui/menus/fixed-menu/icon.tsx
+++ /dev/null
@@ -1,10 +0,0 @@
-import React from "react";
-
-type Props = {
- iconName: string;
- className?: string;
-};
-
-export const Icon: React.FC<Props> = ({ iconName, className = "" }) => (
- <span className={`material-symbols-rounded text-sm font-light leading-5 ${className}`}>{iconName}</span>
-);
diff --git a/packages/editor/lite-text-editor/src/ui/menus/fixed-menu/index.tsx b/packages/editor/lite-text-editor/src/ui/menus/fixed-menu/index.tsx
deleted file mode 100644
index c6786698dd..0000000000
--- a/packages/editor/lite-text-editor/src/ui/menus/fixed-menu/index.tsx
+++ /dev/null
@@ -1,199 +0,0 @@
-import { Editor } from "@tiptap/react";
-
-import {
- BoldItem,
- BulletListItem,
- cn,
- CodeItem,
- findTableAncestor,
- ImageItem,
- isCellSelection,
- ItalicItem,
- LucideIconType,
- NumberedListItem,
- QuoteItem,
- StrikeThroughItem,
- TableItem,
- UnderLineItem,
- UploadImage,
-} from "@plane/editor-core";
-import { Tooltip } from "@plane/ui";
-
-export interface BubbleMenuItem {
- name: string;
- isActive: () => boolean;
- command: () => void;
- icon: LucideIconType;
-}
-
-type EditorBubbleMenuProps = {
- editor: Editor;
- commentAccessSpecifier?: {
- accessValue: string;
- onAccessChange: (accessKey: string) => void;
- showAccessSpecifier: boolean;
- commentAccess:
- | {
- icon: any;
- key: string;
- label: "Private" | "Public";
- }[]
- | undefined;
- };
- uploadFile: UploadImage;
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
- submitButton: React.ReactNode;
-};
-
-export const FixedMenu = (props: EditorBubbleMenuProps) => {
- const basicTextFormattingItems: BubbleMenuItem[] = [
- BoldItem(props.editor),
- ItalicItem(props.editor),
- UnderLineItem(props.editor),
- StrikeThroughItem(props.editor),
- ];
-
- const listFormattingItems: BubbleMenuItem[] = [BulletListItem(props.editor), NumberedListItem(props.editor)];
-
- const userActionItems: BubbleMenuItem[] = [QuoteItem(props.editor), CodeItem(props.editor)];
-
- function getComplexItems(): BubbleMenuItem[] {
- const items: BubbleMenuItem[] = [TableItem(props.editor)];
-
- items.push(ImageItem(props.editor, props.uploadFile, props.setIsSubmitting));
-
- return items;
- }
-
- const complexItems: BubbleMenuItem[] = getComplexItems();
-
- const handleAccessChange = (accessKey: string) => {
- props.commentAccessSpecifier?.onAccessChange(accessKey);
- };
-
- return (
- <div className="flex h-9 w-full items-stretch gap-1.5 overflow-x-scroll">
- {props.commentAccessSpecifier && (
- <div className="flex flex-shrink-0 items-stretch gap-0.5 rounded border-[0.5px] border-custom-border-200 p-1">
- {props?.commentAccessSpecifier.commentAccess?.map((access) => (
- <Tooltip key={access.key} tooltipContent={access.label}>
- <button
- type="button"
- onClick={() => handleAccessChange(access.key)}
- className={`grid aspect-square place-items-center rounded-sm p-1 hover:bg-custom-background-90 ${
- props.commentAccessSpecifier?.accessValue === access.key ? "bg-custom-background-90" : ""
- }`}
- >
- <access.icon
- className={`h-3.5 w-3.5 ${
- props.commentAccessSpecifier?.accessValue === access.key
- ? "text-custom-text-100"
- : "text-custom-text-400"
- }`}
- strokeWidth={2}
- />
- </button>
- </Tooltip>
- ))}
- </div>
- )}
- <div className="flex w-full items-stretch justify-between gap-2 rounded border-[0.5px] border-custom-border-200 bg-custom-background-90 p-1">
- <div className="flex items-stretch">
- <div className="flex items-stretch gap-0.5 border-r border-custom-border-200 pr-2.5">
- {basicTextFormattingItems.map((item) => (
- <Tooltip key={item.name} tooltipContent={<span className="capitalize">{item.name}</span>}>
- <button
- type="button"
- onClick={item.command}
- className={cn(
- "grid aspect-square place-items-center rounded-sm p-1 text-custom-text-400 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon
- className={cn("h-3.5 w-3.5", {
- "text-custom-text-100": item.isActive(),
- })}
- strokeWidth={2.5}
- />
- </button>
- </Tooltip>
- ))}
- </div>
- <div className="flex items-stretch gap-0.5 border-r border-custom-border-200 px-2.5">
- {listFormattingItems.map((item) => (
- <Tooltip key={item.name} tooltipContent={<span className="capitalize">{item.name}</span>}>
- <button
- type="button"
- onClick={item.command}
- className={cn(
- "grid aspect-square place-items-center rounded-sm p-1 text-custom-text-400 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon
- className={cn("h-3.5 w-3.5", {
- "text-custom-text-100": item.isActive(),
- })}
- strokeWidth={2.5}
- />
- </button>
- </Tooltip>
- ))}
- </div>
- <div className="flex items-stretch gap-0.5 border-r border-custom-border-200 px-2.5">
- {userActionItems.map((item) => (
- <Tooltip key={item.name} tooltipContent={<span className="capitalize">{item.name}</span>}>
- <button
- type="button"
- onClick={item.command}
- className={cn(
- "grid aspect-square place-items-center rounded-sm p-1 text-custom-text-400 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon
- className={cn("h-3.5 w-3.5", {
- "text-custom-text-100": item.isActive(),
- })}
- strokeWidth={2.5}
- />
- </button>
- </Tooltip>
- ))}
- </div>
- <div className="flex items-stretch gap-0.5 pl-2.5">
- {complexItems.map((item) => (
- <Tooltip key={item.name} tooltipContent={<span className="capitalize">{item.name}</span>}>
- <button
- type="button"
- onClick={item.command}
- className={cn(
- "grid aspect-square place-items-center rounded-sm p-1 text-custom-text-400 hover:bg-custom-background-80",
- {
- "bg-custom-background-80 text-custom-text-100": item.isActive(),
- }
- )}
- >
- <item.icon
- className={cn("h-3.5 w-3.5", {
- "text-custom-text-100": item.isActive(),
- })}
- strokeWidth={2.5}
- />
- </button>
- </Tooltip>
- ))}
- </div>
- </div>
- <div className="sticky right-1">{props.submitButton}</div>
- </div>
- </div>
- );
-};
diff --git a/packages/editor/lite-text-editor/src/ui/read-only/index.tsx b/packages/editor/lite-text-editor/src/ui/read-only/index.tsx
index 9f81ba5d13..5ceb6956ec 100644
--- a/packages/editor/lite-text-editor/src/ui/read-only/index.tsx
+++ b/packages/editor/lite-text-editor/src/ui/read-only/index.tsx
@@ -1,66 +1,59 @@
import * as React from "react";
-import { EditorContainer, EditorContentWrapper, getEditorClassNames, useReadOnlyEditor } from "@plane/editor-core";
-
-interface ICoreReadOnlyEditor {
- value: string;
- editorContentCustomClassNames?: string;
- noBorder?: boolean;
+import {
+ EditorContainer,
+ EditorContentWrapper,
+ EditorReadOnlyRefApi,
+ getEditorClassNames,
+ IMentionHighlight,
+ useReadOnlyEditor,
+} from "@plane/editor-core";
+
+export interface ILiteTextReadOnlyEditor {
+ initialValue: string;
borderOnFocus?: boolean;
- customClassName?: string;
- mentionHighlights: string[];
+ containerClassName?: string;
+ editorClassName?: string;
+ forwardedRef?: React.MutableRefObject<EditorReadOnlyRefApi | null>;
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
+ };
tabIndex?: number;
}
-interface EditorCoreProps extends ICoreReadOnlyEditor {
- forwardedRef?: React.Ref<EditorHandle>;
-}
-
-interface EditorHandle {
- clearEditor: () => void;
- setEditorValue: (content: string) => void;
-}
-
-const LiteReadOnlyEditor = ({
- editorContentCustomClassNames,
- noBorder,
- borderOnFocus,
- customClassName,
- value,
+const LiteTextReadOnlyEditor = ({
+ containerClassName,
+ editorClassName = "",
+ initialValue,
forwardedRef,
- mentionHighlights,
+ mentionHandler,
tabIndex,
-}: EditorCoreProps) => {
+}: ILiteTextReadOnlyEditor) => {
const editor = useReadOnlyEditor({
- value,
+ initialValue,
+ editorClassName,
forwardedRef,
- mentionHighlights,
+ mentionHandler,
});
- const editorClassNames = getEditorClassNames({
- noBorder,
- borderOnFocus,
- customClassName,
+ const editorContainerClassName = getEditorClassNames({
+ containerClassName,
});
if (!editor) return null;
return (
- <EditorContainer editor={editor} editorClassNames={editorClassNames}>
+ <EditorContainer editor={editor} editorContainerClassName={editorContainerClassName}>
<div className="flex flex-col">
- <EditorContentWrapper
- tabIndex={tabIndex}
- editor={editor}
- editorContentCustomClassNames={editorContentCustomClassNames}
- />
+ <EditorContentWrapper tabIndex={tabIndex} editor={editor} />
</div>
</EditorContainer>
);
};
-const LiteReadOnlyEditorWithRef = React.forwardRef<EditorHandle, ICoreReadOnlyEditor>((props, ref) => (
- <LiteReadOnlyEditor {...props} forwardedRef={ref} />
+const LiteTextReadOnlyEditorWithRef = React.forwardRef<EditorReadOnlyRefApi, ILiteTextReadOnlyEditor>((props, ref) => (
+ <LiteTextReadOnlyEditor {...props} forwardedRef={ref as React.MutableRefObject<EditorReadOnlyRefApi | null>} />
));
-LiteReadOnlyEditorWithRef.displayName = "LiteReadOnlyEditorWithRef";
+LiteTextReadOnlyEditorWithRef.displayName = "LiteReadOnlyEditorWithRef";
-export { LiteReadOnlyEditor, LiteReadOnlyEditorWithRef };
+export { LiteTextReadOnlyEditor, LiteTextReadOnlyEditorWithRef };
diff --git a/packages/editor/rich-text-editor/src/index.ts b/packages/editor/rich-text-editor/src/index.ts
index eb745c45bc..ad6f043a19 100644
--- a/packages/editor/rich-text-editor/src/index.ts
+++ b/packages/editor/rich-text-editor/src/index.ts
@@ -1,4 +1,8 @@
export { RichTextEditor, RichTextEditorWithRef } from "src/ui";
-export { RichReadOnlyEditor, RichReadOnlyEditorWithRef } from "src/ui/read-only";
-export type { RichTextEditorProps, IRichTextEditor } from "src/ui";
-export type { IMentionHighlight, IMentionSuggestion } from "@plane/editor-core";
+export { RichTextReadOnlyEditor, RichTextReadOnlyEditorWithRef } from "src/ui/read-only";
+
+export type { IRichTextEditor } from "src/ui";
+
+export type { IRichTextReadOnlyEditor } from "src/ui/read-only";
+export type { IMentionSuggestion, IMentionHighlight } from "@plane/editor-core";
+export type { EditorRefApi, EditorReadOnlyRefApi } from "@plane/editor-core";
diff --git a/packages/editor/rich-text-editor/src/ui/extensions/index.tsx b/packages/editor/rich-text-editor/src/ui/extensions/index.tsx
index 3d1da6cdab..57d2e0d41b 100644
--- a/packages/editor/rich-text-editor/src/ui/extensions/index.tsx
+++ b/packages/editor/rich-text-editor/src/ui/extensions/index.tsx
@@ -4,23 +4,21 @@ import Placeholder from "@tiptap/extension-placeholder";
export const RichTextEditorExtensions = (
uploadFile: UploadImage,
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void,
dragDropEnabled?: boolean,
setHideDragHandle?: (hideDragHandlerFromDragDrop: () => void) => void
) => [
- SlashCommand(uploadFile, setIsSubmitting),
+ SlashCommand(uploadFile),
dragDropEnabled === true && DragAndDrop(setHideDragHandle),
Placeholder.configure({
- placeholder: ({ node }) => {
+ placeholder: ({ editor, node }) => {
if (node.type.name === "heading") {
return `Heading ${node.attrs.level}`;
}
- if (node.type.name === "image" || node.type.name === "table") {
+
+ if (editor.isActive("table") || editor.isActive("codeBlock") || editor.isActive("image")) {
return "";
}
- if (node.type.name === "codeBlock") {
- return "Type in your code here...";
- }
+
return "Press '/' for commands...";
},
includeChildren: true,
diff --git a/packages/editor/rich-text-editor/src/ui/index.tsx b/packages/editor/rich-text-editor/src/ui/index.tsx
index 366fa471f0..33c14327ed 100644
--- a/packages/editor/rich-text-editor/src/ui/index.tsx
+++ b/packages/editor/rich-text-editor/src/ui/index.tsx
@@ -4,73 +4,56 @@ import {
EditorContainer,
EditorContentWrapper,
getEditorClassNames,
+ IMentionHighlight,
IMentionSuggestion,
RestoreImage,
UploadImage,
useEditor,
+ EditorRefApi,
} from "@plane/editor-core";
import * as React from "react";
import { RichTextEditorExtensions } from "src/ui/extensions";
import { EditorBubbleMenu } from "src/ui/menus/bubble-menu";
export type IRichTextEditor = {
- value: string;
- initialValue?: string;
+ initialValue: string;
+ value?: string | null;
dragDropEnabled?: boolean;
- uploadFile: UploadImage;
- restoreFile: RestoreImage;
- deleteFile: DeleteImage;
- noBorder?: boolean;
- borderOnFocus?: boolean;
- cancelUploadImage?: () => any;
- rerenderOnPropsChange?: {
- id: string;
- description_html: string;
+ fileHandler: {
+ cancel: () => void;
+ delete: DeleteImage;
+ upload: UploadImage;
+ restore: RestoreImage;
};
- customClassName?: string;
- editorContentCustomClassNames?: string;
- onChange?: (json: any, html: string) => void;
- setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
- setShouldShowAlert?: (showAlert: boolean) => void;
- forwardedRef?: any;
+ id?: string;
+ containerClassName?: string;
+ editorClassName?: string;
+ onChange?: (json: object, html: string) => void;
+ forwardedRef?: React.MutableRefObject<EditorRefApi | null>;
debouncedUpdatesEnabled?: boolean;
- mentionHighlights?: string[];
- mentionSuggestions?: IMentionSuggestion[];
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
+ suggestions: () => Promise<IMentionSuggestion[]>;
+ };
tabIndex?: number;
};
-export interface RichTextEditorProps extends IRichTextEditor {
- forwardedRef?: React.Ref<EditorHandle>;
-}
-
-interface EditorHandle {
- clearEditor: () => void;
- setEditorValue: (content: string) => void;
- setEditorValueAtCursorPosition: (content: string) => void;
-}
+const RichTextEditor = (props: IRichTextEditor) => {
+ const {
+ onChange,
+ dragDropEnabled,
+ initialValue,
+ value,
+ fileHandler,
+ containerClassName,
+ editorClassName = "",
+ forwardedRef,
+ // rerenderOnPropsChange,
+ id = "",
+ tabIndex,
+ mentionHandler,
+ } = props;
-const RichTextEditor = ({
- onChange,
- dragDropEnabled,
- debouncedUpdatesEnabled,
- setIsSubmitting,
- setShouldShowAlert,
- editorContentCustomClassNames,
- value,
- initialValue,
- uploadFile,
- deleteFile,
- noBorder,
- cancelUploadImage,
- borderOnFocus,
- customClassName,
- restoreFile,
- forwardedRef,
- mentionHighlights,
- rerenderOnPropsChange,
- mentionSuggestions,
- tabIndex,
-}: RichTextEditorProps) => {
const [hideDragHandleOnMouseLeave, setHideDragHandleOnMouseLeave] = React.useState<() => void>(() => {});
// this essentially sets the hideDragHandle function from the DragAndDrop extension as the Plugin
@@ -80,50 +63,45 @@ const RichTextEditor = ({
};
const editor = useEditor({
+ id,
+ editorClassName,
+ restoreFile: fileHandler.restore,
+ uploadFile: fileHandler.upload,
+ deleteFile: fileHandler.delete,
+ cancelUploadImage: fileHandler.cancel,
onChange,
- debouncedUpdatesEnabled,
- setIsSubmitting,
- setShouldShowAlert,
+ initialValue,
value,
- uploadFile,
- cancelUploadImage,
- deleteFile,
- restoreFile,
forwardedRef,
- rerenderOnPropsChange,
- extensions: RichTextEditorExtensions(uploadFile, setIsSubmitting, dragDropEnabled, setHideDragHandleFunction),
- mentionHighlights,
- mentionSuggestions,
+ // rerenderOnPropsChange,
+ extensions: RichTextEditorExtensions(fileHandler.upload, dragDropEnabled, setHideDragHandleFunction),
+ mentionHandler,
});
- const editorClassNames = getEditorClassNames({
- noBorder,
- borderOnFocus,
- customClassName,
+ const editorContainerClassName = getEditorClassNames({
+ noBorder: true,
+ borderOnFocus: false,
+ containerClassName,
});
- // React.useEffect(() => {
- // if (editor && initialValue && editor.getHTML() != initialValue) editor.commands.setContent(initialValue);
- // }, [editor, initialValue]);
- //
if (!editor) return null;
return (
- <EditorContainer hideDragHandle={hideDragHandleOnMouseLeave} editor={editor} editorClassNames={editorClassNames}>
+ <EditorContainer
+ hideDragHandle={hideDragHandleOnMouseLeave}
+ editor={editor}
+ editorContainerClassName={editorContainerClassName}
+ >
{editor && <EditorBubbleMenu editor={editor} />}
<div className="flex flex-col">
- <EditorContentWrapper
- tabIndex={tabIndex}
- editor={editor}
- editorContentCustomClassNames={editorContentCustomClassNames}
- />
+ <EditorContentWrapper tabIndex={tabIndex} editor={editor} />
</div>
</EditorContainer>
);
};
-const RichTextEditorWithRef = React.forwardRef<EditorHandle, IRichTextEditor>((props, ref) => (
- <RichTextEditor {...props} forwardedRef={ref} />
+const RichTextEditorWithRef = React.forwardRef<EditorRefApi, IRichTextEditor>((props, ref) => (
+ <RichTextEditor {...props} forwardedRef={ref as React.MutableRefObject<EditorRefApi | null>} />
));
RichTextEditorWithRef.displayName = "RichTextEditorWithRef";
diff --git a/packages/editor/rich-text-editor/src/ui/read-only/index.tsx b/packages/editor/rich-text-editor/src/ui/read-only/index.tsx
index 9aa3087315..3220c477ed 100644
--- a/packages/editor/rich-text-editor/src/ui/read-only/index.tsx
+++ b/packages/editor/rich-text-editor/src/ui/read-only/index.tsx
@@ -1,62 +1,54 @@
"use client";
-import { EditorContainer, EditorContentWrapper, getEditorClassNames, useReadOnlyEditor } from "@plane/editor-core";
+import {
+ EditorReadOnlyRefApi,
+ EditorContainer,
+ EditorContentWrapper,
+ getEditorClassNames,
+ IMentionHighlight,
+ useReadOnlyEditor,
+} from "@plane/editor-core";
import * as React from "react";
-interface IRichTextReadOnlyEditor {
- value: string;
- editorContentCustomClassNames?: string;
- noBorder?: boolean;
- borderOnFocus?: boolean;
- customClassName?: string;
- mentionHighlights?: string[];
+export interface IRichTextReadOnlyEditor {
+ initialValue: string;
+ containerClassName?: string;
+ editorClassName?: string;
tabIndex?: number;
+ forwardedRef?: React.MutableRefObject<EditorReadOnlyRefApi | null>;
+ mentionHandler: {
+ highlights: () => Promise<IMentionHighlight[]>;
+ };
}
-interface RichTextReadOnlyEditorProps extends IRichTextReadOnlyEditor {
- forwardedRef?: React.Ref<EditorHandle>;
-}
-
-interface EditorHandle {
- clearEditor: () => void;
- setEditorValue: (content: string) => void;
-}
+const RichTextReadOnlyEditor = (props: IRichTextReadOnlyEditor) => {
+ const { containerClassName, editorClassName = "", initialValue, forwardedRef, mentionHandler } = props;
-const RichReadOnlyEditor = ({
- editorContentCustomClassNames,
- noBorder,
- borderOnFocus,
- customClassName,
- value,
- forwardedRef,
- mentionHighlights,
-}: RichTextReadOnlyEditorProps) => {
const editor = useReadOnlyEditor({
- value,
+ initialValue,
+ editorClassName,
forwardedRef,
- mentionHighlights,
+ mentionHandler,
});
- const editorClassNames = getEditorClassNames({
- noBorder,
- borderOnFocus,
- customClassName,
+ const editorContainerClassName = getEditorClassNames({
+ containerClassName,
});
if (!editor) return null;
return (
- <EditorContainer editor={editor} editorClassNames={editorClassNames}>
+ <EditorContainer editor={editor} editorContainerClassName={editorContainerClassName}>
<div className="flex flex-col">
- <EditorContentWrapper editor={editor} editorContentCustomClassNames={editorContentCustomClassNames} />
+ <EditorContentWrapper editor={editor} />
</div>
</EditorContainer>
);
};
-const RichReadOnlyEditorWithRef = React.forwardRef<EditorHandle, IRichTextReadOnlyEditor>((props, ref) => (
- <RichReadOnlyEditor {...props} forwardedRef={ref} />
+const RichTextReadOnlyEditorWithRef = React.forwardRef<EditorReadOnlyRefApi, IRichTextReadOnlyEditor>((props, ref) => (
+ <RichTextReadOnlyEditor {...props} forwardedRef={ref as React.MutableRefObject<EditorReadOnlyRefApi | null>} />
));
-RichReadOnlyEditorWithRef.displayName = "RichReadOnlyEditorWithRef";
+RichTextReadOnlyEditorWithRef.displayName = "RichReadOnlyEditorWithRef";
-export { RichReadOnlyEditor, RichReadOnlyEditorWithRef };
+export { RichTextReadOnlyEditor, RichTextReadOnlyEditorWithRef };
diff --git a/packages/types/src/cycle/cycle.d.ts b/packages/types/src/cycle/cycle.d.ts
index 28be2ec2a4..e93d6e4443 100644
--- a/packages/types/src/cycle/cycle.d.ts
+++ b/packages/types/src/cycle/cycle.d.ts
@@ -97,10 +97,6 @@ export type SelectCycleType =
| (ICycle & { actionType: "edit" | "delete" | "create-issue" })
| undefined;
-export type SelectIssue =
- | (TIssue & { actionType: "edit" | "delete" | "create" })
- | null;
-
export type CycleDateCheckData = {
start_date: string;
end_date: string;
diff --git a/packages/types/src/cycle/index.ts b/packages/types/src/cycle/index.d.ts
similarity index 100%
rename from packages/types/src/cycle/index.ts
rename to packages/types/src/cycle/index.d.ts
diff --git a/packages/types/src/dashboard.ts b/packages/types/src/dashboard.d.ts
similarity index 96%
rename from packages/types/src/dashboard.ts
rename to packages/types/src/dashboard.d.ts
index be7d7b3be7..9abd1bf22c 100644
--- a/packages/types/src/dashboard.ts
+++ b/packages/types/src/dashboard.d.ts
@@ -1,17 +1,9 @@
+import { EDurationFilters } from "./enums";
import { IIssueActivity, TIssuePriorities } from "./issues";
import { TIssue } from "./issues/issue";
import { TIssueRelationTypes } from "./issues/issue_relation";
import { TStateGroups } from "./state";
-enum EDurationFilters {
- NONE = "none",
- TODAY = "today",
- THIS_WEEK = "this_week",
- THIS_MONTH = "this_month",
- THIS_YEAR = "this_year",
- CUSTOM = "custom",
-}
-
export type TWidgetKeys =
| "overview_stats"
| "assigned_issues"
diff --git a/packages/types/src/enums.ts b/packages/types/src/enums.ts
index 259f13e9bc..a4d098506e 100644
--- a/packages/types/src/enums.ts
+++ b/packages/types/src/enums.ts
@@ -4,3 +4,23 @@ export enum EUserProjectRoles {
MEMBER = 15,
ADMIN = 20,
}
+
+// project pages
+export enum EPageAccess {
+ PUBLIC = 0,
+ PRIVATE = 1,
+}
+
+export enum EDurationFilters {
+ NONE = "none",
+ TODAY = "today",
+ THIS_WEEK = "this_week",
+ THIS_MONTH = "this_month",
+ THIS_YEAR = "this_year",
+ CUSTOM = "custom",
+}
+
+export enum EIssueCommentAccessSpecifier {
+ EXTERNAL = "EXTERNAL",
+ INTERNAL = "INTERNAL",
+}
diff --git a/packages/types/src/issues/activity/issue_comment.d.ts b/packages/types/src/issues/activity/issue_comment.d.ts
index 45d34be082..f361ea7201 100644
--- a/packages/types/src/issues/activity/issue_comment.d.ts
+++ b/packages/types/src/issues/activity/issue_comment.d.ts
@@ -4,6 +4,7 @@ import {
TIssueActivityIssueDetail,
TIssueActivityUserDetail,
} from "./base";
+import { EIssueCommentAccessSpecifier } from "../../enums";
export type TIssueComment = {
id: string;
@@ -20,14 +21,13 @@ export type TIssueComment = {
created_by: string | undefined;
updated_by: string | undefined;
attachments: any[];
-
comment_reactions: any[];
comment_stripped: string;
comment_html: string;
comment_json: object;
external_id: string | undefined;
external_source: string | undefined;
- access: "EXTERNAL" | "INTERNAL";
+ access: EIssueCommentAccessSpecifier;
};
export type TIssueCommentMap = {
diff --git a/packages/types/src/module/index.ts b/packages/types/src/module/index.d.ts
similarity index 100%
rename from packages/types/src/module/index.ts
rename to packages/types/src/module/index.d.ts
diff --git a/packages/types/src/module/modules.d.ts b/packages/types/src/module/modules.d.ts
index 95b084f2f9..0019781bad 100644
--- a/packages/types/src/module/modules.d.ts
+++ b/packages/types/src/module/modules.d.ts
@@ -1,4 +1,11 @@
-import type { TIssue, IIssueFilterOptions, ILinkDetails } from "@plane/types";
+import type {
+ TIssue,
+ IIssueFilterOptions,
+ ILinkDetails,
+ TAssigneesDistribution,
+ TCompletionChartDistribution,
+ TLabelsDistribution,
+} from "@plane/types";
export type TModuleStatus =
| "backlog"
@@ -69,7 +76,3 @@ export type ModuleLink = {
export type SelectModuleType =
| (IModule & { actionType: "edit" | "delete" | "create-issue" })
| undefined;
-
-export type SelectIssue =
- | (TIssue & { actionType: "edit" | "delete" | "create" })
- | undefined;
diff --git a/packages/types/src/notifications.d.ts b/packages/types/src/notifications.d.ts
index 652e2776f5..571b757655 100644
--- a/packages/types/src/notifications.d.ts
+++ b/packages/types/src/notifications.d.ts
@@ -36,7 +36,7 @@ export interface IUserNotification {
}
export interface Data {
- issue: IIssueLite;
+ issue: INotificationIssueLite;
issue_activity: {
actor: string;
field: string;
@@ -48,7 +48,7 @@ export interface Data {
};
}
-export interface IIssueLite {
+export interface INotificationIssueLite {
id: string;
name: string;
identifier: string;
diff --git a/packages/types/src/pages.d.ts b/packages/types/src/pages.d.ts
index 6e1e78be52..a1df4527ea 100644
--- a/packages/types/src/pages.d.ts
+++ b/packages/types/src/pages.d.ts
@@ -1,64 +1,50 @@
-// types
-import {
- TIssue,
- IIssueLabel,
- IWorkspaceLite,
- IProjectLite,
-} from "@plane/types";
+import { EPageAccess } from "./enums";
-export interface IPage {
- access: number;
- archived_at: string | null;
- blocks: IPageBlock[];
- color: string;
- created_at: string | null;
- created_by: string;
- description: string;
- description_html: string;
- description_stripped: string | null;
- id: string;
+export type TPage = {
+ access: EPageAccess | undefined;
+ archived_at: string | null | undefined;
+ color: string | undefined;
+ created_at: Date | undefined;
+ created_by: string | undefined;
+ description_html: string | undefined;
+ id: string | undefined;
is_favorite: boolean;
is_locked: boolean;
- label_details: IIssueLabel[];
- labels: string[];
- name: string;
- owned_by: string;
- project: string;
- project_detail: IProjectLite;
- updated_at: string | null;
- updated_by: string;
- workspace: string;
- workspace_detail: IWorkspaceLite;
-}
+ labels: string[] | undefined;
+ name: string | undefined;
+ owned_by: string | undefined;
+ project: string | undefined;
+ updated_at: Date | undefined;
+ updated_by: string | undefined;
+ view_props: TPageViewProps | undefined;
+ workspace: string | undefined;
+};
-export interface IRecentPages {
- today: string[];
- yesterday: string[];
- this_week: string[];
- older: string[];
- [key: string]: string[];
-}
+export type TPageViewProps = {
+ full_width?: boolean;
+};
-export interface IPageBlock {
- completed_at: Date | null;
- created_at: Date;
- created_by: string;
- description: any;
- description_html: any;
- description_stripped: any;
- id: string;
- issue: string | null;
- issue_detail: TIssue | null;
- name: string;
- page: string;
- project: string;
- project_detail: IProjectLite;
- sort_order: number;
- sync: boolean;
- updated_at: Date;
- updated_by: string;
- workspace: string;
- workspace_detail: IWorkspaceLite;
-}
+// page filters
+export type TPageNavigationTabs = "public" | "private" | "archived";
-export type TPageViewProps = "list" | "detailed" | "masonry";
+export type TPageFiltersSortKey =
+ | "name"
+ | "created_at"
+ | "updated_at"
+ | "opened_at";
+
+export type TPageFiltersSortBy = "asc" | "desc";
+
+export type TPageFilterProps = {
+ created_at?: string[] | null;
+ created_by?: string[] | null;
+ favorites?: boolean;
+ labels?: string[] | null;
+};
+
+export type TPageFilters = {
+ searchQuery: string;
+ sortKey: TPageFiltersSortKey;
+ sortBy: TPageFiltersSortBy;
+ filters?: TPageFilterProps;
+};
diff --git a/packages/ui/src/form-fields/textarea.tsx b/packages/ui/src/form-fields/textarea.tsx
index b93c1aba8c..271b76d83a 100644
--- a/packages/ui/src/form-fields/textarea.tsx
+++ b/packages/ui/src/form-fields/textarea.tsx
@@ -1,4 +1,6 @@
import * as React from "react";
+// helpers
+import { cn } from "../../helpers";
export interface TextAreaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
mode?: "primary" | "transparent";
@@ -46,13 +48,17 @@ const TextArea = React.forwardRef<HTMLTextAreaElement, TextAreaProps>((props, re
value={value}
rows={rows}
cols={cols}
- className={`no-scrollbar w-full bg-transparent px-3 py-2 placeholder-custom-text-400 outline-none ${
- mode === "primary"
- ? "rounded-md border-[0.5px] border-custom-border-200"
- : mode === "transparent"
- ? "focus:ring-theme rounded border-none bg-transparent ring-0 transition-all focus:ring-1"
- : ""
- } ${hasError ? "border-red-500" : ""} ${hasError && mode === "primary" ? "bg-red-100" : ""} ${className}`}
+ className={cn(
+ "no-scrollbar w-full bg-transparent px-3 py-2 placeholder-custom-text-400 outline-none",
+ {
+ "rounded-md border-[0.5px] border-custom-border-200": mode === "primary",
+ "focus:ring-theme rounded border-none bg-transparent ring-0 transition-all focus:ring-1":
+ mode === "transparent",
+ "border-red-500": hasError,
+ "bg-red-100": hasError && mode === "primary",
+ },
+ className
+ )}
{...rest}
/>
);
diff --git a/space/components/editor/index.ts b/space/components/editor/index.ts
new file mode 100644
index 0000000000..4ec0141e20
--- /dev/null
+++ b/space/components/editor/index.ts
@@ -0,0 +1,4 @@
+export * from "./lite-text-editor";
+export * from "./lite-text-read-only-editor";
+export * from "./rich-text-read-only-editor";
+export * from "./toolbar";
diff --git a/space/components/editor/lite-text-editor.tsx b/space/components/editor/lite-text-editor.tsx
new file mode 100644
index 0000000000..677a342571
--- /dev/null
+++ b/space/components/editor/lite-text-editor.tsx
@@ -0,0 +1,76 @@
+import React from "react";
+// editor
+import { EditorRefApi, ILiteTextEditor, LiteTextEditorWithRef } from "@plane/lite-text-editor";
+// components
+import { IssueCommentToolbar } from "@/components/editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
+import { isEmptyHtmlString } from "@/helpers/string.helper";
+// hooks
+import { useMention } from "@/hooks/use-mention";
+// services
+import fileService from "@/services/file.service";
+
+interface LiteTextEditorWrapperProps extends Omit<ILiteTextEditor, "fileHandler" | "mentionHandler"> {
+ workspaceSlug: string;
+ workspaceId: string;
+ isSubmitting?: boolean;
+ showSubmitButton?: boolean;
+}
+
+export const LiteTextEditor = React.forwardRef<EditorRefApi, LiteTextEditorWrapperProps>((props, ref) => {
+ const {
+ containerClassName,
+ workspaceSlug,
+ workspaceId,
+ isSubmitting = false,
+ showSubmitButton = true,
+ ...rest
+ } = props;
+ // use-mention
+ const { mentionHighlights } = useMention();
+
+ function isMutableRefObject<T>(ref: React.ForwardedRef<T>): ref is React.MutableRefObject<T | null> {
+ return !!ref && typeof ref === "object" && "current" in ref;
+ }
+ const isEmpty =
+ props.initialValue === "" ||
+ props.initialValue?.trim() === "" ||
+ props.initialValue === "<p></p>" ||
+ isEmptyHtmlString(props.initialValue ?? "");
+
+ return (
+ <div className="border border-custom-border-200 rounded p-3 space-y-3">
+ <LiteTextEditorWithRef
+ ref={ref}
+ fileHandler={{
+ upload: fileService.getUploadFileFunction(workspaceSlug),
+ delete: fileService.getDeleteImageFunction(workspaceId),
+ restore: fileService.getRestoreImageFunction(workspaceId),
+ cancel: fileService.cancelUpload,
+ }}
+ mentionHandler={{
+ highlights: mentionHighlights,
+ // suggestions disabled for now
+ }}
+ {...rest}
+ // overriding the containerClassName to add relative class passed
+ containerClassName={cn(containerClassName, "relative")}
+ />
+ <IssueCommentToolbar
+ executeCommand={(key) => {
+ if (isMutableRefObject<EditorRefApi>(ref)) {
+ ref.current?.executeMenuItemCommand(key);
+ }
+ }}
+ isSubmitting={isSubmitting}
+ showSubmitButton={showSubmitButton}
+ handleSubmit={(e) => rest.onEnterKeyPress?.(e)}
+ isCommentEmpty={isEmpty}
+ editorRef={isMutableRefObject<EditorRefApi>(ref) ? ref : null}
+ />
+ </div>
+ );
+});
+
+LiteTextEditor.displayName = "LiteTextEditor";
diff --git a/space/components/editor/lite-text-read-only-editor.tsx b/space/components/editor/lite-text-read-only-editor.tsx
new file mode 100644
index 0000000000..6b16a0b074
--- /dev/null
+++ b/space/components/editor/lite-text-read-only-editor.tsx
@@ -0,0 +1,29 @@
+import React from "react";
+// editor
+import { EditorReadOnlyRefApi, ILiteTextReadOnlyEditor, LiteTextReadOnlyEditorWithRef } from "@plane/lite-text-editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// hooks
+import { useMention } from "@/hooks/use-mention";
+
+interface LiteTextReadOnlyEditorWrapperProps extends Omit<ILiteTextReadOnlyEditor, "mentionHandler"> {}
+
+export const LiteTextReadOnlyEditor = React.forwardRef<EditorReadOnlyRefApi, LiteTextReadOnlyEditorWrapperProps>(
+ ({ ...props }, ref) => {
+ const { mentionHighlights } = useMention();
+
+ return (
+ <LiteTextReadOnlyEditorWithRef
+ ref={ref}
+ mentionHandler={{
+ highlights: mentionHighlights,
+ }}
+ {...props}
+ // overriding the customClassName to add relative class passed
+ containerClassName={cn(props.containerClassName, "relative p-2")}
+ />
+ );
+ }
+);
+
+LiteTextReadOnlyEditor.displayName = "LiteTextReadOnlyEditor";
diff --git a/space/components/editor/rich-text-read-only-editor.tsx b/space/components/editor/rich-text-read-only-editor.tsx
new file mode 100644
index 0000000000..562e635814
--- /dev/null
+++ b/space/components/editor/rich-text-read-only-editor.tsx
@@ -0,0 +1,27 @@
+import React from "react";
+// editor
+import { EditorReadOnlyRefApi, IRichTextReadOnlyEditor, RichTextReadOnlyEditorWithRef } from "@plane/rich-text-editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// hooks
+import { useMention } from "@/hooks/use-mention";
+
+interface RichTextReadOnlyEditorWrapperProps extends Omit<IRichTextReadOnlyEditor, "mentionHandler"> {}
+
+export const RichTextReadOnlyEditor = React.forwardRef<EditorReadOnlyRefApi, RichTextReadOnlyEditorWrapperProps>(
+ ({ ...props }, ref) => {
+ const { mentionHighlights } = useMention();
+
+ return (
+ <RichTextReadOnlyEditorWithRef
+ ref={ref}
+ mentionHandler={{ highlights: mentionHighlights }}
+ {...props}
+ // overriding the customClassName to add relative class passed
+ containerClassName={cn(props.containerClassName, "relative border border-custom-border-200 p-3")}
+ />
+ );
+ }
+);
+
+RichTextReadOnlyEditor.displayName = "RichTextReadOnlyEditor";
diff --git a/space/components/editor/toolbar.tsx b/space/components/editor/toolbar.tsx
new file mode 100644
index 0000000000..19bbdab9a7
--- /dev/null
+++ b/space/components/editor/toolbar.tsx
@@ -0,0 +1,110 @@
+import React, { useEffect, useState, useCallback } from "react";
+// editor
+import { EditorMenuItemNames, EditorRefApi } from "@plane/lite-text-editor";
+// ui
+import { Button, Tooltip } from "@plane/ui";
+// constants
+import { TOOLBAR_ITEMS } from "@/constants/editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
+
+type Props = {
+ executeCommand: (commandName: EditorMenuItemNames) => void;
+ handleSubmit: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
+ isCommentEmpty: boolean;
+ isSubmitting: boolean;
+ showSubmitButton: boolean;
+ editorRef: React.MutableRefObject<EditorRefApi | null> | null;
+};
+
+const toolbarItems = TOOLBAR_ITEMS.lite;
+
+export const IssueCommentToolbar: React.FC<Props> = (props) => {
+ const { executeCommand, handleSubmit, isCommentEmpty, editorRef, isSubmitting, showSubmitButton } = props;
+ // states
+ const [activeStates, setActiveStates] = useState<Record<string, boolean>>({});
+
+ // Function to update active states
+ const updateActiveStates = useCallback(() => {
+ if (editorRef?.current) {
+ const newActiveStates: Record<string, boolean> = {};
+ Object.values(toolbarItems)
+ .flat()
+ .forEach((item) => {
+ // Assert that editorRef.current is not null
+ newActiveStates[item.key] = (editorRef.current as EditorRefApi).isMenuItemActive(item.key);
+ });
+ setActiveStates(newActiveStates);
+ }
+ }, [editorRef]);
+
+ // useEffect to call updateActiveStates when isActive prop changes
+ useEffect(() => {
+ if (!editorRef?.current) return;
+ const unsubscribe = editorRef.current.onStateChange(updateActiveStates);
+ updateActiveStates();
+ return () => unsubscribe();
+ }, [editorRef, updateActiveStates]);
+
+ return (
+ <div className="flex h-9 w-full items-stretch gap-1.5 bg-custom-background-90 overflow-x-scroll">
+ <div className="flex w-full items-stretch justify-between gap-2 rounded border-[0.5px] border-custom-border-200 p-1">
+ <div className="flex items-stretch">
+ {Object.keys(toolbarItems).map((key, index) => (
+ <div
+ key={key}
+ className={cn("flex items-stretch gap-0.5 border-r border-custom-border-200 px-2.5", {
+ "pl-0": index === 0,
+ "pr-0": index === Object.keys(toolbarItems).length - 1,
+ })}
+ >
+ {toolbarItems[key].map((item) => (
+ <Tooltip
+ key={item.key}
+ tooltipContent={
+ <p className="flex flex-col gap-1 text-center text-xs">
+ <span className="font-medium">{item.name}</span>
+ {item.shortcut && <kbd className="text-custom-text-400">{item.shortcut.join(" + ")}</kbd>}
+ </p>
+ }
+ >
+ <button
+ type="button"
+ onClick={() => executeCommand(item.key)}
+ className={cn(
+ "grid place-items-center aspect-square rounded-sm p-0.5 text-custom-text-400 hover:bg-custom-background-80",
+ {
+ "bg-custom-background-80 text-custom-text-100": activeStates[item.key],
+ }
+ )}
+ >
+ <item.icon
+ className={cn("h-3.5 w-3.5", {
+ "text-custom-text-100": activeStates[item.key],
+ })}
+ strokeWidth={2.5}
+ />
+ </button>
+ </Tooltip>
+ ))}
+ </div>
+ ))}
+ </div>
+ {showSubmitButton && (
+ <div className="sticky right-1">
+ <Button
+ type="submit"
+ variant="primary"
+ className="px-2.5 py-1.5 text-xs"
+ onClick={handleSubmit}
+ disabled={isCommentEmpty}
+ loading={isSubmitting}
+ >
+ Comment
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/space/components/issues/peek-overview/comment/add-comment.tsx b/space/components/issues/peek-overview/comment/add-comment.tsx
index 6df72e2a87..8ec5b125a7 100644
--- a/space/components/issues/peek-overview/comment/add-comment.tsx
+++ b/space/components/issues/peek-overview/comment/add-comment.tsx
@@ -2,19 +2,15 @@ import React, { useRef } from "react";
import { observer } from "mobx-react-lite";
import { useRouter } from "next/router";
import { useForm, Controller } from "react-hook-form";
+// components
+import { EditorRefApi } from "@plane/lite-text-editor";
+import { LiteTextEditor } from "@/components/editor/lite-text-editor";
+// hooks
+import useToast from "@/hooks/use-toast";
// lib
-import { LiteTextEditorWithRef } from "@plane/lite-text-editor";
-import { Button } from "@plane/ui";
import { useMobxStore } from "@/lib/mobx/store-provider";
-// hooks
-import fileService from "@/services/file.service";
-import { RootStore } from "@/store/root";
-import useToast from "hooks/use-toast";
-// ui
// types
-import { Comment } from "types/issue";
-// components
-// service
+import { Comment } from "@/types/issue";
const defaultValues: Partial<Comment> = {
comment_html: "",
@@ -24,9 +20,20 @@ type Props = {
disabled?: boolean;
};
-export const AddComment: React.FC<Props> = observer((props) => {
- const { disabled = false } = props;
-
+export const AddComment: React.FC<Props> = observer(() => {
+ // const { disabled = false } = props;
+ // refs
+ const editorRef = useRef<EditorRefApi>(null);
+ // router
+ const router = useRouter();
+ const { workspace_slug, project_slug } = router.query;
+ // store hooks
+ const { project } = useMobxStore();
+ const { user: userStore, issueDetails: issueDetailStore } = useMobxStore();
+ // derived values
+ const workspaceId = project.workspace?.id;
+ const issueId = issueDetailStore.peekId;
+ // form info
const {
handleSubmit,
control,
@@ -34,37 +41,25 @@ export const AddComment: React.FC<Props> = observer((props) => {
formState: { isSubmitting },
reset,
} = useForm<Comment>({ defaultValues });
-
- const router = useRouter();
- const { project }: RootStore = useMobxStore();
- const workspaceId = project.workspace?.id;
-
- const { workspace_slug, project_slug } = router.query as { workspace_slug: string; project_slug: string };
-
- const { user: userStore, issueDetails: issueDetailStore } = useMobxStore();
-
- const issueId = issueDetailStore.peekId;
-
- const editorRef = useRef<any>(null);
-
+ // toast alert
const { setToastAlert } = useToast();
const onSubmit = async (formData: Comment) => {
if (!workspace_slug || !project_slug || !issueId || isSubmitting || !formData.comment_html) return;
await issueDetailStore
- .addIssueComment(workspace_slug, project_slug, issueId, formData)
+ .addIssueComment(workspace_slug.toString(), project_slug.toString(), issueId, formData)
.then(() => {
reset(defaultValues);
editorRef.current?.clearEditor();
})
- .catch(() => {
+ .catch(() =>
setToastAlert({
type: "error",
title: "Error!",
message: "Comment could not be posted. Please try again.",
- });
- });
+ })
+ );
};
return (
@@ -74,43 +69,18 @@ export const AddComment: React.FC<Props> = observer((props) => {
name="comment_html"
control={control}
render={({ field: { value, onChange } }) => (
- <LiteTextEditorWithRef
- onEnterKeyPress={(e) => {
- userStore.requiredLogin(() => {
- handleSubmit(onSubmit)(e);
- });
- }}
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspace_slug as string)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId as string)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId as string)}
+ <LiteTextEditor
+ onEnterKeyPress={(e) => userStore.requiredLogin(() => handleSubmit(onSubmit)(e))}
+ workspaceId={workspaceId as string}
+ workspaceSlug={workspace_slug as string}
ref={editorRef}
- value={
+ initialValue={
!value || value === "" || (typeof value === "object" && Object.keys(value).length === 0)
? watch("comment_html")
: value
}
- customClassName="p-2"
- editorContentCustomClassNames="min-h-[35px]"
- debouncedUpdatesEnabled={false}
- onChange={(comment_json: unknown, comment_html: string) => {
- onChange(comment_html);
- }}
- submitButton={
- <Button
- disabled={isSubmitting || disabled}
- variant="primary"
- type="submit"
- className="!px-2.5 !py-1.5 !text-xs"
- onClick={(e) => {
- userStore.requiredLogin(() => {
- handleSubmit(onSubmit)(e);
- });
- }}
- >
- {isSubmitting ? "Adding..." : "Comment"}
- </Button>
- }
+ onChange={(comment_json, comment_html) => onChange(comment_html)}
+ isSubmitting={isSubmitting}
/>
)}
/>
diff --git a/space/components/issues/peek-overview/comment/comment-detail-card.tsx b/space/components/issues/peek-overview/comment/comment-detail-card.tsx
index 3db64bbd1d..e1a1394135 100644
--- a/space/components/issues/peek-overview/comment/comment-detail-card.tsx
+++ b/space/components/issues/peek-overview/comment/comment-detail-card.tsx
@@ -1,23 +1,21 @@
-import React, { useState } from "react";
+import React, { useRef, useState } from "react";
import { observer } from "mobx-react-lite";
import { Controller, useForm } from "react-hook-form";
import { Check, MessageSquare, MoreVertical, X } from "lucide-react";
import { Menu, Transition } from "@headlessui/react";
-// mobx store
// components
-import { LiteReadOnlyEditorWithRef, LiteTextEditorWithRef } from "@plane/lite-text-editor";
-
+import { EditorRefApi } from "@plane/lite-text-editor";
+import { LiteTextEditor, LiteTextReadOnlyEditor } from "@/components/editor";
import { CommentReactions } from "@/components/issues/peek-overview";
// helpers
import { timeAgo } from "@/helpers/date-time.helper";
+// mobx store
import { useMobxStore } from "@/lib/mobx/store-provider";
-// types
-// services
-import fileService from "@/services/file.service";
+// store
import { RootStore } from "@/store/root";
-import useEditorSuggestions from "hooks/use-editor-suggestions";
+// types
+import { Comment } from "@/types/issue";
-import { Comment } from "types/issue";
type Props = {
workspaceSlug: string;
comment: Comment;
@@ -32,12 +30,10 @@ export const CommentCard: React.FC<Props> = observer((props) => {
const { user: userStore, issueDetails: issueDetailStore } = useMobxStore();
// states
const [isEditing, setIsEditing] = useState(false);
-
- const mentionsConfig = useEditorSuggestions();
-
- const editorRef = React.useRef<any>(null);
-
- const showEditorRef = React.useRef<any>(null);
+ // refs
+ const editorRef = useRef<EditorRefApi>(null);
+ const showEditorRef = useRef<EditorRefApi>(null);
+ // form info
const {
control,
formState: { isSubmitting },
@@ -105,19 +101,16 @@ export const CommentCard: React.FC<Props> = observer((props) => {
control={control}
name="comment_html"
render={({ field: { onChange, value } }) => (
- <LiteTextEditorWithRef
+ <LiteTextEditor
+ workspaceId={workspaceId as string}
+ workspaceSlug={workspaceSlug}
onEnterKeyPress={handleSubmit(handleCommentUpdate)}
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId as string)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId as string)}
ref={editorRef}
- value={value}
- debouncedUpdatesEnabled={false}
- customClassName="min-h-[50px] p-3 shadow-sm"
- onChange={(comment_json: unknown, comment_html: string) => {
- onChange(comment_html);
- }}
+ initialValue={value}
+ value={null}
+ onChange={(comment_json, comment_html) => onChange(comment_html)}
+ isSubmitting={isSubmitting}
+ showSubmitButton={false}
/>
)}
/>
@@ -140,12 +133,7 @@ export const CommentCard: React.FC<Props> = observer((props) => {
</div>
</form>
<div className={`${isEditing ? "hidden" : ""}`}>
- <LiteReadOnlyEditorWithRef
- ref={showEditorRef}
- value={comment.comment_html}
- customClassName="text-xs border border-custom-border-200 bg-custom-background-100"
- mentionHighlights={mentionsConfig.mentionHighlights}
- />
+ <LiteTextReadOnlyEditor ref={showEditorRef} initialValue={comment.comment_html} />
<CommentReactions commentId={comment.id} projectId={comment.project} />
</div>
</div>
diff --git a/space/components/issues/peek-overview/full-screen-peek-view.tsx b/space/components/issues/peek-overview/full-screen-peek-view.tsx
index 32b850b128..5ab4dffd71 100644
--- a/space/components/issues/peek-overview/full-screen-peek-view.tsx
+++ b/space/components/issues/peek-overview/full-screen-peek-view.tsx
@@ -8,11 +8,12 @@ import {
PeekOverviewIssueProperties,
} from "@/components/issues/peek-overview";
// types
-import { IIssue } from "types/issue";
+import { IIssue } from "@/types/issue";
type Props = {
handleClose: () => void;
issueDetails: IIssue | undefined;
+ workspace_slug: string;
};
export const FullScreenPeekView: React.FC<Props> = observer((props) => {
diff --git a/space/components/issues/peek-overview/issue-details.tsx b/space/components/issues/peek-overview/issue-details.tsx
index dfc1be430f..5fe73f67a4 100644
--- a/space/components/issues/peek-overview/issue-details.tsx
+++ b/space/components/issues/peek-overview/issue-details.tsx
@@ -1,37 +1,30 @@
-import { RichReadOnlyEditor } from "@plane/rich-text-editor";
+// components
+import { RichTextReadOnlyEditor } from "@/components/editor";
import { IssueReactions } from "@/components/issues/peek-overview";
// types
-import useEditorSuggestions from "hooks/use-editor-suggestions";
-import { IIssue } from "types/issue";
+import { IIssue } from "@/types/issue";
type Props = {
issueDetails: IIssue;
};
-export const PeekOverviewIssueDetails: React.FC<Props> = ({ issueDetails }) => {
- const mentionConfig = useEditorSuggestions();
-
- return (
- <div className="space-y-2">
- <h6 className="font-medium text-custom-text-200">
- {issueDetails.project_detail.identifier}-{issueDetails.sequence_id}
- </h6>
- <h4 className="break-words text-2xl font-semibold">{issueDetails.name}</h4>
- {issueDetails.description_html !== "" && issueDetails.description_html !== "<p></p>" && (
- <RichReadOnlyEditor
- value={
- !issueDetails.description_html ||
- issueDetails.description_html === "" ||
- (typeof issueDetails.description_html === "object" &&
- Object.keys(issueDetails.description_html).length === 0)
- ? "<p></p>"
- : issueDetails.description_html
- }
- customClassName="p-3 min-h-[50px] shadow-sm"
- mentionHighlights={mentionConfig.mentionHighlights}
- />
- )}
- <IssueReactions />
- </div>
- );
-};
+export const PeekOverviewIssueDetails: React.FC<Props> = ({ issueDetails }) => (
+ <div className="space-y-2">
+ <h6 className="font-medium text-custom-text-200">
+ {issueDetails.project_detail.identifier}-{issueDetails.sequence_id}
+ </h6>
+ <h4 className="break-words text-2xl font-semibold">{issueDetails.name}</h4>
+ {issueDetails.description_html !== "" && issueDetails.description_html !== "<p></p>" && (
+ <RichTextReadOnlyEditor
+ initialValue={
+ !issueDetails.description_html ||
+ issueDetails.description_html === "" ||
+ (typeof issueDetails.description_html === "object" && Object.keys(issueDetails.description_html).length === 0)
+ ? "<p></p>"
+ : issueDetails.description_html
+ }
+ />
+ )}
+ <IssueReactions />
+ </div>
+);
diff --git a/space/components/issues/peek-overview/layout.tsx b/space/components/issues/peek-overview/layout.tsx
index b76da13f43..6662288cea 100644
--- a/space/components/issues/peek-overview/layout.tsx
+++ b/space/components/issues/peek-overview/layout.tsx
@@ -117,7 +117,11 @@ export const IssuePeekOverview: React.FC = observer(() => {
<SidePeekView handleClose={handleClose} issueDetails={issueDetails} />
)}
{issueDetailStore.peekMode === "full" && (
- <FullScreenPeekView handleClose={handleClose} issueDetails={issueDetails} />
+ <FullScreenPeekView
+ workspace_slug={workspace_slug}
+ handleClose={handleClose}
+ issueDetails={issueDetails}
+ />
)}
</div>
</Dialog.Panel>
diff --git a/space/constants/editor.ts b/space/constants/editor.ts
new file mode 100644
index 0000000000..bdd07f0c52
--- /dev/null
+++ b/space/constants/editor.ts
@@ -0,0 +1,98 @@
+import {
+ Bold,
+ Code2,
+ Heading1,
+ Heading2,
+ Heading3,
+ Image,
+ Italic,
+ List,
+ ListOrdered,
+ ListTodo,
+ LucideIcon,
+ Quote,
+ Strikethrough,
+ Table,
+ Underline,
+} from "lucide-react";
+// editor
+import { EditorMenuItemNames } from "@plane/lite-text-editor";
+
+type TEditorTypes = "lite" | "document";
+
+export type ToolbarMenuItem = {
+ key: EditorMenuItemNames;
+ name: string;
+ icon: LucideIcon;
+ shortcut?: string[];
+ editors: TEditorTypes[];
+};
+
+export const BASIC_MARK_ITEMS: ToolbarMenuItem[] = [
+ { key: "H1", name: "Heading 1", icon: Heading1, editors: ["document"] },
+ { key: "H2", name: "Heading 2", icon: Heading2, editors: ["document"] },
+ { key: "H3", name: "Heading 3", icon: Heading3, editors: ["document"] },
+ { key: "bold", name: "Bold", icon: Bold, shortcut: ["Cmd", "B"], editors: ["lite", "document"] },
+ { key: "italic", name: "Italic", icon: Italic, shortcut: ["Cmd", "I"], editors: ["lite", "document"] },
+ { key: "underline", name: "Underline", icon: Underline, shortcut: ["Cmd", "U"], editors: ["lite", "document"] },
+ {
+ key: "strike",
+ name: "Strikethrough",
+ icon: Strikethrough,
+ shortcut: ["Cmd", "Shift", "S"],
+ editors: ["lite", "document"],
+ },
+];
+
+export const LIST_ITEMS: ToolbarMenuItem[] = [
+ {
+ key: "bullet-list",
+ name: "Bulleted list",
+ icon: List,
+ shortcut: ["Cmd", "Shift", "7"],
+ editors: ["lite", "document"],
+ },
+ {
+ key: "ordered-list",
+ name: "Numbered list",
+ icon: ListOrdered,
+ shortcut: ["Cmd", "Shift", "8"],
+ editors: ["lite", "document"],
+ },
+ {
+ key: "To-do List",
+ name: "To-do list",
+ icon: ListTodo,
+ shortcut: ["Cmd", "Shift", "9"],
+ editors: ["lite", "document"],
+ },
+];
+
+export const USER_ACTION_ITEMS: ToolbarMenuItem[] = [
+ { key: "quote", name: "Quote", icon: Quote, editors: ["lite", "document"] },
+ { key: "code", name: "Code", icon: Code2, editors: ["lite", "document"] },
+];
+
+export const COMPLEX_ITEMS: ToolbarMenuItem[] = [
+ { key: "table", name: "Table", icon: Table, editors: ["document"] },
+ { key: "image", name: "Image", icon: Image, editors: ["lite", "document"] },
+];
+
+export const TOOLBAR_ITEMS: {
+ [editorType in TEditorTypes]: {
+ [key: string]: ToolbarMenuItem[];
+ };
+} = {
+ lite: {
+ basic: BASIC_MARK_ITEMS.filter((item) => item.editors.includes("lite")),
+ list: LIST_ITEMS.filter((item) => item.editors.includes("lite")),
+ userAction: USER_ACTION_ITEMS.filter((item) => item.editors.includes("lite")),
+ complex: COMPLEX_ITEMS.filter((item) => item.editors.includes("lite")),
+ },
+ document: {
+ basic: BASIC_MARK_ITEMS.filter((item) => item.editors.includes("document")),
+ list: LIST_ITEMS.filter((item) => item.editors.includes("document")),
+ userAction: USER_ACTION_ITEMS.filter((item) => item.editors.includes("document")),
+ complex: COMPLEX_ITEMS.filter((item) => item.editors.includes("document")),
+ },
+};
diff --git a/space/helpers/string.helper.ts b/space/helpers/string.helper.ts
index 4a265ba4ea..b44974d250 100644
--- a/space/helpers/string.helper.ts
+++ b/space/helpers/string.helper.ts
@@ -1,3 +1,5 @@
+import DOMPurify from "dompurify";
+
export const addSpaceIfCamelCase = (str: string) => str.replace(/([a-z])([A-Z])/g, "$1 $2");
const fallbackCopyTextToClipboard = (text: string) => {
@@ -47,3 +49,10 @@ export const checkEmailValidity = (email: string): boolean => {
return isEmailValid;
};
+
+export const isEmptyHtmlString = (htmlString: string) => {
+ // Remove HTML tags using regex
+ const cleanText = DOMPurify.sanitize(htmlString, { ALLOWED_TAGS: [] });
+ // Trim the string and check if it's empty
+ return cleanText.trim() === "";
+};
diff --git a/space/hooks/use-mention.tsx b/space/hooks/use-mention.tsx
new file mode 100644
index 0000000000..9f540cf58d
--- /dev/null
+++ b/space/hooks/use-mention.tsx
@@ -0,0 +1,43 @@
+import { useRef, useEffect } from "react";
+import { UserService } from "services/user.service";
+import useSWR from "swr";
+import { IUser } from "@plane/types";
+
+export const useMention = () => {
+ const userService = new UserService();
+ const { data: user, isLoading: userDataLoading } = useSWR("currentUser", async () => userService.currentUser());
+
+ const userRef = useRef<IUser | undefined>();
+
+ useEffect(() => {
+ if (userRef) {
+ // @ts-expect-error mismatch in types
+ userRef.current = user;
+ }
+ }, [user]);
+
+ const waitForUserDate = async () =>
+ new Promise<IUser>((resolve) => {
+ const checkData = () => {
+ if (userRef.current) {
+ resolve(userRef.current);
+ } else {
+ setTimeout(checkData, 100);
+ }
+ };
+ checkData();
+ });
+
+ const mentionHighlights = async () => {
+ if (!userDataLoading && userRef.current) {
+ return [userRef.current.id];
+ } else {
+ const user = await waitForUserDate();
+ return [user.id];
+ }
+ };
+
+ return {
+ mentionHighlights,
+ };
+};
diff --git a/space/package.json b/space/package.json
index 6e736f9b07..ca811a645d 100644
--- a/space/package.json
+++ b/space/package.json
@@ -25,6 +25,7 @@
"@sentry/nextjs": "^7.108.0",
"axios": "^1.3.4",
"clsx": "^2.0.0",
+ "dompurify": "^3.0.11",
"dotenv": "^16.3.1",
"js-cookie": "^3.0.1",
"lowlight": "^2.9.0",
@@ -43,6 +44,7 @@
"uuid": "^9.0.0"
},
"devDependencies": {
+ "@types/dompurify": "^3.0.5",
"@types/js-cookie": "^3.0.3",
"@types/node": "18.14.1",
"@types/nprogress": "^0.2.0",
diff --git a/space/services/project-member.service.ts b/space/services/project-member.service.ts
new file mode 100644
index 0000000000..c1c2c27325
--- /dev/null
+++ b/space/services/project-member.service.ts
@@ -0,0 +1,27 @@
+// types
+import type { IProjectMember, IProjectMembership } from "@plane/types";
+import { API_BASE_URL } from "@/helpers/common.helper";
+// services
+import APIService from "@/services/api.service";
+
+export class ProjectMemberService extends APIService {
+ constructor() {
+ super(API_BASE_URL);
+ }
+
+ async fetchProjectMembers(workspaceSlug: string, projectId: string): Promise<IProjectMembership[]> {
+ return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/members/`)
+ .then((response) => response?.data)
+ .catch((error) => {
+ throw error?.response?.data;
+ });
+ }
+
+ async getProjectMember(workspaceSlug: string, projectId: string, memberId: string): Promise<IProjectMember> {
+ return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/members/${memberId}/`)
+ .then((response) => response?.data)
+ .catch((error) => {
+ throw error?.response?.data;
+ });
+ }
+}
diff --git a/space/styles/globals.css b/space/styles/globals.css
index 92980b0d7d..2220225fb3 100644
--- a/space/styles/globals.css
+++ b/space/styles/globals.css
@@ -33,8 +33,8 @@
--color-primary-900: 13, 24, 51;
--color-background-100: 255, 255, 255; /* primary bg */
- --color-background-90: 250, 250, 250; /* secondary bg */
- --color-background-80: 245, 245, 245; /* tertiary bg */
+ --color-background-90: 247, 247, 247; /* secondary bg */
+ --color-background-80: 232, 232, 232; /* tertiary bg */
--color-text-100: 23, 23, 23; /* primary text */
--color-text-200: 58, 58, 58; /* secondary text */
@@ -97,8 +97,8 @@
color-scheme: light !important;
--color-background-100: 255, 255, 255; /* primary bg */
- --color-background-90: 250, 250, 250; /* secondary bg */
- --color-background-80: 245, 245, 245; /* tertiary bg */
+ --color-background-90: 247, 247, 247; /* secondary bg */
+ --color-background-80: 232, 232, 232; /* tertiary bg */
/* onboarding colors */
--gradient-onboarding-100: linear-gradient(106deg, #f2f6ff 29.8%, #e1eaff 99.34%);
@@ -151,9 +151,9 @@
[data-theme="dark-contrast"] {
color-scheme: dark !important;
- --color-background-100: 7, 7, 7; /* primary bg */
- --color-background-90: 11, 11, 11; /* secondary bg */
- --color-background-80: 23, 23, 23; /* tertiary bg */
+ --color-background-100: 25, 25, 25; /* primary bg */
+ --color-background-90: 32, 32, 32; /* secondary bg */
+ --color-background-80: 44, 44, 44; /* tertiary bg */
--color-shadow-2xs: 0px 0px 1px 0px rgba(0, 0, 0, 0.15), 0px 1px 3px 0px rgba(0, 0, 0, 0.5);
--color-shadow-xs: 0px 0px 2px 0px rgba(0, 0, 0, 0.2), 0px 2px 4px 0px rgba(0, 0, 0, 0.5);
diff --git a/web/components/command-palette/command-palette.tsx b/web/components/command-palette/command-palette.tsx
index 490d392e2c..00de628b7d 100644
--- a/web/components/command-palette/command-palette.tsx
+++ b/web/components/command-palette/command-palette.tsx
@@ -12,7 +12,7 @@ import { BulkDeleteIssuesModal } from "@/components/core";
import { CycleCreateUpdateModal } from "@/components/cycles";
import { CreateUpdateIssueModal, DeleteIssueModal } from "@/components/issues";
import { CreateUpdateModuleModal } from "@/components/modules";
-import { CreateUpdatePageModal } from "@/components/pages";
+import { CreatePageModal } from "@/components/pages";
import { CreateProjectModal } from "@/components/project";
import { CreateUpdateProjectViewModal } from "@/components/views";
// helpers
@@ -294,10 +294,12 @@ export const CommandPalette: FC = observer(() => {
workspaceSlug={workspaceSlug.toString()}
projectId={projectId.toString()}
/>
- <CreateUpdatePageModal
- isOpen={isCreatePageModalOpen}
- handleClose={() => toggleCreatePageModal(false)}
+ <CreatePageModal
+ workspaceSlug={workspaceSlug.toString()}
projectId={projectId.toString()}
+ isModalOpen={isCreatePageModalOpen}
+ handleModalClose={() => toggleCreatePageModal(false)}
+ redirectionEnabled
/>
</>
)}
diff --git a/web/components/core/modals/gpt-assistant-popover.tsx b/web/components/core/modals/gpt-assistant-popover.tsx
index 3348272d69..a67b13f7ef 100644
--- a/web/components/core/modals/gpt-assistant-popover.tsx
+++ b/web/components/core/modals/gpt-assistant-popover.tsx
@@ -6,8 +6,8 @@ import { usePopper } from "react-popper";
// ui
import { AlertCircle } from "lucide-react";
import { Popover, Transition } from "@headlessui/react";
-import { RichReadOnlyEditorWithRef } from "@plane/rich-text-editor";
import { Button, Input, TOAST_TYPE, setToast } from "@plane/ui";
+import { RichTextReadOnlyEditor } from "@/components/editor/rich-text-editor/rich-text-read-only-editor";
// icons
// components
// hooks
@@ -173,8 +173,8 @@ export const GptAssistantPopover: React.FC<Props> = (props) => {
const generateResponseButtonText = isSubmitting
? "Generating response..."
: response === ""
- ? "Generate response"
- : "Generate again";
+ ? "Generate response"
+ : "Generate again";
return (
<Popover as="div" className={`relative w-min text-left`}>
@@ -202,23 +202,15 @@ export const GptAssistantPopover: React.FC<Props> = (props) => {
{prompt && (
<div className="text-sm">
Content:
- <RichReadOnlyEditorWithRef
- value={prompt}
- customClassName="-m-3"
- noBorder
- borderOnFocus={false}
- ref={editorRef}
- />
+ <RichTextReadOnlyEditor initialValue={prompt} containerClassName="-m-3" ref={editorRef} />
</div>
)}
{response !== "" && (
<div className="page-block-section max-h-[8rem] text-sm">
Response:
- <RichReadOnlyEditorWithRef
- value={`<p>${response}</p>`}
- customClassName={response ? "-mx-3 -my-3" : ""}
- noBorder
- borderOnFocus={false}
+ <RichTextReadOnlyEditor
+ initialValue={`<p>${response}</p>`}
+ containerClassName={response ? "-mx-3 -my-3" : ""}
ref={responseRef}
/>
</div>
@@ -245,6 +237,7 @@ export const GptAssistantPopover: React.FC<Props> = (props) => {
prompt && prompt !== "" ? "Tell AI what action to perform on this content..." : "Ask AI anything..."
}`}
className="w-full"
+ autoFocus
/>
)}
/>
@@ -253,7 +246,7 @@ export const GptAssistantPopover: React.FC<Props> = (props) => {
<>{responseActionButton}</>
) : (
<>
- <div className="flex items-center justify-center gap-2 text-sm text-custom-primary">
+ <div className="flex items-start justify-center gap-2 text-sm text-custom-primary">
<AlertCircle className="h-4 w-4" />
<p>By using this feature, you consent to sharing the message with a 3rd party service. </p>
</div>
diff --git a/web/components/editor/index.ts b/web/components/editor/index.ts
new file mode 100644
index 0000000000..72e92a6a8a
--- /dev/null
+++ b/web/components/editor/index.ts
@@ -0,0 +1,2 @@
+export * from "./lite-text-editor";
+export * from "./rich-text-editor";
diff --git a/web/components/editor/lite-text-editor/index.ts b/web/components/editor/lite-text-editor/index.ts
new file mode 100644
index 0000000000..661c8e7554
--- /dev/null
+++ b/web/components/editor/lite-text-editor/index.ts
@@ -0,0 +1,3 @@
+export * from "./lite-text-editor";
+export * from "./lite-text-read-only-editor";
+export * from "./toolbar";
diff --git a/web/components/editor/lite-text-editor/lite-text-editor.tsx b/web/components/editor/lite-text-editor/lite-text-editor.tsx
new file mode 100644
index 0000000000..1be78a54e2
--- /dev/null
+++ b/web/components/editor/lite-text-editor/lite-text-editor.tsx
@@ -0,0 +1,107 @@
+import React from "react";
+// editor
+import { EditorRefApi, ILiteTextEditor, LiteTextEditorWithRef } from "@plane/lite-text-editor";
+// types
+import { IUserLite } from "@plane/types";
+// components
+import { IssueCommentToolbar } from "@/components/editor";
+// constants
+import { EIssueCommentAccessSpecifier } from "@/constants/issue";
+// helpers
+import { cn } from "@/helpers/common.helper";
+import { isEmptyHtmlString } from "@/helpers/string.helper";
+// hooks
+import { useMember, useMention, useUser } from "@/hooks/store";
+// services
+import { FileService } from "@/services/file.service";
+
+interface LiteTextEditorWrapperProps extends Omit<ILiteTextEditor, "fileHandler" | "mentionHandler"> {
+ workspaceSlug: string;
+ workspaceId: string;
+ projectId: string;
+ accessSpecifier?: EIssueCommentAccessSpecifier;
+ handleAccessChange?: (accessKey: EIssueCommentAccessSpecifier) => void;
+ showAccessSpecifier?: boolean;
+ showSubmitButton?: boolean;
+ isSubmitting?: boolean;
+}
+
+const fileService = new FileService();
+
+export const LiteTextEditor = React.forwardRef<EditorRefApi, LiteTextEditorWrapperProps>((props, ref) => {
+ const {
+ containerClassName,
+ workspaceSlug,
+ workspaceId,
+ projectId,
+ accessSpecifier,
+ handleAccessChange,
+ showAccessSpecifier = false,
+ showSubmitButton = true,
+ isSubmitting = false,
+ ...rest
+ } = props;
+ // store hooks
+ const { currentUser } = useUser();
+ const {
+ getUserDetails,
+ project: { getProjectMemberIds },
+ } = useMember();
+ // derived values
+ const projectMemberIds = getProjectMemberIds(projectId);
+ const projectMemberDetails = projectMemberIds?.map((id) => getUserDetails(id) as IUserLite);
+ // use-mention
+ const { mentionHighlights, mentionSuggestions } = useMention({
+ workspaceSlug,
+ projectId,
+ members: projectMemberDetails,
+ user: currentUser ?? undefined,
+ });
+
+ const isEmpty =
+ props.initialValue === "" ||
+ props.initialValue?.trim() === "" ||
+ props.initialValue === "<p></p>" ||
+ isEmptyHtmlString(props.initialValue ?? "");
+
+ function isMutableRefObject<T>(ref: React.ForwardedRef<T>): ref is React.MutableRefObject<T | null> {
+ return !!ref && typeof ref === "object" && "current" in ref;
+ }
+
+ return (
+ <div className="border border-custom-border-200 rounded p-3 space-y-3">
+ <LiteTextEditorWithRef
+ ref={ref}
+ fileHandler={{
+ upload: fileService.getUploadFileFunction(workspaceSlug),
+ delete: fileService.getDeleteImageFunction(workspaceId),
+ restore: fileService.getRestoreImageFunction(workspaceId),
+ cancel: fileService.cancelUpload,
+ }}
+ mentionHandler={{
+ highlights: mentionHighlights,
+ suggestions: mentionSuggestions,
+ }}
+ {...rest}
+ containerClassName={cn(containerClassName, "relative")}
+ />
+ <IssueCommentToolbar
+ accessSpecifier={accessSpecifier}
+ executeCommand={(key) => {
+ if (isMutableRefObject<EditorRefApi>(ref)) {
+ ref.current?.executeMenuItemCommand(key);
+ }
+ }}
+ handleAccessChange={handleAccessChange}
+ handleSubmit={(e) => rest.onEnterKeyPress?.(e)}
+ isCommentEmpty={isEmpty}
+ isSubmitting={isSubmitting}
+ showAccessSpecifier={showAccessSpecifier}
+ editorRef={isMutableRefObject<EditorRefApi>(ref) ? ref : null}
+ showSubmitButton={showSubmitButton}
+ />
+ </div>
+ );
+});
+
+LiteTextEditor.displayName = "LiteTextEditor";
diff --git a/web/components/editor/lite-text-editor/lite-text-read-only-editor.tsx b/web/components/editor/lite-text-editor/lite-text-read-only-editor.tsx
new file mode 100644
index 0000000000..8ee95b5854
--- /dev/null
+++ b/web/components/editor/lite-text-editor/lite-text-read-only-editor.tsx
@@ -0,0 +1,29 @@
+import React from "react";
+// editor
+import { EditorReadOnlyRefApi, ILiteTextReadOnlyEditor, LiteTextReadOnlyEditorWithRef } from "@plane/lite-text-editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// hooks
+import { useMention } from "@/hooks/store";
+
+interface LiteTextReadOnlyEditorWrapperProps extends Omit<ILiteTextReadOnlyEditor, "mentionHandler"> {}
+
+export const LiteTextReadOnlyEditor = React.forwardRef<EditorReadOnlyRefApi, LiteTextReadOnlyEditorWrapperProps>(
+ ({ ...props }, ref) => {
+ const { mentionHighlights } = useMention({});
+
+ return (
+ <LiteTextReadOnlyEditorWithRef
+ ref={ref}
+ mentionHandler={{
+ highlights: mentionHighlights,
+ }}
+ {...props}
+ // overriding the containerClassName to add relative class passed
+ containerClassName={cn(props.containerClassName, "relative p-2")}
+ />
+ );
+ }
+);
+
+LiteTextReadOnlyEditor.displayName = "LiteTextReadOnlyEditor";
diff --git a/web/components/editor/lite-text-editor/toolbar.tsx b/web/components/editor/lite-text-editor/toolbar.tsx
new file mode 100644
index 0000000000..d80db9ccd7
--- /dev/null
+++ b/web/components/editor/lite-text-editor/toolbar.tsx
@@ -0,0 +1,172 @@
+import React, { useEffect, useState, useCallback } from "react";
+import { Globe2, Lock, LucideIcon } from "lucide-react";
+// editor
+import { EditorMenuItemNames } from "@plane/document-editor";
+import { EditorRefApi } from "@plane/lite-text-editor";
+// ui
+import { Button, Tooltip } from "@plane/ui";
+// constants
+import { TOOLBAR_ITEMS } from "@/constants/editor";
+import { EIssueCommentAccessSpecifier } from "@/constants/issue";
+// helpers
+import { cn } from "@/helpers/common.helper";
+
+type Props = {
+ accessSpecifier?: EIssueCommentAccessSpecifier;
+ executeCommand: (commandName: EditorMenuItemNames) => void;
+ handleAccessChange?: (accessKey: EIssueCommentAccessSpecifier) => void;
+ handleSubmit: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
+ isCommentEmpty: boolean;
+ isSubmitting: boolean;
+ showAccessSpecifier: boolean;
+ showSubmitButton: boolean;
+ editorRef: React.MutableRefObject<EditorRefApi | null> | null;
+};
+
+type TCommentAccessType = {
+ icon: LucideIcon;
+ key: EIssueCommentAccessSpecifier;
+ label: "Private" | "Public";
+};
+
+const COMMENT_ACCESS_SPECIFIERS: TCommentAccessType[] = [
+ {
+ icon: Lock,
+ key: EIssueCommentAccessSpecifier.INTERNAL,
+ label: "Private",
+ },
+ {
+ icon: Globe2,
+ key: EIssueCommentAccessSpecifier.EXTERNAL,
+ label: "Public",
+ },
+];
+
+const toolbarItems = TOOLBAR_ITEMS.lite;
+
+export const IssueCommentToolbar: React.FC<Props> = (props) => {
+ const {
+ accessSpecifier,
+ executeCommand,
+ handleAccessChange,
+ handleSubmit,
+ isCommentEmpty,
+ isSubmitting,
+ showAccessSpecifier,
+ showSubmitButton,
+ editorRef,
+ } = props;
+
+ // State to manage active states of toolbar items
+ const [activeStates, setActiveStates] = useState<Record<string, boolean>>({});
+
+ // Function to update active states
+ const updateActiveStates = useCallback(() => {
+ if (editorRef?.current) {
+ const newActiveStates: Record<string, boolean> = {};
+ Object.values(toolbarItems)
+ .flat()
+ .forEach((item) => {
+ // Assert that editorRef.current is not null
+ newActiveStates[item.key] = (editorRef.current as EditorRefApi).isMenuItemActive(item.key);
+ });
+ setActiveStates(newActiveStates);
+ }
+ }, [editorRef]);
+
+ // useEffect to call updateActiveStates when isActive prop changes
+ useEffect(() => {
+ if (!editorRef?.current) return;
+ const unsubscribe = editorRef.current.onStateChange(updateActiveStates);
+ updateActiveStates();
+ return () => unsubscribe();
+ }, [editorRef, updateActiveStates]);
+
+ return (
+ <div className="flex h-9 w-full items-stretch gap-1.5 bg-custom-background-90 overflow-x-scroll">
+ {showAccessSpecifier && (
+ <div className="flex flex-shrink-0 items-stretch gap-0.5 rounded border-[0.5px] border-custom-border-200 p-1">
+ {COMMENT_ACCESS_SPECIFIERS.map((access) => {
+ const isAccessActive = accessSpecifier === access.key;
+
+ return (
+ <Tooltip key={access.key} tooltipContent={access.label}>
+ <button
+ type="button"
+ onClick={() => handleAccessChange?.(access.key)}
+ className={cn("grid place-items-center aspect-square rounded-sm p-1 hover:bg-custom-background-80", {
+ "bg-custom-background-80": isAccessActive,
+ })}
+ >
+ <access.icon
+ className={cn("h-3.5 w-3.5 text-custom-text-400", {
+ "text-custom-text-100": isAccessActive,
+ })}
+ strokeWidth={2}
+ />
+ </button>
+ </Tooltip>
+ );
+ })}
+ </div>
+ )}
+ <div className="flex w-full items-stretch justify-between gap-2 rounded border-[0.5px] border-custom-border-200 p-1">
+ <div className="flex items-stretch">
+ {Object.keys(toolbarItems).map((key, index) => (
+ <div
+ key={key}
+ className={cn("flex items-stretch gap-0.5 border-r border-custom-border-200 px-2.5", {
+ "pl-0": index === 0,
+ "pr-0": index === Object.keys(toolbarItems).length - 1,
+ })}
+ >
+ {toolbarItems[key].map((item) => (
+ <Tooltip
+ key={item.key}
+ tooltipContent={
+ <p className="flex flex-col gap-1 text-center text-xs">
+ <span className="font-medium">{item.name}</span>
+ {item.shortcut && <kbd className="text-custom-text-400">{item.shortcut.join(" + ")}</kbd>}
+ </p>
+ }
+ >
+ <button
+ type="button"
+ onClick={() => executeCommand(item.key)}
+ className={cn(
+ "grid place-items-center aspect-square rounded-sm p-0.5 text-custom-text-400 hover:bg-custom-background-80",
+ {
+ "bg-custom-background-80 text-custom-text-100": activeStates[item.key],
+ }
+ )}
+ >
+ <item.icon
+ className={cn("h-3.5 w-3.5", {
+ "text-custom-text-100": activeStates[item.key],
+ })}
+ strokeWidth={2.5}
+ />
+ </button>
+ </Tooltip>
+ ))}
+ </div>
+ ))}
+ </div>
+ {showSubmitButton && (
+ <div className="sticky right-1">
+ <Button
+ type="submit"
+ variant="primary"
+ className="px-2.5 py-1.5 text-xs"
+ onClick={handleSubmit}
+ disabled={isCommentEmpty}
+ loading={isSubmitting}
+ >
+ Comment
+ </Button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/web/components/editor/rich-text-editor/index.ts b/web/components/editor/rich-text-editor/index.ts
new file mode 100644
index 0000000000..f185d0054e
--- /dev/null
+++ b/web/components/editor/rich-text-editor/index.ts
@@ -0,0 +1,2 @@
+export * from "./rich-text-editor";
+export * from "./rich-text-read-only-editor";
diff --git a/web/components/editor/rich-text-editor/rich-text-editor.tsx b/web/components/editor/rich-text-editor/rich-text-editor.tsx
new file mode 100644
index 0000000000..e2173445d4
--- /dev/null
+++ b/web/components/editor/rich-text-editor/rich-text-editor.tsx
@@ -0,0 +1,59 @@
+import React, { forwardRef } from "react";
+// editor
+import { EditorRefApi, IRichTextEditor, RichTextEditorWithRef } from "@plane/rich-text-editor";
+// types
+import { IUserLite } from "@plane/types";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// hooks
+import { useMember, useMention, useUser } from "@/hooks/store";
+// services
+import { FileService } from "@/services/file.service";
+
+interface RichTextEditorWrapperProps extends Omit<IRichTextEditor, "fileHandler" | "mentionHandler"> {
+ workspaceSlug: string;
+ workspaceId: string;
+ projectId: string;
+}
+
+const fileService = new FileService();
+
+export const RichTextEditor = forwardRef<EditorRefApi, RichTextEditorWrapperProps>((props, ref) => {
+ const { containerClassName, workspaceSlug, workspaceId, projectId, ...rest } = props;
+ // store hooks
+ const { currentUser } = useUser();
+ const {
+ getUserDetails,
+ project: { getProjectMemberIds },
+ } = useMember();
+ // derived values
+ const projectMemberIds = getProjectMemberIds(projectId);
+ const projectMemberDetails = projectMemberIds?.map((id) => getUserDetails(id) as IUserLite);
+ // use-mention
+ const { mentionHighlights, mentionSuggestions } = useMention({
+ workspaceSlug,
+ projectId,
+ members: projectMemberDetails,
+ user: currentUser ?? undefined,
+ });
+
+ return (
+ <RichTextEditorWithRef
+ ref={ref}
+ fileHandler={{
+ upload: fileService.getUploadFileFunction(workspaceSlug),
+ delete: fileService.getDeleteImageFunction(workspaceId),
+ restore: fileService.getRestoreImageFunction(workspaceId),
+ cancel: fileService.cancelUpload,
+ }}
+ mentionHandler={{
+ highlights: mentionHighlights,
+ suggestions: mentionSuggestions,
+ }}
+ {...rest}
+ containerClassName={cn(containerClassName, "relative min-h-[150px] border border-custom-border-200 p-3")}
+ />
+ );
+});
+
+RichTextEditor.displayName = "RichTextEditor";
diff --git a/web/components/editor/rich-text-editor/rich-text-read-only-editor.tsx b/web/components/editor/rich-text-editor/rich-text-read-only-editor.tsx
new file mode 100644
index 0000000000..1415bc098a
--- /dev/null
+++ b/web/components/editor/rich-text-editor/rich-text-read-only-editor.tsx
@@ -0,0 +1,29 @@
+import React from "react";
+// editor
+import { EditorReadOnlyRefApi, IRichTextReadOnlyEditor, RichTextReadOnlyEditorWithRef } from "@plane/rich-text-editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// hooks
+import { useMention } from "@/hooks/store";
+
+interface RichTextReadOnlyEditorWrapperProps extends Omit<IRichTextReadOnlyEditor, "mentionHandler"> {}
+
+export const RichTextReadOnlyEditor = React.forwardRef<EditorReadOnlyRefApi, RichTextReadOnlyEditorWrapperProps>(
+ ({ ...props }, ref) => {
+ const { mentionHighlights } = useMention({});
+
+ return (
+ <RichTextReadOnlyEditorWithRef
+ ref={ref}
+ mentionHandler={{
+ highlights: mentionHighlights,
+ }}
+ {...props}
+ // overriding the containerClassName to add relative class passed
+ containerClassName={cn(props.containerClassName, "relative border border-custom-border-200 p-3")}
+ />
+ );
+ }
+);
+
+RichTextReadOnlyEditor.displayName = "RichTextReadOnlyEditor";
diff --git a/web/components/headers/index.ts b/web/components/headers/index.ts
index b57b91534c..b50074c8e7 100644
--- a/web/components/headers/index.ts
+++ b/web/components/headers/index.ts
@@ -14,6 +14,7 @@ export * from "./cycles";
export * from "./modules-list";
export * from "./project-settings";
export * from "./workspace-settings";
+export * from "./page-details";
export * from "./pages";
export * from "./project-draft-issues";
export * from "./project-archived-issue-details";
diff --git a/web/components/headers/page-details.tsx b/web/components/headers/page-details.tsx
index 4130dffcef..9a595bf1ce 100644
--- a/web/components/headers/page-details.tsx
+++ b/web/components/headers/page-details.tsx
@@ -24,7 +24,7 @@ export const PageDetailsHeader: FC<IPagesHeaderProps> = observer((props) => {
const { commandPalette: commandPaletteStore } = useApplication();
const { currentProjectDetails } = useProject();
- const pageDetails = usePage(pageId as string);
+ const { name } = usePage(pageId?.toString() ?? "");
return (
<div className="relative z-10 flex h-[3.75rem] w-full flex-shrink-0 flex-row items-center justify-between gap-x-2 gap-y-4 bg-custom-sidebar-background-100 p-4">
@@ -71,10 +71,7 @@ export const PageDetailsHeader: FC<IPagesHeaderProps> = observer((props) => {
<Breadcrumbs.BreadcrumbItem
type="text"
link={
- <BreadcrumbLink
- label={pageDetails?.name ?? "Page"}
- icon={<FileText className="h-4 w-4 text-custom-text-300" />}
- />
+ <BreadcrumbLink label={name ?? "Page"} icon={<FileText className="h-4 w-4 text-custom-text-300" />} />
}
/>
</Breadcrumbs>
diff --git a/web/components/inbox/content/issue-root.tsx b/web/components/inbox/content/issue-root.tsx
index 7edcc26446..627c86c455 100644
--- a/web/components/inbox/content/issue-root.tsx
+++ b/web/components/inbox/content/issue-root.tsx
@@ -25,11 +25,13 @@ type Props = {
isEditable: boolean;
isSubmitting: "submitting" | "submitted" | "saved";
setIsSubmitting: Dispatch<SetStateAction<"submitting" | "submitted" | "saved">>;
+ swrIssueDescription: string | undefined;
};
export const InboxIssueMainContent: React.FC<Props> = observer((props) => {
const router = useRouter();
- const { workspaceSlug, projectId, inboxIssue, isEditable, isSubmitting, setIsSubmitting } = props;
+ const { workspaceSlug, projectId, inboxIssue, isEditable, isSubmitting, setIsSubmitting, swrIssueDescription } =
+ props;
// hooks
const { currentUser } = useUser();
const { setShowAlert } = useReloadConfirmations(isSubmitting === "submitting");
@@ -49,13 +51,6 @@ export const InboxIssueMainContent: React.FC<Props> = observer((props) => {
const issue = inboxIssue.issue;
if (!issue) return <></>;
- const issueDescription =
- issue.description_html !== undefined || issue.description_html !== null
- ? issue.description_html != ""
- ? issue.description_html
- : "<p></p>"
- : undefined;
-
const issueOperations: TIssueOperations = useMemo(
() => ({
// eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -116,6 +111,7 @@ export const InboxIssueMainContent: React.FC<Props> = observer((props) => {
);
if (!issue?.project_id || !issue?.id) return <></>;
+
return (
<>
<div className="rounded-lg space-y-4">
@@ -134,8 +130,8 @@ export const InboxIssueMainContent: React.FC<Props> = observer((props) => {
workspaceSlug={workspaceSlug}
projectId={issue.project_id}
issueId={issue.id}
- value={issueDescription}
- initialValue={issueDescription}
+ swrIssueDescription={swrIssueDescription}
+ initialValue={issue.description_html ?? "<p></p>"}
disabled={!isEditable}
issueOperations={issueOperations}
setIsSubmitting={(value) => setIsSubmitting(value)}
diff --git a/web/components/inbox/content/root.tsx b/web/components/inbox/content/root.tsx
index 9b5f94a48d..9af3da0bc6 100644
--- a/web/components/inbox/content/root.tsx
+++ b/web/components/inbox/content/root.tsx
@@ -22,14 +22,14 @@ export const InboxContentRoot: FC<TInboxContentRoot> = observer((props) => {
membership: { currentProjectRole },
} = useUser();
- useSWR(
+ const { data: swrIssueDetails } = useSWR(
workspaceSlug && projectId && inboxIssueId
? `PROJECT_INBOX_ISSUE_DETAIL_${workspaceSlug}_${projectId}_${inboxIssueId}`
: null,
- () => {
- workspaceSlug && projectId && inboxIssueId && fetchInboxIssueById(workspaceSlug, projectId, inboxIssueId);
- },
- { revalidateOnFocus: false }
+ workspaceSlug && projectId && inboxIssueId
+ ? () => fetchInboxIssueById(workspaceSlug, projectId, inboxIssueId)
+ : null,
+ { revalidateOnFocus: true }
);
const isEditable = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER;
@@ -57,6 +57,7 @@ export const InboxContentRoot: FC<TInboxContentRoot> = observer((props) => {
isEditable={isEditable && !isIssueDisabled}
isSubmitting={isSubmitting}
setIsSubmitting={setIsSubmitting}
+ swrIssueDescription={swrIssueDetails?.issue.description_html}
/>
</div>
</div>
diff --git a/web/components/inbox/modals/create-issue-modal.tsx b/web/components/inbox/modals/create-issue-modal.tsx
index 9336613c6c..3cc642be89 100644
--- a/web/components/inbox/modals/create-issue-modal.tsx
+++ b/web/components/inbox/modals/create-issue-modal.tsx
@@ -4,7 +4,7 @@ import { useRouter } from "next/router";
import { Controller, useForm } from "react-hook-form";
import { Sparkle } from "lucide-react";
import { Transition, Dialog } from "@headlessui/react";
-import { RichTextEditorWithRef } from "@plane/rich-text-editor";
+import { EditorRefApi } from "@plane/rich-text-editor";
// types
import { TIssue } from "@plane/types";
// ui
@@ -12,13 +12,15 @@ import { Button, Input, ToggleSwitch, TOAST_TYPE, setToast } from "@plane/ui";
// components
import { GptAssistantPopover } from "@/components/core";
import { PriorityDropdown } from "@/components/dropdowns";
-// constants
+import { RichTextEditor } from "@/components/editor/rich-text-editor/rich-text-editor";
import { ISSUE_CREATED } from "@/constants/event-tracker";
-// hooks
-import { useApplication, useEventTracker, useWorkspace, useMention, useProjectInbox } from "@/hooks/store";
+import { useApplication, useEventTracker, useWorkspace, useProjectInbox } from "@/hooks/store";
// services
import { AIService } from "@/services/ai.service";
-import { FileService } from "@/services/file.service";
+// components
+// ui
+// types
+// constants
type Props = {
isOpen: boolean;
@@ -33,7 +35,6 @@ const defaultValues: Partial<TIssue> = {
// services
const aiService = new AIService();
-const fileService = new FileService();
export const CreateInboxIssueModal: React.FC<Props> = observer((props) => {
const { isOpen, onClose } = props;
@@ -46,11 +47,11 @@ export const CreateInboxIssueModal: React.FC<Props> = observer((props) => {
const [gptAssistantModal, setGptAssistantModal] = useState(false);
const [iAmFeelingLucky, setIAmFeelingLucky] = useState(false);
// refs
- const editorRef = useRef<any>(null);
+ const editorRef = useRef<EditorRefApi>(null);
// hooks
- const { mentionHighlights, mentionSuggestions } = useMention();
const workspaceStore = useWorkspace();
- const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug as string)?.id as string;
+ const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug.toString() as string)?.id.toString() as string;
+
// store hooks
const { createInboxIssue } = useProjectInbox();
const {
@@ -264,20 +265,16 @@ export const CreateInboxIssueModal: React.FC<Props> = observer((props) => {
name="description_html"
control={control}
render={({ field: { value, onChange } }) => (
- <RichTextEditorWithRef
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
+ <RichTextEditor
+ initialValue={!value || value === "" ? "<p></p>" : value}
ref={editorRef}
- debouncedUpdatesEnabled={false}
- value={!value || value === "" ? "<p></p>" : value}
- customClassName="min-h-[150px]"
- onChange={(description, description_html: string) => {
+ workspaceSlug={workspaceSlug.toString()}
+ workspaceId={workspaceId}
+ projectId={projectId.toString()}
+ dragDropEnabled={false}
+ onChange={(_description: object, description_html: string) => {
onChange(description_html);
}}
- mentionSuggestions={mentionSuggestions}
- mentionHighlights={mentionHighlights}
/>
)}
/>
diff --git a/web/components/issues/description-form.tsx b/web/components/issues/description-form.tsx
deleted file mode 100644
index 5af8a418e0..0000000000
--- a/web/components/issues/description-form.tsx
+++ /dev/null
@@ -1,203 +0,0 @@
-import { ChangeEvent, FC, useCallback, useEffect, useState } from "react";
-import debounce from "lodash/debounce";
-import { observer } from "mobx-react";
-import { Controller, useForm } from "react-hook-form";
-import { RichReadOnlyEditor, RichTextEditor } from "@plane/rich-text-editor";
-import { TIssue } from "@plane/types";
-// hooks
-import { Loader, TextArea } from "@plane/ui";
-import { useMention, useWorkspace } from "@/hooks/store";
-import useReloadConfirmations from "@/hooks/use-reload-confirmation";
-// components
-// types
-import { FileService } from "@/services/file.service";
-import { TIssueOperations } from "./issue-detail";
-// services
-
-export interface IssueDescriptionFormValues {
- name: string;
- description_html: string;
-}
-
-export interface IssueDetailsProps {
- workspaceSlug: string;
- projectId: string;
- issueId: string;
- issue: {
- name: string;
- description_html: string;
- id: string;
- project_id?: string;
- };
- issueOperations: TIssueOperations;
- disabled: boolean;
- isSubmitting: "submitting" | "submitted" | "saved";
- setIsSubmitting: (value: "submitting" | "submitted" | "saved") => void;
-}
-
-const fileService = new FileService();
-
-export const IssueDescriptionForm: FC<IssueDetailsProps> = observer((props) => {
- const { workspaceSlug, projectId, issueId, issue, issueOperations, disabled, isSubmitting, setIsSubmitting } = props;
- const workspaceStore = useWorkspace();
- const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug)?.id as string;
- // states
- const [characterLimit, setCharacterLimit] = useState(false);
- // hooks
- const { setShowAlert } = useReloadConfirmations();
- // store hooks
- const { mentionHighlights, mentionSuggestions } = useMention();
- // form info
- const {
- handleSubmit,
- watch,
- reset,
- control,
- formState: { errors },
- } = useForm<TIssue>({
- defaultValues: {
- name: issue?.name,
- description_html: issue?.description_html,
- },
- });
-
- const [localTitleValue, setLocalTitleValue] = useState("");
- const [localIssueDescription, setLocalIssueDescription] = useState({
- id: issue.id,
- description_html: issue.description_html,
- });
-
- const handleDescriptionFormSubmit = useCallback(
- async (formData: Partial<TIssue>) => {
- if (!formData?.name || formData?.name.length === 0 || formData?.name.length > 255) return;
-
- await issueOperations.update(workspaceSlug, projectId, issueId, {
- name: formData.name ?? "",
- description_html: formData.description_html ?? "<p></p>",
- });
- },
- [workspaceSlug, projectId, issueId, issueOperations]
- );
-
- useEffect(() => {
- if (isSubmitting === "submitted") {
- setShowAlert(false);
- setTimeout(async () => {
- setIsSubmitting("saved");
- }, 2000);
- } else if (isSubmitting === "submitting") {
- setShowAlert(true);
- }
- }, [isSubmitting, setShowAlert, setIsSubmitting]);
-
- // reset form values
- useEffect(() => {
- if (!issue) return;
-
- reset({
- ...issue,
- });
- setLocalIssueDescription({
- id: issue.id,
- description_html: issue.description_html === "" ? "<p></p>" : issue.description_html,
- });
- setLocalTitleValue(issue.name);
- }, [issue, issue.description_html, reset]);
-
- // ADDING handleDescriptionFormSubmit TO DEPENDENCY ARRAY PRODUCES ADVERSE EFFECTS
- // TODO: Verify the exhaustive-deps warning
- // eslint-disable-next-line react-hooks/exhaustive-deps
- const debouncedFormSave = useCallback(
- debounce(async () => {
- handleSubmit(handleDescriptionFormSubmit)().finally(() => setIsSubmitting("submitted"));
- }, 1500),
- [handleSubmit]
- );
-
- return (
- <div className="relative">
- <div className="relative">
- {!disabled ? (
- <Controller
- name="name"
- control={control}
- render={({ field: { onChange } }) => (
- <TextArea
- value={localTitleValue}
- id="name"
- name="name"
- placeholder="Enter issue name"
- onFocus={() => setCharacterLimit(true)}
- onChange={(e: ChangeEvent<HTMLTextAreaElement>) => {
- setCharacterLimit(false);
- setIsSubmitting("submitting");
- setLocalTitleValue(e.target.value);
- onChange(e.target.value);
- debouncedFormSave();
- }}
- required
- className="block min-h-min w-full resize-none overflow-hidden rounded border-none bg-transparent px-3 py-2 text-2xl font-medium outline-none ring-0 focus:ring-1 focus:ring-custom-primary"
- hasError={Boolean(errors?.name)}
- role="textbox"
- />
- )}
- />
- ) : (
- <h4 className="break-words text-2xl font-semibold">{issue.name}</h4>
- )}
- {characterLimit && !disabled && (
- <div className="pointer-events-none absolute bottom-1 right-1 z-[2] rounded bg-custom-background-100 p-0.5 text-xs text-custom-text-200">
- <span className={`${watch("name").length === 0 || watch("name").length > 255 ? "text-red-500" : ""}`}>
- {watch("name").length}
- </span>
- /255
- </div>
- )}
- </div>
- <span>{errors.name ? errors.name.message : null}</span>
- <div className="relative">
- {localIssueDescription.description_html ? (
- <Controller
- name="description_html"
- control={control}
- render={({ field: { onChange } }) =>
- !disabled ? (
- <RichTextEditor
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
- value={localIssueDescription.description_html}
- rerenderOnPropsChange={localIssueDescription}
- setShouldShowAlert={setShowAlert}
- setIsSubmitting={setIsSubmitting}
- dragDropEnabled
- customClassName="min-h-[150px] shadow-sm"
- onChange={(description: any, description_html: string) => {
- setShowAlert(true);
- setIsSubmitting("submitting");
- onChange(description_html);
- debouncedFormSave();
- }}
- mentionSuggestions={mentionSuggestions}
- mentionHighlights={mentionHighlights}
- />
- ) : (
- <RichReadOnlyEditor
- value={localIssueDescription.description_html}
- customClassName="!p-0 !pt-2 text-custom-text-200"
- noBorder={disabled}
- mentionHighlights={mentionHighlights}
- />
- )
- }
- />
- ) : (
- <Loader>
- <Loader.Item height="150px" />
- </Loader>
- )}
- </div>
- </div>
- );
-});
diff --git a/web/components/issues/description-input.tsx b/web/components/issues/description-input.tsx
index 511cb9e15d..80cd9a34ad 100644
--- a/web/components/issues/description-input.tsx
+++ b/web/components/issues/description-input.tsx
@@ -1,95 +1,122 @@
-import { FC, useState, useEffect } from "react";
-// components
-import { RichReadOnlyEditor, RichTextEditor } from "@plane/rich-text-editor";
+import { FC, useCallback, useEffect, useState } from "react";
+import debounce from "lodash/debounce";
+import { observer } from "mobx-react";
+import { Controller, useForm } from "react-hook-form";
+// types
+import { TIssue } from "@plane/types";
+// ui
import { Loader } from "@plane/ui";
+// components
+import { RichTextEditor, RichTextReadOnlyEditor } from "@/components/editor";
+import { TIssueOperations } from "@/components/issues/issue-detail";
// hooks
-import { useMention, useWorkspace } from "@/hooks/store";
-import useDebounce from "@/hooks/use-debounce";
-// services
-import { FileService } from "@/services/file.service";
-const fileService = new FileService();
-// types
-import { TIssueOperations } from "./issue-detail";
+import { useWorkspace } from "@/hooks/store";
export type IssueDescriptionInputProps = {
workspaceSlug: string;
projectId: string;
issueId: string;
- value: string | undefined;
initialValue: string | undefined;
disabled?: boolean;
issueOperations: TIssueOperations;
- setIsSubmitting: (value: "submitting" | "submitted" | "saved") => void;
+ setIsSubmitting: (initialValue: "submitting" | "submitted" | "saved") => void;
+ swrIssueDescription: string | null | undefined;
};
-export const IssueDescriptionInput: FC<IssueDescriptionInputProps> = (props) => {
- const { workspaceSlug, projectId, issueId, value, initialValue, disabled, issueOperations, setIsSubmitting } = props;
- // states
- const [localIssueId, setLocalIssueId] = useState(issueId);
- const [descriptionHTML, setDescriptionHTML] = useState(value);
- // store hooks
- const { mentionHighlights, mentionSuggestions } = useMention();
+export const IssueDescriptionInput: FC<IssueDescriptionInputProps> = observer((props) => {
+ const {
+ workspaceSlug,
+ projectId,
+ issueId,
+ disabled,
+ swrIssueDescription,
+ initialValue,
+ issueOperations,
+ setIsSubmitting,
+ } = props;
+
+ const { handleSubmit, reset, control } = useForm<TIssue>({
+ defaultValues: {
+ description_html: initialValue,
+ },
+ });
+
+ const [localIssueDescription, setLocalIssueDescription] = useState({
+ id: issueId,
+ description_html: initialValue,
+ });
+
+ const handleDescriptionFormSubmit = useCallback(
+ async (formData: Partial<TIssue>) => {
+ await issueOperations.update(workspaceSlug, projectId, issueId, {
+ description_html: formData.description_html ?? "<p></p>",
+ });
+ },
+ [workspaceSlug, projectId, issueId, issueOperations]
+ );
+
const { getWorkspaceBySlug } = useWorkspace();
- // hooks
- const debouncedValue = useDebounce(descriptionHTML, 1500);
// computed values
const workspaceId = getWorkspaceBySlug(workspaceSlug)?.id as string;
+ // reset form values
useEffect(() => {
- if (issueId !== localIssueId) {
- setDescriptionHTML(undefined);
- setLocalIssueId(issueId);
- } else {
- setDescriptionHTML(value);
- }
- return () => setDescriptionHTML(undefined);
- }, [issueId, localIssueId, value]);
-
- useEffect(() => {
- if (debouncedValue && debouncedValue !== value) {
- issueOperations.update(workspaceSlug, projectId, issueId, { description_html: debouncedValue }).finally(() => {
- setIsSubmitting("submitted");
- });
- }
- // DO NOT Add more dependencies here. It will cause multiple requests to be sent.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [debouncedValue]);
-
- if (!descriptionHTML) {
- return (
- <Loader>
- <Loader.Item height="150px" />
- </Loader>
- );
- }
+ if (!issueId) return;
+ reset({
+ id: issueId,
+ description_html: initialValue === "" ? "<p></p>" : initialValue,
+ });
+ setLocalIssueDescription({
+ id: issueId,
+ description_html: initialValue === "" ? "<p></p>" : initialValue,
+ });
+ }, [initialValue, issueId, reset]);
- if (disabled) {
- return (
- <RichReadOnlyEditor
- value={descriptionHTML}
- customClassName="!p-0 !pt-2 text-custom-text-200"
- noBorder={disabled}
- mentionHighlights={mentionHighlights}
- />
- );
- }
+ // ADDING handleDescriptionFormSubmit TO DEPENDENCY ARRAY PRODUCES ADVERSE EFFECTS
+ // TODO: Verify the exhaustive-deps warning
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const debouncedFormSave = useCallback(
+ debounce(async () => {
+ handleSubmit(handleDescriptionFormSubmit)().finally(() => setIsSubmitting("submitted"));
+ }, 1500),
+ [handleSubmit, issueId]
+ );
return (
- <RichTextEditor
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
- value={descriptionHTML}
- initialValue={initialValue}
- dragDropEnabled
- customClassName="min-h-[150px] shadow-sm"
- onChange={(description: any, description_html: string) => {
- setIsSubmitting("submitting");
- setDescriptionHTML(description_html === "" ? "<p></p>" : description_html);
- }}
- mentionSuggestions={mentionSuggestions}
- mentionHighlights={mentionHighlights}
- />
+ <>
+ {localIssueDescription.description_html ? (
+ <Controller
+ name="description_html"
+ control={control}
+ render={({ field: { onChange } }) =>
+ !disabled ? (
+ <RichTextEditor
+ id={issueId}
+ initialValue={localIssueDescription.description_html ?? "<p></p>"}
+ value={swrIssueDescription ?? null}
+ workspaceSlug={workspaceSlug}
+ workspaceId={workspaceId}
+ projectId={projectId}
+ dragDropEnabled
+ onChange={(_description: object, description_html: string) => {
+ setIsSubmitting("submitting");
+ onChange(description_html);
+ debouncedFormSave();
+ }}
+ />
+ ) : (
+ <RichTextReadOnlyEditor
+ initialValue={localIssueDescription.description_html ?? ""}
+ containerClassName="!p-0 !pt-2 text-custom-text-200"
+ />
+ )
+ }
+ />
+ ) : (
+ <Loader>
+ <Loader.Item height="150px" />
+ </Loader>
+ )}
+ </>
);
-};
+});
diff --git a/web/components/issues/index.ts b/web/components/issues/index.ts
index 96136ccfe8..83431f5beb 100644
--- a/web/components/issues/index.ts
+++ b/web/components/issues/index.ts
@@ -1,7 +1,6 @@
export * from "./attachment";
export * from "./issue-modal";
export * from "./delete-issue-modal";
-export * from "./description-form";
export * from "./issue-layouts";
export * from "./description-input";
export * from "./title-input";
diff --git a/web/components/issues/issue-detail/index.ts b/web/components/issues/issue-detail/index.ts
index dc36d97ab9..c7e21ab4c9 100644
--- a/web/components/issues/issue-detail/index.ts
+++ b/web/components/issues/issue-detail/index.ts
@@ -1,14 +1,13 @@
-export * from "./root";
-export * from "./main-content";
-export * from "./sidebar";
-export * from "./parent";
+export * from "./issue-activity";
export * from "./label";
-export * from "./subscription";
export * from "./links";
-export * from "./issue-activity";
+export * from "./parent";
export * from "./reactions";
-// select components
export * from "./cycle-select";
+export * from "./main-content";
export * from "./module-select";
export * from "./parent-select";
export * from "./relation-select";
+export * from "./root";
+export * from "./sidebar";
+export * from "./subscription";
diff --git a/web/components/issues/issue-detail/issue-activity/activity-comment-root.tsx b/web/components/issues/issue-detail/issue-activity/activity-comment-root.tsx
index 17794a618a..31a2f5525c 100644
--- a/web/components/issues/issue-detail/issue-activity/activity-comment-root.tsx
+++ b/web/components/issues/issue-detail/issue-activity/activity-comment-root.tsx
@@ -10,6 +10,7 @@ import { TActivityOperations } from "./root";
type TIssueActivityCommentRoot = {
workspaceSlug: string;
+ projectId: string;
issueId: string;
activityOperations: TActivityOperations;
showAccessSpecifier?: boolean;
@@ -17,7 +18,7 @@ type TIssueActivityCommentRoot = {
};
export const IssueActivityCommentRoot: FC<TIssueActivityCommentRoot> = observer((props) => {
- const { workspaceSlug, issueId, activityOperations, showAccessSpecifier, disabled } = props;
+ const { workspaceSlug, issueId, activityOperations, showAccessSpecifier, projectId, disabled } = props;
// hooks
const {
activity: { getActivityCommentByIssueId },
@@ -32,6 +33,7 @@ export const IssueActivityCommentRoot: FC<TIssueActivityCommentRoot> = observer(
{activityComments.map((activityComment, index) =>
activityComment.activity_type === "COMMENT" ? (
<IssueCommentCard
+ projectId={projectId}
key={activityComment.id}
workspaceSlug={workspaceSlug}
commentId={activityComment.id}
diff --git a/web/components/issues/issue-detail/issue-activity/comments/comment-card.tsx b/web/components/issues/issue-detail/issue-activity/comments/comment-card.tsx
index 8f694af09b..8f5ad9e433 100644
--- a/web/components/issues/issue-detail/issue-activity/comments/comment-card.tsx
+++ b/web/components/issues/issue-detail/issue-activity/comments/comment-card.tsx
@@ -1,25 +1,25 @@
import { FC, useEffect, useRef, useState } from "react";
import { useForm } from "react-hook-form";
import { Check, Globe2, Lock, Pencil, Trash2, X } from "lucide-react";
-import { LiteTextEditorWithRef, LiteReadOnlyEditorWithRef } from "@plane/lite-text-editor";
+import { EditorReadOnlyRefApi, EditorRefApi } from "@plane/lite-text-editor";
import { TIssueComment } from "@plane/types";
-// hooks
+// ui
import { CustomMenu } from "@plane/ui";
+// components
+import { LiteTextEditor, LiteTextReadOnlyEditor } from "@/components/editor";
+// constants
+import { EIssueCommentAccessSpecifier } from "@/constants/issue";
+// helpers
import { isEmptyHtmlString } from "@/helpers/string.helper";
-import { useIssueDetail, useMention, useUser, useWorkspace } from "@/hooks/store";
+// hooks
+import { useIssueDetail, useUser, useWorkspace } from "@/hooks/store";
// components
-// ui
-// services
-import { FileService } from "@/services/file.service";
-// types
import { IssueCommentReaction } from "../../reactions/issue-comment";
import { TActivityOperations } from "../root";
import { IssueCommentBlock } from "./comment-block";
-// helpers
-
-const fileService = new FileService();
type TIssueCommentCard = {
+ projectId: string;
workspaceSlug: string;
commentId: string;
activityOperations: TActivityOperations;
@@ -29,16 +29,23 @@ type TIssueCommentCard = {
};
export const IssueCommentCard: FC<TIssueCommentCard> = (props) => {
- const { workspaceSlug, commentId, activityOperations, ends, showAccessSpecifier = false, disabled = false } = props;
+ const {
+ workspaceSlug,
+ projectId,
+ commentId,
+ activityOperations,
+ ends,
+ showAccessSpecifier = false,
+ disabled = false,
+ } = props;
// hooks
const {
comment: { getCommentById },
} = useIssueDetail();
const { currentUser } = useUser();
- const { mentionHighlights, mentionSuggestions } = useMention();
// refs
- const editorRef = useRef<any>(null);
- const showEditorRef = useRef<any>(null);
+ const editorRef = useRef<EditorRefApi>(null);
+ const showEditorRef = useRef<EditorReadOnlyRefApi>(null);
// state
const [isEditing, setIsEditing] = useState(false);
@@ -62,8 +69,8 @@ export const IssueCommentCard: FC<TIssueCommentCard> = (props) => {
activityOperations.updateComment(comment.id, formData);
- editorRef.current?.setEditorValue(formData.comment_html);
- showEditorRef.current?.setEditorValue(formData.comment_html);
+ editorRef.current?.setEditorValue(formData?.comment_html ?? "<p></p>");
+ showEditorRef.current?.setEditorValue(formData?.comment_html ?? "<p></p>");
};
useEffect(() => {
@@ -92,7 +99,9 @@ export const IssueCommentCard: FC<TIssueCommentCard> = (props) => {
<>
{comment.access === "INTERNAL" ? (
<CustomMenu.MenuItem
- onClick={() => activityOperations.updateComment(comment.id, { access: "EXTERNAL" })}
+ onClick={() =>
+ activityOperations.updateComment(comment.id, { access: EIssueCommentAccessSpecifier.EXTERNAL })
+ }
className="flex items-center gap-1"
>
<Globe2 className="h-3 w-3" />
@@ -100,7 +109,9 @@ export const IssueCommentCard: FC<TIssueCommentCard> = (props) => {
</CustomMenu.MenuItem>
) : (
<CustomMenu.MenuItem
- onClick={() => activityOperations.updateComment(comment.id, { access: "INTERNAL" })}
+ onClick={() =>
+ activityOperations.updateComment(comment.id, { access: EIssueCommentAccessSpecifier.INTERNAL })
+ }
className="flex items-center gap-1"
>
<Lock className="h-3 w-3" />
@@ -126,23 +137,18 @@ export const IssueCommentCard: FC<TIssueCommentCard> = (props) => {
<form className={`flex-col gap-2 ${isEditing ? "flex" : "hidden"}`}>
<div
onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey && !isEmpty) {
- handleSubmit(onEnter)(e);
- }
+ if (e.key === "Enter" && !e.shiftKey && !isEmpty) handleSubmit(onEnter)(e);
}}
>
- <LiteTextEditorWithRef
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(comment?.workspace_detail?.slug as string)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
+ <LiteTextEditor
+ workspaceId={workspaceId}
+ projectId={projectId}
+ workspaceSlug={workspaceSlug}
ref={editorRef}
- value={watch("comment_html") ?? ""}
- debouncedUpdatesEnabled={false}
- customClassName="min-h-[50px] p-3 shadow-sm"
- onChange={(comment_json: any, comment_html: string) => setValue("comment_html", comment_html)}
- mentionSuggestions={mentionSuggestions}
- mentionHighlights={mentionHighlights}
+ initialValue={watch("comment_html") ?? ""}
+ value={null}
+ onChange={(comment_json, comment_html) => setValue("comment_html", comment_html)}
+ showSubmitButton={false}
/>
</div>
<div className="flex gap-1 self-end">
@@ -170,15 +176,14 @@ export const IssueCommentCard: FC<TIssueCommentCard> = (props) => {
<div className={`relative ${isEditing ? "hidden" : ""}`}>
{showAccessSpecifier && (
<div className="absolute right-2.5 top-2.5 z-[1] text-custom-text-300">
- {comment.access === "INTERNAL" ? <Lock className="h-3 w-3" /> : <Globe2 className="h-3 w-3" />}
+ {comment.access === EIssueCommentAccessSpecifier.INTERNAL ? (
+ <Lock className="h-3 w-3" />
+ ) : (
+ <Globe2 className="h-3 w-3" />
+ )}
</div>
)}
- <LiteReadOnlyEditorWithRef
- ref={showEditorRef}
- value={comment.comment_html ?? ""}
- customClassName="text-xs border border-custom-border-200 bg-custom-background-100"
- mentionHighlights={mentionHighlights}
- />
+ <LiteTextReadOnlyEditor ref={showEditorRef} initialValue={comment.comment_html ?? ""} />
<IssueCommentReaction
workspaceSlug={workspaceSlug}
diff --git a/web/components/issues/issue-detail/issue-activity/comments/comment-create.tsx b/web/components/issues/issue-detail/issue-activity/comments/comment-create.tsx
index 04fb1e0b42..6261e693ab 100644
--- a/web/components/issues/issue-detail/issue-activity/comments/comment-create.tsx
+++ b/web/components/issues/issue-detail/issue-activity/comments/comment-create.tsx
@@ -1,82 +1,61 @@
import { FC, useRef } from "react";
import { useForm, Controller } from "react-hook-form";
-import { Globe2, Lock } from "lucide-react";
-import { LiteTextEditorWithRef } from "@plane/lite-text-editor";
+// types
import { TIssueComment } from "@plane/types";
// components
-import { Button } from "@plane/ui";
-// services
+import { LiteTextEditor } from "@/components/editor/lite-text-editor/lite-text-editor";
+// constants
+import { EIssueCommentAccessSpecifier } from "@/constants/issue";
+// helpers
import { isEmptyHtmlString } from "@/helpers/string.helper";
-import { useMention, useWorkspace } from "@/hooks/store";
-import { FileService } from "@/services/file.service";
-// types
+// hooks
+import { useWorkspace } from "@/hooks/store";
+// editor
import { TActivityOperations } from "../root";
-// icons
-// helpers
-
-const fileService = new FileService();
type TIssueCommentCreate = {
+ projectId: string;
workspaceSlug: string;
activityOperations: TActivityOperations;
showAccessSpecifier?: boolean;
};
-type commentAccessType = {
- icon: any;
- key: string;
- label: "Private" | "Public";
-};
-const commentAccess: commentAccessType[] = [
- {
- icon: Lock,
- key: "INTERNAL",
- label: "Private",
- },
- {
- icon: Globe2,
- key: "EXTERNAL",
- label: "Public",
- },
-];
-
export const IssueCommentCreate: FC<TIssueCommentCreate> = (props) => {
- const { workspaceSlug, activityOperations, showAccessSpecifier = false } = props;
- const workspaceStore = useWorkspace();
- const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug as string)?.id as string;
-
- const { mentionHighlights, mentionSuggestions } = useMention();
-
+ const { workspaceSlug, projectId, activityOperations, showAccessSpecifier = false } = props;
// refs
const editorRef = useRef<any>(null);
- // react hook form
+ // store hooks
+ const workspaceStore = useWorkspace();
+ // derived values
+ const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug as string)?.id as string;
+ // form info
const {
handleSubmit,
control,
watch,
formState: { isSubmitting },
reset,
- } = useForm<Partial<TIssueComment>>({ defaultValues: { comment_html: "<p></p>" } });
+ } = useForm<Partial<TIssueComment>>({
+ defaultValues: {
+ comment_html: "<p></p>",
+ },
+ });
- const onSubmit = async (formData: Partial<TIssueComment>) => {
+ const onSubmit = async (formData: Partial<TIssueComment>) =>
await activityOperations.createComment(formData).finally(() => {
- reset({ comment_html: "" });
+ reset({
+ comment_html: "<p></p>",
+ });
editorRef.current?.clearEditor();
});
- };
- const isEmpty =
- watch("comment_html") === "" ||
- watch("comment_html")?.trim() === "" ||
- watch("comment_html") === "<p></p>" ||
- (isEmptyHtmlString(watch("comment_html") ?? "") && !watch("comment_html")?.includes("mention-component"));
+ const commentHTML = watch("comment_html");
+ const isEmpty = commentHTML?.trim() === "" || commentHTML === "<p></p>" || isEmptyHtmlString(commentHTML ?? "");
return (
<div
onKeyDown={(e) => {
- if (e.key === "Enter" && !e.shiftKey && !isEmpty && !isSubmitting) {
- handleSubmit(onSubmit)(e);
- }
+ if (e.key === "Enter" && !e.shiftKey && !isEmpty && !isSubmitting) handleSubmit(onSubmit)(e);
}}
>
<Controller
@@ -87,39 +66,19 @@ export const IssueCommentCreate: FC<TIssueCommentCreate> = (props) => {
name="comment_html"
control={control}
render={({ field: { value, onChange } }) => (
- <LiteTextEditorWithRef
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
+ <LiteTextEditor
+ workspaceId={workspaceId}
+ projectId={projectId}
+ workspaceSlug={workspaceSlug}
+ onEnterKeyPress={(e) => handleSubmit(onSubmit)(e)}
ref={editorRef}
- value={!value ? "<p></p>" : value}
- customClassName="p-2"
- editorContentCustomClassNames="min-h-[35px]"
- debouncedUpdatesEnabled={false}
- onChange={(comment_json: any, comment_html: string) => {
- onChange(comment_html);
- }}
- mentionSuggestions={mentionSuggestions}
- mentionHighlights={mentionHighlights}
- commentAccessSpecifier={
- showAccessSpecifier
- ? { accessValue: accessValue ?? "INTERNAL", onAccessChange, showAccessSpecifier, commentAccess }
- : undefined
- }
- submitButton={
- <Button
- disabled={isSubmitting || isEmpty}
- variant="primary"
- type="submit"
- className="!px-2.5 !py-1.5 !text-xs"
- onClick={(e) => {
- handleSubmit(onSubmit)(e);
- }}
- >
- {isSubmitting ? "Adding..." : "Comment"}
- </Button>
- }
+ initialValue={value ?? "<p></p>"}
+ containerClassName="min-h-[35px]"
+ onChange={(comment_json, comment_html) => onChange(comment_html)}
+ accessSpecifier={accessValue ?? EIssueCommentAccessSpecifier.INTERNAL}
+ handleAccessChange={onAccessChange}
+ showAccessSpecifier={showAccessSpecifier}
+ isSubmitting={isSubmitting}
/>
)}
/>
diff --git a/web/components/issues/issue-detail/issue-activity/comments/index.ts b/web/components/issues/issue-detail/issue-activity/comments/index.ts
new file mode 100644
index 0000000000..8077dd06d2
--- /dev/null
+++ b/web/components/issues/issue-detail/issue-activity/comments/index.ts
@@ -0,0 +1,4 @@
+export * from "./comment-block";
+export * from "./comment-card";
+export * from "./comment-create";
+export * from "./root";
diff --git a/web/components/issues/issue-detail/issue-activity/comments/root.tsx b/web/components/issues/issue-detail/issue-activity/comments/root.tsx
index d374da8758..1db216537e 100644
--- a/web/components/issues/issue-detail/issue-activity/comments/root.tsx
+++ b/web/components/issues/issue-detail/issue-activity/comments/root.tsx
@@ -8,6 +8,7 @@ import { IssueCommentCard } from "./comment-card";
// types
type TIssueCommentRoot = {
+ projectId: string;
workspaceSlug: string;
issueId: string;
activityOperations: TActivityOperations;
@@ -16,7 +17,7 @@ type TIssueCommentRoot = {
};
export const IssueCommentRoot: FC<TIssueCommentRoot> = observer((props) => {
- const { workspaceSlug, issueId, activityOperations, showAccessSpecifier, disabled } = props;
+ const { workspaceSlug, projectId, issueId, activityOperations, showAccessSpecifier, disabled } = props;
// hooks
const {
comment: { getCommentsByIssueId },
@@ -29,6 +30,7 @@ export const IssueCommentRoot: FC<TIssueCommentRoot> = observer((props) => {
<div>
{commentIds.map((commentId, index) => (
<IssueCommentCard
+ projectId={projectId}
key={commentId}
workspaceSlug={workspaceSlug}
commentId={commentId}
diff --git a/web/components/issues/issue-detail/issue-activity/index.ts b/web/components/issues/issue-detail/issue-activity/index.ts
index 5c6634ce58..13b2088357 100644
--- a/web/components/issues/issue-detail/issue-activity/index.ts
+++ b/web/components/issues/issue-detail/issue-activity/index.ts
@@ -7,6 +7,4 @@ export * from "./activity/root";
export * from "./activity/activity-list";
// issue comment
-export * from "./comments/root";
-export * from "./comments/comment-card";
-export * from "./comments/comment-create";
+export * from "./comments";
diff --git a/web/components/issues/issue-detail/issue-activity/root.tsx b/web/components/issues/issue-detail/issue-activity/root.tsx
index 1056ecf778..cdcd63057d 100644
--- a/web/components/issues/issue-detail/issue-activity/root.tsx
+++ b/web/components/issues/issue-detail/issue-activity/root.tsx
@@ -1,14 +1,14 @@
import { FC, useMemo, useState } from "react";
import { observer } from "mobx-react-lite";
import { History, LucideIcon, MessageCircle, ListRestart } from "lucide-react";
+// types
import { TIssueComment } from "@plane/types";
-// hooks
-import { TOAST_TYPE, setToast } from "@plane/ui";
-import { useIssueDetail, useProject } from "@/hooks/store";
// ui
+import { TOAST_TYPE, setToast } from "@plane/ui";
// components
-import { IssueActivityCommentRoot, IssueActivityRoot, IssueCommentRoot, IssueCommentCreate } from "./";
-// types
+import { IssueActivityCommentRoot, IssueActivityRoot, IssueCommentRoot, IssueCommentCreate } from "@/components/issues";
+// hooks
+import { useIssueDetail, useProject } from "@/hooks/store";
type TIssueActivity = {
workspaceSlug: string;
@@ -142,6 +142,7 @@ export const IssueActivity: FC<TIssueActivity> = observer((props) => {
{activityTab === "all" ? (
<div className="space-y-3">
<IssueActivityCommentRoot
+ projectId={projectId}
workspaceSlug={workspaceSlug}
issueId={issueId}
activityOperations={activityOperations}
@@ -150,6 +151,7 @@ export const IssueActivity: FC<TIssueActivity> = observer((props) => {
/>
{!disabled && (
<IssueCommentCreate
+ projectId={projectId}
workspaceSlug={workspaceSlug}
activityOperations={activityOperations}
showAccessSpecifier={project.is_deployed}
@@ -161,6 +163,7 @@ export const IssueActivity: FC<TIssueActivity> = observer((props) => {
) : (
<div className="space-y-3">
<IssueCommentRoot
+ projectId={projectId}
workspaceSlug={workspaceSlug}
issueId={issueId}
activityOperations={activityOperations}
@@ -169,6 +172,7 @@ export const IssueActivity: FC<TIssueActivity> = observer((props) => {
/>
{!disabled && (
<IssueCommentCreate
+ projectId={projectId}
workspaceSlug={workspaceSlug}
activityOperations={activityOperations}
showAccessSpecifier={project.is_deployed}
diff --git a/web/components/issues/issue-detail/main-content.tsx b/web/components/issues/issue-detail/main-content.tsx
index 28e01fd1e3..92e72c63a9 100644
--- a/web/components/issues/issue-detail/main-content.tsx
+++ b/web/components/issues/issue-detail/main-content.tsx
@@ -1,8 +1,12 @@
import { useEffect, useState } from "react";
import { observer } from "mobx-react-lite";
-// hooks
+// types
+import { TIssue } from "@plane/types";
+// ui
import { StateGroupIcon } from "@plane/ui";
+// components
import { IssueAttachmentRoot, IssueUpdateStatus } from "@/components/issues";
+// hooks
import { useIssueDetail, useProjectState, useUser } from "@/hooks/store";
import useReloadConfirmations from "@/hooks/use-reload-confirmation";
// components
@@ -12,8 +16,6 @@ import { IssueTitleInput } from "../title-input";
import { IssueActivity } from "./issue-activity";
import { IssueParentDetail } from "./parent";
import { IssueReaction } from "./reactions";
-// ui
-// types
import { TIssueOperations } from "./root";
type Props = {
@@ -22,10 +24,11 @@ type Props = {
issueId: string;
issueOperations: TIssueOperations;
isEditable: boolean;
+ swrIssueDetails: TIssue | null | undefined;
};
export const IssueMainContent: React.FC<Props> = observer((props) => {
- const { workspaceSlug, projectId, issueId, issueOperations, isEditable } = props;
+ const { workspaceSlug, projectId, issueId, issueOperations, isEditable, swrIssueDetails } = props;
// states
const [isSubmitting, setIsSubmitting] = useState<"submitting" | "submitted" | "saved">("saved");
// hooks
@@ -39,12 +42,8 @@ export const IssueMainContent: React.FC<Props> = observer((props) => {
useEffect(() => {
if (isSubmitting === "submitted") {
setShowAlert(false);
- setTimeout(async () => {
- setIsSubmitting("saved");
- }, 2000);
- } else if (isSubmitting === "submitting") {
- setShowAlert(true);
- }
+ setTimeout(async () => setIsSubmitting("saved"), 2000);
+ } else if (isSubmitting === "submitting") setShowAlert(true);
}, [isSubmitting, setShowAlert, setIsSubmitting]);
const issue = issueId ? getIssueById(issueId) : undefined;
@@ -52,13 +51,6 @@ export const IssueMainContent: React.FC<Props> = observer((props) => {
const currentIssueState = projectStates?.find((s) => s.id === issue.state_id);
- const issueDescription =
- issue.description_html !== undefined || issue.description_html !== null
- ? issue.description_html != ""
- ? issue.description_html
- : "<p></p>"
- : undefined;
-
return (
<>
<div className="rounded-lg space-y-4">
@@ -94,16 +86,18 @@ export const IssueMainContent: React.FC<Props> = observer((props) => {
value={issue.name}
/>
+ {/* {issue?.description_html === issueDescription && ( */}
<IssueDescriptionInput
+ swrIssueDescription={swrIssueDetails?.description_html}
workspaceSlug={workspaceSlug}
projectId={issue.project_id}
issueId={issue.id}
- value={issueDescription}
- initialValue={issueDescription}
+ initialValue={issue.description_html}
disabled={!isEditable}
issueOperations={issueOperations}
setIsSubmitting={(value) => setIsSubmitting(value)}
/>
+ {/* )} */}
{currentUser && (
<IssueReaction
diff --git a/web/components/issues/issue-detail/root.tsx b/web/components/issues/issue-detail/root.tsx
index 46f5dd1452..14a0a8eb57 100644
--- a/web/components/issues/issue-detail/root.tsx
+++ b/web/components/issues/issue-detail/root.tsx
@@ -48,10 +48,11 @@ export type TIssueDetailRoot = {
projectId: string;
issueId: string;
is_archived?: boolean;
+ swrIssueDetails: TIssue | null | undefined;
};
export const IssueDetailRoot: FC<TIssueDetailRoot> = observer((props) => {
- const { workspaceSlug, projectId, issueId, is_archived = false } = props;
+ const { workspaceSlug, projectId, issueId, swrIssueDetails, is_archived = false } = props;
// router
const router = useRouter();
// hooks
@@ -359,6 +360,7 @@ export const IssueDetailRoot: FC<TIssueDetailRoot> = observer((props) => {
<div className="max-w-2/3 h-full w-full space-y-5 divide-y-2 divide-custom-border-200 overflow-y-auto p-5">
<IssueMainContent
workspaceSlug={workspaceSlug}
+ swrIssueDetails={swrIssueDetails}
projectId={projectId}
issueId={issueId}
issueOperations={issueOperations}
diff --git a/web/components/issues/issue-layouts/filters/header/helpers/filter-header.tsx b/web/components/issues/issue-layouts/filters/header/helpers/filter-header.tsx
index a2d2f0ac94..bed8057401 100644
--- a/web/components/issues/issue-layouts/filters/header/helpers/filter-header.tsx
+++ b/web/components/issues/issue-layouts/filters/header/helpers/filter-header.tsx
@@ -10,7 +10,7 @@ interface IFilterHeader {
export const FilterHeader = ({ title, isPreviewEnabled, handleIsPreviewEnabled }: IFilterHeader) => (
<div className="sticky top-0 flex items-center justify-between gap-2 bg-custom-background-100">
- <div className="flex-grow truncate text-xs font-medium text-custom-text-300">{title}</div>
+ <div className="flex-grow truncate text-xs font-medium text-custom-text-400">{title}</div>
<button
type="button"
className="grid h-5 w-5 flex-shrink-0 place-items-center rounded hover:bg-custom-background-80"
diff --git a/web/components/issues/issue-modal/form.tsx b/web/components/issues/issue-modal/form.tsx
index a713327f6b..a1e4b60b0d 100644
--- a/web/components/issues/issue-modal/form.tsx
+++ b/web/components/issues/issue-modal/form.tsx
@@ -3,9 +3,8 @@ import { observer } from "mobx-react-lite";
import { useRouter } from "next/router";
import { Controller, useForm } from "react-hook-form";
import { LayoutPanelTop, Sparkle, X } from "lucide-react";
-import { RichTextEditorWithRef } from "@plane/rich-text-editor";
+import { EditorRefApi } from "@plane/rich-text-editor";
import type { TIssue, ISearchIssueResponse } from "@plane/types";
-// editor
// hooks
import { Button, CustomMenu, Input, Loader, ToggleSwitch, TOAST_TYPE, setToast } from "@plane/ui";
import { GptAssistantPopover } from "@/components/core";
@@ -19,17 +18,17 @@ import {
MemberDropdown,
StateDropdown,
} from "@/components/dropdowns";
+import { RichTextEditor } from "@/components/editor/rich-text-editor/rich-text-editor";
import { ParentIssuesListModal } from "@/components/issues";
import { IssueLabelSelect } from "@/components/issues/select";
import { CreateLabelModal } from "@/components/labels";
import { renderFormattedPayloadDate, getDate } from "@/helpers/date-time.helper";
import { getChangedIssuefields } from "@/helpers/issue.helper";
import { shouldRenderProject } from "@/helpers/project.helper";
-import { useApplication, useEstimate, useIssueDetail, useMention, useProject, useWorkspace } from "@/hooks/store";
+import { useApplication, useEstimate, useIssueDetail, useProject, useWorkspace } from "@/hooks/store";
import { useProjectIssueProperties } from "@/hooks/use-project-issue-properties";
// services
import { AIService } from "@/services/ai.service";
-import { FileService } from "@/services/file.service";
// components
// ui
// helpers
@@ -65,7 +64,6 @@ export interface IssueFormProps {
// services
const aiService = new AIService();
-const fileService = new FileService();
const TAB_INDICES = [
"name",
@@ -112,7 +110,7 @@ export const IssueFormRoot: FC<IssueFormProps> = observer((props) => {
const [iAmFeelingLucky, setIAmFeelingLucky] = useState(false);
// refs
- const editorRef = useRef<any>(null);
+ const editorRef = useRef<EditorRefApi>(null);
// router
const router = useRouter();
const { workspaceSlug } = router.query;
@@ -126,7 +124,7 @@ export const IssueFormRoot: FC<IssueFormProps> = observer((props) => {
} = useApplication();
const { getProjectById } = useProject();
const { areEstimatesEnabledForProject } = useEstimate();
- const { mentionHighlights, mentionSuggestions } = useMention();
+
const {
issue: { getIssueById },
} = useIssueDetail();
@@ -462,36 +460,26 @@ export const IssueFormRoot: FC<IssueFormProps> = observer((props) => {
/>
)}
</div>
- {data?.description_html && watch("description_html") && (
- <Controller
- name="description_html"
- control={control}
- render={({ field: { value, onChange } }) => (
- <RichTextEditorWithRef
- cancelUploadImage={fileService.cancelUpload}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
- ref={editorRef}
- debouncedUpdatesEnabled={false}
- value={
- !value || value === "" || (typeof value === "object" && Object.keys(value).length === 0)
- ? watch("description_html")
- : value
- }
- initialValue={data?.description_html}
- customClassName="min-h-[7rem] border-custom-border-100"
- onChange={(description: any, description_html: string) => {
- onChange(description_html === "" ? "<p></p>" : description_html);
- handleFormChange();
- }}
- mentionHighlights={mentionHighlights}
- mentionSuggestions={mentionSuggestions}
- tabIndex={getTabIndex("description_html")}
- />
- )}
- />
- )}
+ <Controller
+ name="description_html"
+ control={control}
+ render={({ field: { value, onChange } }) => (
+ <RichTextEditor
+ initialValue={value}
+ value={data.description_html}
+ workspaceSlug={workspaceSlug?.toString() as string}
+ workspaceId={workspaceId}
+ projectId={projectId}
+ // dragDropEnabled={false}
+ onChange={(_description: object, description_html: string) => {
+ onChange(description_html);
+ handleFormChange();
+ }}
+ ref={editorRef}
+ tabIndex={getTabIndex("description_html")}
+ />
+ )}
+ />
</Fragment>
)}
</div>
diff --git a/web/components/issues/issue-update-status.tsx b/web/components/issues/issue-update-status.tsx
index a3a8ca83be..018e5754aa 100644
--- a/web/components/issues/issue-update-status.tsx
+++ b/web/components/issues/issue-update-status.tsx
@@ -24,7 +24,7 @@ export const IssueUpdateStatus: React.FC<Props> = observer((props) => {
)}
<div
className={`flex items-center gap-x-2 transition-all duration-300 ${
- isSubmitting === "saved" ? "fadeOut" : "fadeIn"
+ isSubmitting === "saved" ? "fade-out" : "fade-in"
}`}
>
{isSubmitting !== "submitted" && isSubmitting !== "saved" && (
diff --git a/web/components/issues/peek-overview/issue-detail.tsx b/web/components/issues/peek-overview/issue-detail.tsx
index ab84dc3c0f..82fb4d15f8 100644
--- a/web/components/issues/peek-overview/issue-detail.tsx
+++ b/web/components/issues/peek-overview/issue-detail.tsx
@@ -74,8 +74,9 @@ export const PeekOverviewIssueDetails: FC<IPeekOverviewIssueDetails> = observer(
workspaceSlug={workspaceSlug}
projectId={issue.project_id}
issueId={issue.id}
- value={issueDescription}
initialValue={issueDescription}
+ // for now peek overview doesn't have live syncing while tab changes
+ swrIssueDescription={null}
disabled={disabled}
issueOperations={issueOperations}
setIsSubmitting={(value) => setIsSubmitting(value)}
diff --git a/web/components/pages/create-update-page-modal.tsx b/web/components/pages/create-update-page-modal.tsx
deleted file mode 100644
index 3f077d0c6d..0000000000
--- a/web/components/pages/create-update-page-modal.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import React, { FC } from "react";
-import { useRouter } from "next/router";
-import { Dialog, Transition } from "@headlessui/react";
-import { IPage } from "@plane/types";
-// components
-import { PAGE_CREATED, PAGE_UPDATED } from "@/constants/event-tracker";
-import { useEventTracker } from "@/hooks/store";
-// hooks
-// types
-import { useProjectPages } from "@/hooks/store/use-project-page";
-import { IPageStore } from "@/store/page.store";
-import { PageForm } from "./page-form";
-// constants
-
-type Props = {
- // data?: IPage | null;
- pageStore?: IPageStore;
- handleClose: () => void;
- isOpen: boolean;
- projectId: string;
-};
-
-export const CreateUpdatePageModal: FC<Props> = (props) => {
- const { isOpen, handleClose, projectId, pageStore } = props;
- // router
- const router = useRouter();
- const { workspaceSlug } = router.query;
- // store hooks
- const { createPage } = useProjectPages();
- const { capturePageEvent } = useEventTracker();
-
- const createProjectPage = async (payload: IPage) => {
- if (!workspaceSlug) return;
- await createPage(workspaceSlug.toString(), projectId, payload)
- .then((res) => {
- capturePageEvent({
- eventName: PAGE_CREATED,
- payload: {
- ...res,
- state: "SUCCESS",
- },
- });
- })
- .catch(() => {
- capturePageEvent({
- eventName: PAGE_CREATED,
- payload: {
- state: "FAILED",
- },
- });
- });
- };
-
- const handleFormSubmit = async (formData: IPage) => {
- if (!workspaceSlug || !projectId) return;
- try {
- if (pageStore) {
- if (pageStore.name !== formData.name) {
- await pageStore.updateName(formData.name);
- }
- if (pageStore.access !== formData.access) {
- formData.access === 1 ? await pageStore.makePrivate() : await pageStore.makePublic();
- }
- capturePageEvent({
- eventName: PAGE_UPDATED,
- payload: {
- ...pageStore,
- state: "SUCCESS",
- },
- });
- } else {
- await createProjectPage(formData);
- }
- handleClose();
- } catch (error) {
- console.log(error);
- }
- };
-
- return (
- <Transition.Root show={isOpen} as={React.Fragment}>
- <Dialog as="div" className="relative z-20" onClose={handleClose}>
- <Transition.Child
- as={React.Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0"
- enterTo="opacity-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
- >
- <div className="fixed inset-0 bg-custom-backdrop transition-opacity" />
- </Transition.Child>
-
- <div className="fixed inset-0 z-20 overflow-y-auto">
- <div className="my-10 flex justify-center p-4 text-center sm:p-0 md:my-20">
- <Transition.Child
- as={React.Fragment}
- enter="ease-out duration-300"
- enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- enterTo="opacity-100 translate-y-0 sm:scale-100"
- leave="ease-in duration-200"
- leaveFrom="opacity-100 translate-y-0 sm:scale-100"
- leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
- >
- <Dialog.Panel className="relative transform rounded-lg bg-custom-background-100 p-5 px-4 text-left shadow-custom-shadow-md transition-all w-full sm:max-w-2xl">
- <PageForm handleFormSubmit={handleFormSubmit} handleClose={handleClose} pageStore={pageStore} />
- </Dialog.Panel>
- </Transition.Child>
- </div>
- </div>
- </Dialog>
- </Transition.Root>
- );
-};
diff --git a/web/components/pages/dropdowns/index.ts b/web/components/pages/dropdowns/index.ts
new file mode 100644
index 0000000000..db98841b0e
--- /dev/null
+++ b/web/components/pages/dropdowns/index.ts
@@ -0,0 +1 @@
+export * from "./quick-actions";
diff --git a/web/components/pages/dropdowns/quick-actions.tsx b/web/components/pages/dropdowns/quick-actions.tsx
new file mode 100644
index 0000000000..241b08ae91
--- /dev/null
+++ b/web/components/pages/dropdowns/quick-actions.tsx
@@ -0,0 +1,131 @@
+import { useState } from "react";
+import { observer } from "mobx-react";
+import { ArchiveRestoreIcon, ExternalLink, Link, Lock, Trash2, UsersRound } from "lucide-react";
+import { ArchiveIcon, CustomMenu, TOAST_TYPE, setToast } from "@plane/ui";
+// components
+import { DeletePageModal } from "@/components/pages";
+// helpers
+import { copyUrlToClipboard } from "@/helpers/string.helper";
+// hooks
+import { usePage } from "@/hooks/store";
+
+type Props = {
+ pageId: string;
+ projectId: string;
+ workspaceSlug: string;
+};
+
+export const PageQuickActions: React.FC<Props> = observer((props) => {
+ const { pageId, projectId, workspaceSlug } = props;
+ // states
+ const [deletePageModal, setDeletePageModal] = useState(false);
+ // store hooks
+ const { access, archive, archived_at, makePublic, makePrivate, restore } = usePage(pageId);
+
+ const pageLink = `${workspaceSlug}/projects/${projectId}/pages/${pageId}`;
+ const handleCopyText = () =>
+ copyUrlToClipboard(pageLink).then(() => {
+ setToast({
+ type: TOAST_TYPE.SUCCESS,
+ title: "Link Copied!",
+ message: "Page link copied to clipboard.",
+ });
+ });
+ const handleOpenInNewTab = () => window.open(`/${pageLink}`, "_blank");
+
+ return (
+ <>
+ <DeletePageModal
+ isOpen={deletePageModal}
+ onClose={() => setDeletePageModal(false)}
+ pageId={pageId}
+ projectId={projectId}
+ />
+ <CustomMenu placement="bottom-end" ellipsis closeOnSelect>
+ <CustomMenu.MenuItem
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleCopyText();
+ }}
+ >
+ <span className="flex items-center gap-2">
+ <Link className="h-3 w-3" />
+ Copy link
+ </span>
+ </CustomMenu.MenuItem>
+ <CustomMenu.MenuItem
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleOpenInNewTab();
+ }}
+ >
+ <span className="flex items-center gap-2">
+ <ExternalLink className="h-3 w-3" />
+ Open in new tab
+ </span>
+ </CustomMenu.MenuItem>
+ <CustomMenu.MenuItem
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ if (archived_at) restore();
+ else archive();
+ }}
+ >
+ <span className="flex items-center gap-2">
+ {archived_at ? (
+ <>
+ <ArchiveRestoreIcon className="h-3 w-3" />
+ Restore
+ </>
+ ) : (
+ <>
+ <ArchiveIcon className="h-3 w-3" />
+ Archive
+ </>
+ )}
+ </span>
+ </CustomMenu.MenuItem>
+ {!archived_at && (
+ <CustomMenu.MenuItem
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ access === 0 ? makePrivate() : makePublic();
+ }}
+ >
+ <span className="flex items-center gap-2">
+ {access === 0 ? (
+ <>
+ <Lock className="h-3 w-3" />
+ Make private
+ </>
+ ) : (
+ <>
+ <UsersRound className="h-3 w-3" />
+ Make public
+ </>
+ )}
+ </span>
+ </CustomMenu.MenuItem>
+ )}
+ {archived_at && (
+ <CustomMenu.MenuItem
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setDeletePageModal(true);
+ }}
+ >
+ <span className="flex items-center gap-2">
+ <Trash2 className="h-3 w-3" />
+ Delete
+ </span>
+ </CustomMenu.MenuItem>
+ )}
+ </CustomMenu>
+ </>
+ );
+});
diff --git a/web/components/pages/editor/editor-body.tsx b/web/components/pages/editor/editor-body.tsx
new file mode 100644
index 0000000000..260b90b6fd
--- /dev/null
+++ b/web/components/pages/editor/editor-body.tsx
@@ -0,0 +1,173 @@
+import { useEffect } from "react";
+import { observer } from "mobx-react";
+import { useRouter } from "next/router";
+import { Control, Controller } from "react-hook-form";
+// document editor
+import {
+ DocumentEditorWithRef,
+ DocumentReadOnlyEditorWithRef,
+ EditorReadOnlyRefApi,
+ EditorRefApi,
+ IMarking,
+} from "@plane/document-editor";
+// types
+import { IUserLite, TPage } from "@plane/types";
+// components
+import { PageContentBrowser, PageEditorTitle } from "@/components/pages";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// hooks
+import { useMember, useMention, useUser, useWorkspace } from "@/hooks/store";
+import useReloadConfirmations from "@/hooks/use-reload-confirmation";
+// services
+import { FileService } from "@/services/file.service";
+// store
+import { IPageStore } from "@/store/pages/page.store";
+
+const fileService = new FileService();
+
+type Props = {
+ control: Control<TPage, any>;
+ editorRef: React.RefObject<EditorRefApi>;
+ readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
+ swrPageDetails: TPage | undefined;
+ handleSubmit: () => void;
+ markings: IMarking[];
+ pageStore: IPageStore;
+ sidePeekVisible: boolean;
+ handleEditorReady: (value: boolean) => void;
+ handleReadOnlyEditorReady: (value: boolean) => void;
+ updateMarkings: (description_html: string) => void;
+};
+
+export const PageEditorBody: React.FC<Props> = observer((props) => {
+ const {
+ control,
+ handleReadOnlyEditorReady,
+ handleEditorReady,
+ editorRef,
+ markings,
+ readOnlyEditorRef,
+ handleSubmit,
+ pageStore,
+ swrPageDetails,
+ sidePeekVisible,
+ updateMarkings,
+ } = props;
+ // router
+ const router = useRouter();
+ const { workspaceSlug, projectId } = router.query;
+ // store hooks
+ const { currentUser } = useUser();
+ const { getWorkspaceBySlug } = useWorkspace();
+ const {
+ getUserDetails,
+ project: { getProjectMemberIds },
+ } = useMember();
+ // derived values
+ const workspaceId = workspaceSlug ? getWorkspaceBySlug(workspaceSlug.toString())?.id ?? "" : "";
+ const pageTitle = pageStore?.name ?? "";
+ const pageDescription = pageStore?.description_html ?? "<p></p>";
+ const isFullWidth = !!pageStore?.view_props?.full_width;
+ const { description_html, isContentEditable, updateTitle, isSubmitting, setIsSubmitting } = pageStore;
+ const projectMemberIds = projectId ? getProjectMemberIds(projectId.toString()) : [];
+ const projectMemberDetails = projectMemberIds?.map((id) => getUserDetails(id) as IUserLite);
+ // use-mention
+ const { mentionHighlights, mentionSuggestions } = useMention({
+ workspaceSlug: workspaceSlug?.toString() ?? "",
+ projectId: projectId?.toString() ?? "",
+ members: projectMemberDetails,
+ user: currentUser ?? undefined,
+ });
+
+ const { setShowAlert } = useReloadConfirmations(isSubmitting === "submitting");
+
+ useEffect(() => {
+ updateMarkings(description_html ?? "<p></p>");
+ }, [description_html, updateMarkings]);
+
+ return (
+ <div className="flex items-center h-full w-full overflow-y-auto">
+ <div
+ className={cn("sticky top-0 hidden h-full flex-shrink-0 -translate-x-full p-5 duration-200 md:block", {
+ "translate-x-0": sidePeekVisible,
+ "w-56 lg:w-72": !isFullWidth,
+ "w-[10%]": isFullWidth,
+ })}
+ >
+ {!isFullWidth && (
+ <PageContentBrowser
+ editorRef={(isContentEditable ? editorRef : readOnlyEditorRef)?.current}
+ markings={markings}
+ />
+ )}
+ </div>
+ <div
+ className={cn("h-full w-full pt-5", {
+ "md:w-[calc(100%-14rem)] lg:w-[calc(100%-18rem-18rem)]": !isFullWidth,
+ "w-[80%]": isFullWidth,
+ })}
+ >
+ <div className="h-full w-full flex flex-col gap-y-7 overflow-y-auto overflow-x-hidden">
+ <div className="w-full flex-shrink-0 ml-5">
+ <PageEditorTitle
+ editorRef={editorRef}
+ title={pageTitle}
+ updateTitle={updateTitle}
+ readOnly={!isContentEditable}
+ />
+ </div>
+ {isContentEditable ? (
+ <Controller
+ name="description_html"
+ control={control}
+ render={({ field: { onChange } }) => (
+ <DocumentEditorWithRef
+ fileHandler={{
+ cancel: fileService.cancelUpload,
+ delete: fileService.getDeleteImageFunction(workspaceId),
+ restore: fileService.getRestoreImageFunction(workspaceId),
+ upload: fileService.getUploadFileFunction(workspaceSlug as string, setIsSubmitting),
+ }}
+ handleEditorReady={handleEditorReady}
+ initialValue={pageDescription}
+ value={swrPageDetails?.description_html ?? "<p></p>"}
+ ref={editorRef}
+ containerClassName="p-0 pb-64"
+ editorClassName="px-10"
+ onChange={(_description_json, description_html) => {
+ setIsSubmitting("submitting");
+ setShowAlert(true);
+ onChange(description_html);
+ handleSubmit();
+ }}
+ mentionHandler={{
+ highlights: mentionHighlights,
+ suggestions: mentionSuggestions,
+ }}
+ />
+ )}
+ />
+ ) : (
+ <DocumentReadOnlyEditorWithRef
+ ref={readOnlyEditorRef}
+ initialValue={pageDescription}
+ handleEditorReady={handleReadOnlyEditorReady}
+ containerClassName="p-0 pb-64 border-none"
+ editorClassName="px-10"
+ mentionHandler={{
+ highlights: mentionHighlights,
+ }}
+ />
+ )}
+ </div>
+ </div>
+ <div
+ className={cn("hidden lg:block h-full flex-shrink-0", {
+ "w-56 lg:w-72": !isFullWidth,
+ "w-[10%]": isFullWidth,
+ })}
+ />
+ </div>
+ );
+});
diff --git a/web/components/pages/editor/header/extra-options.tsx b/web/components/pages/editor/header/extra-options.tsx
new file mode 100644
index 0000000000..1b00cce34f
--- /dev/null
+++ b/web/components/pages/editor/header/extra-options.tsx
@@ -0,0 +1,99 @@
+import { useState } from "react";
+import { observer } from "mobx-react";
+import { Lock, RefreshCw, Sparkle } from "lucide-react";
+// editor
+import { EditorReadOnlyRefApi, EditorRefApi } from "@plane/document-editor";
+// ui
+import { ArchiveIcon } from "@plane/ui";
+// components
+import { GptAssistantPopover } from "@/components/core";
+import { PageInfoPopover, PageOptionsDropdown } from "@/components/pages";
+// helpers
+import { cn } from "@/helpers/common.helper";
+import { renderFormattedDate } from "@/helpers/date-time.helper";
+// hooks
+import { useApplication } from "@/hooks/store";
+// store
+import { IPageStore } from "@/store/pages/page.store";
+
+type Props = {
+ editorRef: React.RefObject<EditorRefApi>;
+ handleDuplicatePage: () => void;
+ pageStore: IPageStore;
+ projectId: string;
+ readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
+};
+
+export const PageExtraOptions: React.FC<Props> = observer((props) => {
+ const { editorRef, handleDuplicatePage, pageStore, projectId, readOnlyEditorRef } = props;
+ // states
+ const [gptModalOpen, setGptModal] = useState(false);
+ // store hooks
+ const {
+ config: { envConfig },
+ } = useApplication();
+ // derived values
+ const { archived_at, isContentEditable, isSubmitting, is_locked } = pageStore;
+
+ const handleAiAssistance = async (response: string) => {
+ if (!editorRef) return;
+ editorRef.current?.setEditorValueAtCursorPosition(response);
+ };
+
+ return (
+ <div className="flex flex-grow items-center justify-end gap-3">
+ {isContentEditable && (
+ <div
+ className={cn("fade-in flex items-center gap-x-2 transition-all duration-300", {
+ "fade-out": isSubmitting === "saved",
+ })}
+ >
+ {isSubmitting === "submitting" && <RefreshCw className="h-4 w-4 stroke-custom-text-300" />}
+ <span className="text-sm text-custom-text-300">{isSubmitting === "submitting" ? "Saving..." : "Saved"}</span>
+ </div>
+ )}
+ {is_locked && (
+ <div className="flex h-7 items-center gap-2 rounded-full bg-custom-background-80 px-3 py-0.5 text-xs font-medium text-custom-text-300">
+ <Lock className="h-3 w-3" />
+ <span>Locked</span>
+ </div>
+ )}
+ {archived_at && (
+ <div className="flex h-7 items-center gap-2 rounded-full bg-blue-500/20 px-3 py-0.5 text-xs font-medium text-blue-500">
+ <ArchiveIcon className="h-3 w-3" />
+ <span>Archived at {renderFormattedDate(archived_at)}</span>
+ </div>
+ )}
+ {isContentEditable && envConfig?.has_openai_configured && (
+ <GptAssistantPopover
+ isOpen={gptModalOpen}
+ projectId={projectId}
+ handleClose={() => {
+ setGptModal((prevData) => !prevData);
+ // this is done so that the title do not reset after gpt popover closed
+ // reset(getValues());
+ }}
+ onResponse={handleAiAssistance}
+ placement="top-end"
+ button={
+ <button
+ type="button"
+ className="flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
+ onClick={() => setGptModal((prevData) => !prevData)}
+ >
+ <Sparkle className="h-4 w-4" />
+ AI
+ </button>
+ }
+ className="!min-w-[38rem]"
+ />
+ )}
+ <PageInfoPopover pageStore={pageStore} />
+ <PageOptionsDropdown
+ editorRef={isContentEditable ? editorRef.current : readOnlyEditorRef.current}
+ handleDuplicatePage={handleDuplicatePage}
+ pageStore={pageStore}
+ />
+ </div>
+ );
+});
diff --git a/web/components/pages/editor/header/index.ts b/web/components/pages/editor/header/index.ts
new file mode 100644
index 0000000000..8c43b2730d
--- /dev/null
+++ b/web/components/pages/editor/header/index.ts
@@ -0,0 +1,5 @@
+export * from "./extra-options";
+export * from "./info-popover";
+export * from "./options-dropdown";
+export * from "./root";
+export * from "./toolbar";
diff --git a/packages/editor/document-editor/src/ui/components/info-popover.tsx b/web/components/pages/editor/header/info-popover.tsx
similarity index 67%
rename from packages/editor/document-editor/src/ui/components/info-popover.tsx
rename to web/components/pages/editor/header/info-popover.tsx
index 16a3452a66..55b4b28fb7 100644
--- a/packages/editor/document-editor/src/ui/components/info-popover.tsx
+++ b/web/components/pages/editor/header/info-popover.tsx
@@ -1,42 +1,28 @@
import { useState } from "react";
import { usePopper } from "react-popper";
import { Calendar, History, Info } from "lucide-react";
-// types
-import { DocumentDetails } from "src/types/editor-types";
-//utils
-import { getDate } from "src/utils/date-utils";
+// helpers
+import { renderFormattedDate } from "@/helpers/date-time.helper";
+// store
+import { IPageStore } from "@/store/pages/page.store";
type Props = {
- documentDetails: DocumentDetails;
+ pageStore: IPageStore;
};
-// function to render a Date in the format- 25 May 2023 at 2:53PM
-const renderDate = (date: Date | undefined): string => {
- const options: Intl.DateTimeFormatOptions = {
- day: "numeric",
- month: "long",
- year: "numeric",
- hour: "numeric",
- minute: "numeric",
- hour12: true,
- };
-
- const formattedDate: string = new Intl.DateTimeFormat("en-US", options).format(date);
-
- return formattedDate;
-};
-
-export const InfoPopover: React.FC<Props> = (props) => {
- const { documentDetails } = props;
-
+export const PageInfoPopover: React.FC<Props> = (props) => {
+ const { pageStore } = props;
+ // states
const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false);
-
+ // refs
const [referenceElement, setReferenceElement] = useState<HTMLButtonElement | null>(null);
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(null);
-
+ // popper-js
const { styles: infoPopoverStyles, attributes: infoPopoverAttributes } = usePopper(referenceElement, popperElement, {
placement: "bottom-start",
});
+ // derived values
+ const { created_at, updated_at } = pageStore;
return (
<div onMouseEnter={() => setIsPopoverOpen(true)} onMouseLeave={() => setIsPopoverOpen(false)}>
@@ -54,14 +40,14 @@ export const InfoPopover: React.FC<Props> = (props) => {
<h6 className="text-xs text-custom-text-400">Last updated on</h6>
<h5 className="flex items-center gap-1 text-sm">
<History className="h-3 w-3" />
- {renderDate(getDate(documentDetails?.last_updated_at))}
+ {renderFormattedDate(updated_at)}
</h5>
</div>
<div className="space-y-1.5">
<h6 className="text-xs text-custom-text-400">Created on</h6>
<h5 className="flex items-center gap-1 text-sm">
<Calendar className="h-3 w-3" />
- {renderDate(getDate(documentDetails?.created_on))}
+ {renderFormattedDate(created_at)}
</h5>
</div>
</div>
diff --git a/web/components/pages/editor/header/options-dropdown.tsx b/web/components/pages/editor/header/options-dropdown.tsx
new file mode 100644
index 0000000000..53bfc43b50
--- /dev/null
+++ b/web/components/pages/editor/header/options-dropdown.tsx
@@ -0,0 +1,175 @@
+import { observer } from "mobx-react";
+import { Clipboard, Copy, Link, Lock } from "lucide-react";
+// document editor
+import { EditorReadOnlyRefApi, EditorRefApi } from "@plane/document-editor";
+// ui
+import { ArchiveIcon, CustomMenu, TOAST_TYPE, ToggleSwitch, setToast } from "@plane/ui";
+// helpers
+import { copyTextToClipboard, copyUrlToClipboard } from "@/helpers/string.helper";
+// hooks
+import { useApplication } from "@/hooks/store";
+// store
+import { IPageStore } from "@/store/pages/page.store";
+
+type Props = {
+ editorRef: EditorRefApi | EditorReadOnlyRefApi | null;
+ handleDuplicatePage: () => void;
+ pageStore: IPageStore;
+};
+
+export const PageOptionsDropdown: React.FC<Props> = observer((props) => {
+ const { editorRef, handleDuplicatePage, pageStore } = props;
+ // store values
+ const {
+ archive,
+ lock,
+ unlock,
+ canCurrentUserArchivePage,
+ canCurrentUserDuplicatePage,
+ canCurrentUserLockPage,
+ restore,
+ view_props,
+ updateViewProps,
+ } = pageStore;
+ // store hooks
+ const {
+ router: { workspaceSlug, projectId },
+ } = useApplication();
+
+ const handleArchivePage = async () =>
+ await archive().catch(() =>
+ setToast({
+ type: TOAST_TYPE.ERROR,
+ title: "Error!",
+ message: "Page could not be archived. Please try again later.",
+ })
+ );
+
+ const handleRestorePage = async () =>
+ await restore().catch(() =>
+ setToast({
+ type: TOAST_TYPE.ERROR,
+ title: "Error!",
+ message: "Page could not be restored. Please try again later.",
+ })
+ );
+
+ const handleLockPage = async () =>
+ await lock().catch(() =>
+ setToast({
+ type: TOAST_TYPE.ERROR,
+ title: "Error!",
+ message: "Page could not be locked. Please try again later.",
+ })
+ );
+
+ const handleUnlockPage = async () =>
+ await unlock().catch(() =>
+ setToast({
+ type: TOAST_TYPE.ERROR,
+ title: "Error!",
+ message: "Page could not be unlocked. Please try again later.",
+ })
+ );
+
+ // menu items list
+ const MENU_ITEMS: {
+ key: string;
+ action: () => void;
+ label: string;
+ icon: React.FC<any>;
+ shouldRender: boolean;
+ }[] = [
+ {
+ key: "copy-markdown",
+ action: () => {
+ if (!editorRef) return;
+ copyTextToClipboard(editorRef.getMarkDown()).then(() =>
+ setToast({
+ type: TOAST_TYPE.SUCCESS,
+ title: "Successful!",
+ message: "Markdown copied to clipboard.",
+ })
+ );
+ },
+ label: "Copy markdown",
+ icon: Clipboard,
+ shouldRender: true,
+ },
+ {
+ key: "copy-page-link",
+ action: () => {
+ copyUrlToClipboard(`${workspaceSlug}/projects/${projectId}/pages/${pageStore.id}`).then(() =>
+ setToast({
+ type: TOAST_TYPE.SUCCESS,
+ title: "Successful!",
+ message: "Page link copied to clipboard.",
+ })
+ );
+ },
+ label: "Copy page link",
+ icon: Link,
+ shouldRender: true,
+ },
+ {
+ key: "make-a-copy",
+ action: handleDuplicatePage,
+ label: "Make a copy",
+ icon: Copy,
+ shouldRender: canCurrentUserDuplicatePage,
+ },
+ {
+ key: "lock-page",
+ action: handleLockPage,
+ label: "Lock page",
+ icon: Lock,
+ shouldRender: !pageStore.is_locked && canCurrentUserLockPage,
+ },
+ {
+ key: "unlock-page",
+ action: handleUnlockPage,
+ label: "Unlock page",
+ icon: Lock,
+ shouldRender: pageStore.is_locked && canCurrentUserLockPage,
+ },
+ {
+ key: "archive-page",
+ action: handleArchivePage,
+ label: "Archive page",
+ icon: ArchiveIcon,
+ shouldRender: !pageStore.archived_at && canCurrentUserArchivePage,
+ },
+ {
+ key: "restore-page",
+ action: handleRestorePage,
+ label: "Restore page",
+ icon: ArchiveIcon,
+ shouldRender: !!pageStore.archived_at && canCurrentUserArchivePage,
+ },
+ ];
+
+ return (
+ <CustomMenu maxHeight="md" placement="bottom-start" verticalEllipsis closeOnSelect>
+ <CustomMenu.MenuItem
+ className="flex w-full items-center justify-between gap-2"
+ onClick={() =>
+ updateViewProps({
+ full_width: !view_props?.full_width,
+ })
+ }
+ >
+ Full width
+ <ToggleSwitch value={!!view_props?.full_width} onChange={() => {}} />
+ </CustomMenu.MenuItem>
+ {MENU_ITEMS.map((item) => {
+ if (!item.shouldRender) return null;
+ return (
+ <CustomMenu.MenuItem key={item.key} onClick={item.action} className="flex items-center gap-2">
+ <item.icon className="h-3 w-3" />
+ <div className="text-custom-text-300">{item.label}</div>
+ </CustomMenu.MenuItem>
+ );
+ })}
+ </CustomMenu>
+ );
+});
diff --git a/web/components/pages/editor/header/root.tsx b/web/components/pages/editor/header/root.tsx
new file mode 100644
index 0000000000..b3bae94bab
--- /dev/null
+++ b/web/components/pages/editor/header/root.tsx
@@ -0,0 +1,70 @@
+import { observer } from "mobx-react";
+import { EditorReadOnlyRefApi, EditorRefApi, IMarking } from "@plane/document-editor";
+// components
+import { PageExtraOptions, PageSummaryPopover, PageToolbar } from "@/components/pages";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// store
+import { IPageStore } from "@/store/pages/page.store";
+
+type Props = {
+ editorRef: React.RefObject<EditorRefApi>;
+ readOnlyEditorRef: React.RefObject<EditorReadOnlyRefApi>;
+ handleDuplicatePage: () => void;
+ markings: IMarking[];
+ pageStore: IPageStore;
+ projectId: string;
+ sidePeekVisible: boolean;
+ setSidePeekVisible: (sidePeekState: boolean) => void;
+ editorReady: boolean;
+ readOnlyEditorReady: boolean;
+};
+
+export const PageEditorHeaderRoot: React.FC<Props> = observer((props) => {
+ const {
+ editorRef,
+ readOnlyEditorRef,
+ editorReady,
+ markings,
+ readOnlyEditorReady,
+ handleDuplicatePage,
+ pageStore,
+ projectId,
+ sidePeekVisible,
+ setSidePeekVisible,
+ } = props;
+ // derived values
+ const { isContentEditable, view_props } = pageStore;
+ const isFullWidth = !!view_props?.full_width;
+
+ if (!editorRef.current && !readOnlyEditorRef.current) return null;
+
+ return (
+ <div className="flex items-center border-b border-custom-border-200 px-3 py-2 md:px-5">
+ <div
+ className={cn("flex-shrink-0", {
+ "w-56 lg:w-72": !isFullWidth,
+ "w-[10%]": isFullWidth,
+ })}
+ >
+ <PageSummaryPopover
+ editorRef={isContentEditable ? editorRef.current : readOnlyEditorRef.current}
+ isFullWidth={isFullWidth}
+ markings={markings}
+ sidePeekVisible={sidePeekVisible}
+ setSidePeekVisible={setSidePeekVisible}
+ />
+ </div>
+ {(editorReady || readOnlyEditorReady) && isContentEditable && editorRef.current && (
+ <PageToolbar editorRef={editorRef?.current} />
+ )}
+ <PageExtraOptions
+ editorRef={editorRef}
+ handleDuplicatePage={handleDuplicatePage}
+ pageStore={pageStore}
+ projectId={projectId}
+ readOnlyEditorRef={readOnlyEditorRef}
+ />
+ </div>
+ );
+});
diff --git a/web/components/pages/editor/header/toolbar.tsx b/web/components/pages/editor/header/toolbar.tsx
new file mode 100644
index 0000000000..a23d57e770
--- /dev/null
+++ b/web/components/pages/editor/header/toolbar.tsx
@@ -0,0 +1,90 @@
+import React, { useEffect, useState, useCallback } from "react";
+// editor
+import { EditorMenuItemNames, EditorRefApi } from "@plane/document-editor";
+// ui
+import { Tooltip } from "@plane/ui";
+// constants
+import { TOOLBAR_ITEMS, ToolbarMenuItem } from "@/constants/editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
+
+type Props = {
+ editorRef: EditorRefApi;
+};
+
+type ToolbarButtonProps = {
+ item: ToolbarMenuItem;
+ isActive: boolean;
+ executeCommand: (commandName: EditorMenuItemNames) => void;
+};
+
+const ToolbarButton: React.FC<ToolbarButtonProps> = React.memo((props) => {
+ const { item, isActive, executeCommand } = props;
+
+ return (
+ <Tooltip
+ tooltipContent={
+ <p className="flex flex-col gap-1 text-center text-xs">
+ <span className="font-medium">{item.name}</span>
+ {item.shortcut && <kbd className="text-custom-text-400">{item.shortcut.join(" + ")}</kbd>}
+ </p>
+ }
+ >
+ <button
+ key={item.key}
+ type="button"
+ onClick={() => executeCommand(item.key)}
+ className={cn("grid h-7 w-7 place-items-center rounded text-custom-text-300 hover:bg-custom-background-80", {
+ "bg-custom-background-80 text-custom-text-100": isActive,
+ })}
+ >
+ <item.icon
+ className={cn("h-4 w-4", {
+ "text-custom-text-100": isActive,
+ })}
+ />
+ </button>
+ </Tooltip>
+ );
+});
+
+ToolbarButton.displayName = "ToolbarButton";
+
+const toolbarItems = TOOLBAR_ITEMS.document;
+
+export const PageToolbar: React.FC<Props> = ({ editorRef }) => {
+ const [activeStates, setActiveStates] = useState<Record<string, boolean>>({});
+
+ const updateActiveStates = useCallback(() => {
+ const newActiveStates: Record<string, boolean> = {};
+ Object.values(toolbarItems)
+ .flat()
+ .forEach((item) => {
+ newActiveStates[item.key] = editorRef.isMenuItemActive(item.key);
+ });
+ setActiveStates(newActiveStates);
+ }, [editorRef]);
+
+ useEffect(() => {
+ const unsubscribe = editorRef.onStateChange(updateActiveStates);
+ updateActiveStates();
+ return () => unsubscribe();
+ }, [editorRef, updateActiveStates]);
+
+ return (
+ <div className="flex flex-wrap items-center divide-x divide-custom-border-200">
+ {Object.keys(toolbarItems).map((key) => (
+ <div key={key} className="flex items-center gap-0.5 px-2 first:pl-0 last:pr-0">
+ {toolbarItems[key].map((item) => (
+ <ToolbarButton
+ key={item.key}
+ item={item}
+ isActive={activeStates[item.key]}
+ executeCommand={editorRef.executeMenuItemCommand}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ );
+};
diff --git a/web/components/pages/editor/index.ts b/web/components/pages/editor/index.ts
new file mode 100644
index 0000000000..0ed58726f4
--- /dev/null
+++ b/web/components/pages/editor/index.ts
@@ -0,0 +1,4 @@
+export * from "./header";
+export * from "./summary";
+export * from "./editor-body";
+export * from "./title";
diff --git a/web/components/pages/editor/summary/content-browser.tsx b/web/components/pages/editor/summary/content-browser.tsx
new file mode 100644
index 0000000000..c5519eb185
--- /dev/null
+++ b/web/components/pages/editor/summary/content-browser.tsx
@@ -0,0 +1,49 @@
+// types
+import { EditorReadOnlyRefApi, EditorRefApi, IMarking } from "@plane/document-editor";
+import { OutlineHeading1, OutlineHeading2, OutlineHeading3 } from "./heading-components";
+
+type Props = {
+ editorRef: EditorRefApi | EditorReadOnlyRefApi | null;
+ markings: IMarking[];
+ setSidePeekVisible?: (sidePeekState: boolean) => void;
+};
+
+export const PageContentBrowser: React.FC<Props> = (props) => {
+ const { editorRef, markings, setSidePeekVisible } = props;
+
+ const handleOnClick = (marking: IMarking) => {
+ editorRef?.scrollSummary(marking);
+ if (setSidePeekVisible) setSidePeekVisible(false);
+ };
+
+ const HeadingComponent: {
+ [key: number]: React.FC<{ marking: IMarking; onClick: () => void }>;
+ } = {
+ 1: OutlineHeading1,
+ 2: OutlineHeading2,
+ 3: OutlineHeading3,
+ };
+
+ return (
+ <div className="h-full flex flex-col overflow-hidden">
+ <h2 className="font-medium">Outline</h2>
+ <div className="h-full flex flex-col items-start gap-y-2 overflow-y-auto mt-2">
+ {markings.length !== 0 ? (
+ markings.map((marking) => {
+ const Component = HeadingComponent[marking.level];
+ if (!Component) return null;
+ return (
+ <Component
+ key={`${marking.level}-${marking.sequence}`}
+ marking={marking}
+ onClick={() => handleOnClick(marking)}
+ />
+ );
+ })
+ ) : (
+ <p className="mt-3 text-xs text-custom-text-400">Headings will be displayed here for navigation</p>
+ )}
+ </div>
+ </div>
+ );
+};
diff --git a/web/components/pages/editor/summary/heading-components.tsx b/web/components/pages/editor/summary/heading-components.tsx
new file mode 100644
index 0000000000..a8eade6fc7
--- /dev/null
+++ b/web/components/pages/editor/summary/heading-components.tsx
@@ -0,0 +1,37 @@
+// document editor
+import { IMarking } from "@plane/document-editor";
+
+type HeadingProps = {
+ marking: IMarking;
+ onClick: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
+};
+
+export const OutlineHeading1 = ({ marking, onClick }: HeadingProps) => (
+ <button
+ type="button"
+ onClick={onClick}
+ className="ml-4 cursor-pointer text-sm font-medium text-custom-text-400 hover:text-custom-primary-100 max-md:ml-2.5"
+ >
+ {marking.text}
+ </button>
+);
+
+export const OutlineHeading2 = ({ marking, onClick }: HeadingProps) => (
+ <button
+ type="button"
+ onClick={onClick}
+ className="ml-6 cursor-pointer text-xs font-medium text-custom-text-400 hover:text-custom-primary-100"
+ >
+ {marking.text}
+ </button>
+);
+
+export const OutlineHeading3 = ({ marking, onClick }: HeadingProps) => (
+ <button
+ type="button"
+ onClick={onClick}
+ className="ml-8 cursor-pointer text-xs font-medium text-custom-text-400 hover:text-custom-primary-100"
+ >
+ {marking.text}
+ </button>
+);
diff --git a/web/components/pages/editor/summary/index.ts b/web/components/pages/editor/summary/index.ts
new file mode 100644
index 0000000000..3c4afb4d8a
--- /dev/null
+++ b/web/components/pages/editor/summary/index.ts
@@ -0,0 +1,2 @@
+export * from "./content-browser";
+export * from "./popover";
diff --git a/packages/editor/document-editor/src/ui/components/summary-popover.tsx b/web/components/pages/editor/summary/popover.tsx
similarity index 71%
rename from packages/editor/document-editor/src/ui/components/summary-popover.tsx
rename to web/components/pages/editor/summary/popover.tsx
index 41056c6ad2..4f9654c96e 100644
--- a/packages/editor/document-editor/src/ui/components/summary-popover.tsx
+++ b/web/components/pages/editor/summary/popover.tsx
@@ -1,25 +1,27 @@
import { useState } from "react";
-import { Editor } from "@tiptap/react";
import { usePopper } from "react-popper";
import { List } from "lucide-react";
+// document editor
+import { EditorReadOnlyRefApi, EditorRefApi, IMarking } from "@plane/document-editor";
+// helpers
+import { cn } from "@/helpers/common.helper";
// components
-import { ContentBrowser } from "src/ui/components/content-browser";
-// types
-import { IMarking } from "src/types/editor-types";
+import { PageContentBrowser } from "./content-browser";
type Props = {
- editor: Editor;
+ editorRef: EditorRefApi | EditorReadOnlyRefApi | null;
+ isFullWidth: boolean;
markings: IMarking[];
sidePeekVisible: boolean;
setSidePeekVisible: (sidePeekState: boolean) => void;
};
-export const SummaryPopover: React.FC<Props> = (props) => {
- const { editor, markings, sidePeekVisible, setSidePeekVisible } = props;
-
+export const PageSummaryPopover: React.FC<Props> = (props) => {
+ const { editorRef, markings, sidePeekVisible, setSidePeekVisible } = props;
+ // refs
const [referenceElement, setReferenceElement] = useState<HTMLButtonElement | null>(null);
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(null);
-
+ // popper-js
const { styles: summaryPopoverStyles, attributes: summaryPopoverAttributes } = usePopper(
referenceElement,
popperElement,
@@ -40,7 +42,11 @@ export const SummaryPopover: React.FC<Props> = (props) => {
>
<List className="h-4 w-4" />
</button>
- <div className="md:hidden block">
+ <div
+ className={cn("block md:hidden", {
+ // "md:hidden": !isFullWidth,
+ })}
+ >
{sidePeekVisible && (
<div
className="z-10 max-h-80 w-64 overflow-y-auto rounded border-[0.5px] border-custom-border-200 bg-custom-background-100 p-3 shadow-custom-shadow-rg"
@@ -48,7 +54,7 @@ export const SummaryPopover: React.FC<Props> = (props) => {
style={summaryPopoverStyles.popper}
{...summaryPopoverAttributes.popper}
>
- <ContentBrowser setSidePeekVisible={setSidePeekVisible} editor={editor} markings={markings} />
+ <PageContentBrowser setSidePeekVisible={setSidePeekVisible} editorRef={editorRef} markings={markings} />
</div>
)}
</div>
@@ -60,7 +66,7 @@ export const SummaryPopover: React.FC<Props> = (props) => {
style={summaryPopoverStyles.popper}
{...summaryPopoverAttributes.popper}
>
- <ContentBrowser editor={editor} markings={markings} />
+ <PageContentBrowser editorRef={editorRef} markings={markings} />
</div>
)}
</div>
diff --git a/web/components/pages/editor/title.tsx b/web/components/pages/editor/title.tsx
new file mode 100644
index 0000000000..8b329e53a4
--- /dev/null
+++ b/web/components/pages/editor/title.tsx
@@ -0,0 +1,40 @@
+import { observer } from "mobx-react";
+// editor
+import { EditorRefApi } from "@plane/document-editor";
+// ui
+import { TextArea } from "@plane/ui";
+
+type Props = {
+ editorRef: React.RefObject<EditorRefApi>;
+ readOnly: boolean;
+ title: string;
+ updateTitle: (title: string) => void;
+};
+
+export const PageEditorTitle: React.FC<Props> = observer((props) => {
+ const { editorRef, readOnly, title, updateTitle } = props;
+
+ return (
+ <>
+ {readOnly ? (
+ <h6 className="-mt-2 break-words bg-transparent text-4xl font-bold">{title}</h6>
+ ) : (
+ <TextArea
+ onChange={(e) => updateTitle(e.target.value)}
+ className="-mt-2 w-full bg-custom-background text-4xl font-bold outline-none p-0 border-none resize-none rounded-none"
+ style={{
+ lineHeight: "1.2",
+ }}
+ placeholder="Untitled Page"
+ onKeyDown={(e) => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ editorRef.current?.setFocusAtPosition(0);
+ }
+ }}
+ value={title}
+ />
+ )}
+ </>
+ );
+});
diff --git a/web/components/pages/header/index.ts b/web/components/pages/header/index.ts
new file mode 100644
index 0000000000..1efe34c51e
--- /dev/null
+++ b/web/components/pages/header/index.ts
@@ -0,0 +1 @@
+export * from "./root";
diff --git a/web/components/pages/header/root.tsx b/web/components/pages/header/root.tsx
new file mode 100644
index 0000000000..964209e415
--- /dev/null
+++ b/web/components/pages/header/root.tsx
@@ -0,0 +1,85 @@
+import { useCallback } from "react";
+import { observer } from "mobx-react";
+import { ListFilter } from "lucide-react";
+import { TPageFilterProps, TPageNavigationTabs } from "@plane/types";
+// components
+import { FiltersDropdown } from "@/components/issues";
+import {
+ PageAppliedFiltersList,
+ PageFiltersSelection,
+ PageOrderByDropdown,
+ PageSearchInput,
+ PageTabNavigation,
+} from "@/components/pages";
+// helpers
+import { calculateTotalFilters } from "@/helpers/filter.helper";
+// hooks
+import { useLabel, useMember, useProjectPages } from "@/hooks/store";
+
+type Props = {
+ pageType: TPageNavigationTabs;
+ projectId: string;
+ workspaceSlug: string;
+};
+
+export const PagesListHeaderRoot: React.FC<Props> = observer((props) => {
+ const { pageType, projectId, workspaceSlug } = props;
+ // store hooks
+ const { filters, updateFilters, clearAllFilters } = useProjectPages(projectId);
+ const {
+ workspace: { workspaceMemberIds },
+ } = useMember();
+ const { projectLabels } = useLabel();
+
+ const handleRemoveFilter = useCallback(
+ (key: keyof TPageFilterProps, value: string | null) => {
+ let newValues = filters.filters?.[key];
+
+ if (key === "favorites") newValues = !!value;
+ if (Array.isArray(newValues)) {
+ if (!value) newValues = [];
+ else newValues = newValues.filter((val) => val !== value);
+ }
+
+ updateFilters("filters", { [key]: newValues });
+ },
+ [filters.filters, updateFilters]
+ );
+
+ return (
+ <>
+ <div className="flex-shrink-0 w-full border-b border-custom-border-200 px-3 relative flex items-center gap-4 justify-between">
+ <PageTabNavigation workspaceSlug={workspaceSlug} projectId={projectId} pageType={pageType} />
+ <div className="h-full flex items-center gap-2 self-end">
+ <PageSearchInput projectId={projectId} />
+ <PageOrderByDropdown
+ sortBy={filters.sortBy}
+ sortKey={filters.sortKey}
+ onChange={(val) => {
+ if (val.key) updateFilters("sortKey", val.key);
+ if (val.order) updateFilters("sortBy", val.order);
+ }}
+ />
+ <FiltersDropdown icon={<ListFilter className="h-3 w-3" />} title="Filters" placement="bottom-end">
+ <PageFiltersSelection
+ filters={filters}
+ handleFiltersUpdate={updateFilters}
+ labels={projectLabels}
+ memberIds={workspaceMemberIds ?? undefined}
+ />
+ </FiltersDropdown>
+ </div>
+ </div>
+ {calculateTotalFilters(filters?.filters ?? {}) !== 0 && (
+ <div className="border-b border-custom-border-200 px-5 py-3">
+ <PageAppliedFiltersList
+ appliedFilters={filters.filters ?? {}}
+ handleClearAllFilters={clearAllFilters}
+ handleRemoveFilter={handleRemoveFilter}
+ alwaysAllowEditing
+ />
+ </div>
+ )}
+ </>
+ );
+});
diff --git a/web/components/pages/index.ts b/web/components/pages/index.ts
index c24b78ff57..58926da2c5 100644
--- a/web/components/pages/index.ts
+++ b/web/components/pages/index.ts
@@ -1,4 +1,9 @@
-export * from "./pages-list";
-export * from "./create-update-page-modal";
-export * from "./delete-page-modal";
-export * from "./page-form";
+export * from "./dropdowns";
+export * from "./editor";
+export * from "./header";
+export * from "./list";
+export * from "./loaders";
+export * from "./modals";
+export * from "./page-detail";
+export * from "./pages-list-main-content";
+export * from "./pages-list-view";
diff --git a/web/components/pages/list/applied-filters/date.tsx b/web/components/pages/list/applied-filters/date.tsx
new file mode 100644
index 0000000000..3c1cb2dc0d
--- /dev/null
+++ b/web/components/pages/list/applied-filters/date.tsx
@@ -0,0 +1,56 @@
+import { observer } from "mobx-react-lite";
+// icons
+import { X } from "lucide-react";
+// helpers
+import { DATE_BEFORE_FILTER_OPTIONS } from "@/constants/filters";
+import { renderFormattedDate } from "@/helpers/date-time.helper";
+import { capitalizeFirstLetter } from "@/helpers/string.helper";
+// constants
+
+type Props = {
+ editable: boolean | undefined;
+ handleRemove: (val: string) => void;
+ values: string[];
+};
+
+export const AppliedDateFilters: React.FC<Props> = observer((props) => {
+ const { editable, handleRemove, values } = props;
+
+ const getDateLabel = (value: string): string => {
+ let dateLabel = "";
+
+ const dateDetails = DATE_BEFORE_FILTER_OPTIONS.find((d) => d.value === value);
+
+ if (dateDetails) dateLabel = dateDetails.name;
+ else {
+ const dateParts = value.split(";");
+
+ if (dateParts.length === 2) {
+ const [date, time] = dateParts;
+
+ dateLabel = `${capitalizeFirstLetter(time)} ${renderFormattedDate(date)}`;
+ }
+ }
+
+ return dateLabel;
+ };
+
+ return (
+ <>
+ {values.map((date) => (
+ <div key={date} className="flex items-center gap-1 rounded bg-custom-background-80 p-1 text-xs">
+ <span className="normal-case">{getDateLabel(date)}</span>
+ {editable && (
+ <button
+ type="button"
+ className="grid place-items-center text-custom-text-300 hover:text-custom-text-200"
+ onClick={() => handleRemove(date)}
+ >
+ <X size={10} strokeWidth={2} />
+ </button>
+ )}
+ </div>
+ ))}
+ </>
+ );
+});
diff --git a/web/components/pages/list/applied-filters/index.ts b/web/components/pages/list/applied-filters/index.ts
new file mode 100644
index 0000000000..687cffb998
--- /dev/null
+++ b/web/components/pages/list/applied-filters/index.ts
@@ -0,0 +1,3 @@
+export * from "./date";
+export * from "./members";
+export * from "./root";
diff --git a/web/components/pages/list/applied-filters/members.tsx b/web/components/pages/list/applied-filters/members.tsx
new file mode 100644
index 0000000000..9c8ecb4f85
--- /dev/null
+++ b/web/components/pages/list/applied-filters/members.tsx
@@ -0,0 +1,46 @@
+import { observer } from "mobx-react-lite";
+import { X } from "lucide-react";
+// ui
+import { Avatar } from "@plane/ui";
+// types
+import { useMember } from "@/hooks/store";
+
+type Props = {
+ handleRemove: (val: string) => void;
+ values: string[];
+ editable: boolean | undefined;
+};
+
+export const AppliedMembersFilters: React.FC<Props> = observer((props) => {
+ const { handleRemove, values, editable } = props;
+ // store hooks
+ const {
+ workspace: { getWorkspaceMemberDetails },
+ } = useMember();
+
+ return (
+ <>
+ {values.map((memberId) => {
+ const memberDetails = getWorkspaceMemberDetails(memberId)?.member;
+
+ if (!memberDetails) return null;
+
+ return (
+ <div key={memberId} className="flex items-center gap-1 rounded bg-custom-background-80 p-1 text-xs">
+ <Avatar name={memberDetails.display_name} src={memberDetails.avatar} showTooltip={false} />
+ <span className="normal-case">{memberDetails.display_name}</span>
+ {editable && (
+ <button
+ type="button"
+ className="grid place-items-center text-custom-text-300 hover:text-custom-text-200"
+ onClick={() => handleRemove(memberId)}
+ >
+ <X size={10} strokeWidth={2} />
+ </button>
+ )}
+ </div>
+ );
+ })}
+ </>
+ );
+});
diff --git a/web/components/pages/list/applied-filters/root.tsx b/web/components/pages/list/applied-filters/root.tsx
new file mode 100644
index 0000000000..f889739ccc
--- /dev/null
+++ b/web/components/pages/list/applied-filters/root.tsx
@@ -0,0 +1,81 @@
+import { X } from "lucide-react";
+import { TPageFilterProps } from "@plane/types";
+// components
+import { AppliedDateFilters, AppliedMembersFilters } from "@/components/pages";
+// helpers
+import { replaceUnderscoreIfSnakeCase } from "@/helpers/string.helper";
+// types
+
+type Props = {
+ appliedFilters: TPageFilterProps;
+ handleClearAllFilters: () => void;
+ handleRemoveFilter: (key: keyof TPageFilterProps, value: string | null) => void;
+ alwaysAllowEditing?: boolean;
+};
+
+const MEMBERS_FILTERS = ["created_by"];
+const DATE_FILTERS = ["created_at"];
+
+export const PageAppliedFiltersList: React.FC<Props> = (props) => {
+ const { appliedFilters, handleClearAllFilters, handleRemoveFilter, alwaysAllowEditing } = props;
+
+ if (!appliedFilters) return null;
+ if (Object.keys(appliedFilters).length === 0) return null;
+
+ const isEditingAllowed = alwaysAllowEditing;
+
+ return (
+ <div className="flex flex-wrap items-stretch gap-2 bg-custom-background-100">
+ {Object.entries(appliedFilters).map(([key, value]) => {
+ const filterKey = key as keyof TPageFilterProps;
+
+ if (!value) return;
+ if (Array.isArray(value) && value.length === 0) return;
+
+ return (
+ <div
+ key={filterKey}
+ className="flex flex-wrap items-center gap-2 rounded-md border border-custom-border-200 px-2 py-1 capitalize"
+ >
+ <div className="flex flex-wrap items-center gap-1.5">
+ <span className="text-xs text-custom-text-300">{replaceUnderscoreIfSnakeCase(filterKey)}</span>
+ {DATE_FILTERS.includes(filterKey) && (
+ <AppliedDateFilters
+ editable={isEditingAllowed}
+ handleRemove={(val) => handleRemoveFilter(filterKey, val)}
+ values={Array.isArray(value) ? value : []}
+ />
+ )}
+ {MEMBERS_FILTERS.includes(filterKey) && (
+ <AppliedMembersFilters
+ editable={isEditingAllowed}
+ handleRemove={(val) => handleRemoveFilter(filterKey, val)}
+ values={Array.isArray(value) ? value : []}
+ />
+ )}
+ {isEditingAllowed && (
+ <button
+ type="button"
+ className="grid place-items-center text-custom-text-300 hover:text-custom-text-200"
+ onClick={() => handleRemoveFilter(filterKey, null)}
+ >
+ <X size={12} strokeWidth={2} />
+ </button>
+ )}
+ </div>
+ </div>
+ );
+ })}
+ {isEditingAllowed && (
+ <button
+ type="button"
+ onClick={handleClearAllFilters}
+ className="flex items-center gap-2 rounded-md border border-custom-border-200 px-2 py-1 text-xs text-custom-text-300 hover:text-custom-text-200"
+ >
+ Clear all
+ <X size={12} strokeWidth={2} />
+ </button>
+ )}
+ </div>
+ );
+};
diff --git a/web/components/pages/list/block.tsx b/web/components/pages/list/block.tsx
new file mode 100644
index 0000000000..6b20fb49df
--- /dev/null
+++ b/web/components/pages/list/block.tsx
@@ -0,0 +1,110 @@
+import { FC } from "react";
+import { observer } from "mobx-react";
+import Link from "next/link";
+import { Circle, Info, Lock, Minus, Star, UsersRound } from "lucide-react";
+import { Avatar, TOAST_TYPE, Tooltip, setToast } from "@plane/ui";
+// components
+import { PageQuickActions } from "@/components/pages";
+// helpers
+import { cn } from "@/helpers/common.helper";
+import { renderFormattedDate } from "@/helpers/date-time.helper";
+// hooks
+import { useMember, usePage } from "@/hooks/store";
+
+type TPageListBlock = {
+ workspaceSlug: string;
+ projectId: string;
+ pageId: string;
+};
+
+export const PageListBlock: FC<TPageListBlock> = observer((props) => {
+ const { workspaceSlug, projectId, pageId } = props;
+ // hooks
+ const { access, created_at, is_favorite, name, owned_by, addToFavorites, removeFromFavorites } = usePage(pageId);
+ const { getUserDetails } = useMember();
+ // derived values
+ const ownerDetails = owned_by ? getUserDetails(owned_by) : undefined;
+
+ const handleFavorites = () => {
+ if (is_favorite)
+ removeFromFavorites().then(() =>
+ setToast({
+ type: TOAST_TYPE.SUCCESS,
+ title: "Success!",
+ message: "Page removed from favorites.",
+ })
+ );
+ else
+ addToFavorites().then(() =>
+ setToast({
+ type: TOAST_TYPE.SUCCESS,
+ title: "Success!",
+ message: "Page added to favorites.",
+ })
+ );
+ };
+
+ return (
+ <Link
+ href={`/${workspaceSlug}/projects/${projectId}/pages/${pageId}`}
+ className="flex items-center justify-between gap-5 py-7 px-6 hover:bg-custom-background-90"
+ >
+ {/* page title */}
+ <Tooltip tooltipHeading="Title" tooltipContent={name}>
+ <h5 className="text-base font-semibold truncate">{name}</h5>
+ </Tooltip>
+
+ {/* page properties */}
+ <div className="flex items-center gap-5 flex-shrink-0">
+ {/* page details */}
+ <div className="flex items-center gap-2 text-custom-text-400">
+ {/* <span className="text-xs">Labels</span>
+ <Circle className="h-1 w-1 fill-custom-text-300" /> */}
+ <div className="cursor-default">
+ <Tooltip tooltipHeading="Owned by" tooltipContent={ownerDetails?.display_name}>
+ <Avatar src={ownerDetails?.avatar} name={ownerDetails?.display_name} />
+ </Tooltip>
+ </div>
+ <Circle className="h-1 w-1 fill-custom-text-300" />
+ {/* <span className="text-xs cursor-default">10m read</span>
+ <Circle className="h-1 w-1 fill-custom-text-300" /> */}
+ <div className="cursor-default">
+ <Tooltip tooltipContent={access === 0 ? "Public" : "Private"}>
+ {access === 0 ? <UsersRound className="h-3 w-3" /> : <Lock className="h-3 w-3" />}
+ </Tooltip>
+ </div>
+ </div>
+
+ {/* vertical divider */}
+ <Minus className="h-5 w-5 text-custom-text-400 rotate-90 -mx-3" strokeWidth={1} />
+
+ {/* page info */}
+ <Tooltip tooltipContent={`Created on ${renderFormattedDate(created_at)}`}>
+ <span className="h-4 w-4 grid place-items-center cursor-default">
+ <Info className="h-4 w-4 text-custom-text-300" />
+ </span>
+ </Tooltip>
+
+ {/* favorite/unfavorite */}
+ <button
+ type="button"
+ className="h-4 w-4 grid place-items-center"
+ onClick={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ handleFavorites();
+ }}
+ >
+ <Star
+ className={cn("h-4 w-4 text-custom-text-300 transition-all", {
+ "fill-yellow-500 stroke-yellow-500": is_favorite,
+ })}
+ />
+ </button>
+
+ {/* quick actions dropdown */}
+ <PageQuickActions pageId={pageId} projectId={projectId} workspaceSlug={workspaceSlug} />
+ </div>
+ </Link>
+ );
+});
diff --git a/web/components/pages/list/filters/created-at.tsx b/web/components/pages/list/filters/created-at.tsx
new file mode 100644
index 0000000000..5a1b75c00b
--- /dev/null
+++ b/web/components/pages/list/filters/created-at.tsx
@@ -0,0 +1,64 @@
+import React, { useState } from "react";
+import { observer } from "mobx-react-lite";
+// components
+import { DateFilterModal } from "@/components/core";
+import { FilterHeader, FilterOption } from "@/components/issues";
+// constants
+import { DATE_BEFORE_FILTER_OPTIONS } from "@/constants/filters";
+
+type Props = {
+ appliedFilters: string[] | null;
+ handleUpdate: (val: string | string[]) => void;
+ searchQuery: string;
+};
+
+export const FilterCreatedDate: React.FC<Props> = observer((props) => {
+ const { appliedFilters, handleUpdate, searchQuery } = props;
+
+ const [previewEnabled, setPreviewEnabled] = useState(true);
+ const [isDateFilterModalOpen, setIsDateFilterModalOpen] = useState(false);
+
+ const appliedFiltersCount = appliedFilters?.length ?? 0;
+
+ const filteredOptions = DATE_BEFORE_FILTER_OPTIONS.filter((d) =>
+ d.name.toLowerCase().includes(searchQuery.toLowerCase())
+ );
+
+ return (
+ <>
+ {isDateFilterModalOpen && (
+ <DateFilterModal
+ handleClose={() => setIsDateFilterModalOpen(false)}
+ isOpen={isDateFilterModalOpen}
+ onSelect={(val) => handleUpdate(val)}
+ title="Created date"
+ />
+ )}
+ <FilterHeader
+ title={`Created date${appliedFiltersCount > 0 ? ` (${appliedFiltersCount})` : ""}`}
+ isPreviewEnabled={previewEnabled}
+ handleIsPreviewEnabled={() => setPreviewEnabled(!previewEnabled)}
+ />
+ {previewEnabled && (
+ <div>
+ {filteredOptions.length > 0 ? (
+ <>
+ {filteredOptions.map((option) => (
+ <FilterOption
+ key={option.value}
+ isChecked={appliedFilters?.includes(option.value) ? true : false}
+ onClick={() => handleUpdate(option.value)}
+ title={option.name}
+ multiple
+ />
+ ))}
+ <FilterOption isChecked={false} onClick={() => setIsDateFilterModalOpen(true)} title="Custom" multiple />
+ </>
+ ) : (
+ <p className="text-xs italic text-custom-text-400">No matches found</p>
+ )}
+ </div>
+ )}
+ </>
+ );
+});
diff --git a/web/components/pages/list/filters/created-by.tsx b/web/components/pages/list/filters/created-by.tsx
new file mode 100644
index 0000000000..bddacc5504
--- /dev/null
+++ b/web/components/pages/list/filters/created-by.tsx
@@ -0,0 +1,96 @@
+import { useMemo, useState } from "react";
+import sortBy from "lodash/sortBy";
+import { observer } from "mobx-react-lite";
+// ui
+import { Avatar, Loader } from "@plane/ui";
+// components
+import { FilterHeader, FilterOption } from "@/components/issues";
+// hooks
+import { useMember } from "@/hooks/store";
+
+type Props = {
+ appliedFilters: string[] | null;
+ handleUpdate: (val: string) => void;
+ memberIds: string[] | undefined;
+ searchQuery: string;
+};
+
+export const FilterCreatedBy: React.FC<Props> = observer((props: Props) => {
+ const { appliedFilters, handleUpdate, memberIds, searchQuery } = props;
+ // states
+ const [itemsToRender, setItemsToRender] = useState(5);
+ const [previewEnabled, setPreviewEnabled] = useState(true);
+ // store hooks
+ const { getUserDetails } = useMember();
+
+ const appliedFiltersCount = appliedFilters?.length ?? 0;
+
+ const sortedOptions = useMemo(() => {
+ const filteredOptions = (memberIds || []).filter((memberId) =>
+ getUserDetails(memberId)?.display_name.toLowerCase().includes(searchQuery.toLowerCase())
+ );
+
+ return sortBy(filteredOptions, [
+ (memberId) => !(appliedFilters ?? []).includes(memberId),
+ (memberId) => getUserDetails(memberId)?.display_name.toLowerCase(),
+ ]);
+ }, [appliedFilters, getUserDetails, memberIds, searchQuery]);
+
+ const handleViewToggle = () => {
+ if (!sortedOptions) return;
+
+ if (itemsToRender === sortedOptions.length) setItemsToRender(5);
+ else setItemsToRender(sortedOptions.length);
+ };
+
+ return (
+ <>
+ <FilterHeader
+ title={`Created by${appliedFiltersCount > 0 ? ` (${appliedFiltersCount})` : ""}`}
+ isPreviewEnabled={previewEnabled}
+ handleIsPreviewEnabled={() => setPreviewEnabled(!previewEnabled)}
+ />
+ {previewEnabled && (
+ <div>
+ {sortedOptions ? (
+ sortedOptions.length > 0 ? (
+ <>
+ {sortedOptions.slice(0, itemsToRender).map((memberId) => {
+ const member = getUserDetails(memberId);
+
+ if (!member) return null;
+ return (
+ <FilterOption
+ key={`member-${member.id}`}
+ isChecked={appliedFilters?.includes(member.id) ? true : false}
+ onClick={() => handleUpdate(member.id)}
+ icon={<Avatar name={member.display_name} src={member.avatar} showTooltip={false} size="md" />}
+ title={member.display_name}
+ />
+ );
+ })}
+ {sortedOptions.length > 5 && (
+ <button
+ type="button"
+ className="ml-8 text-xs font-medium text-custom-primary-100"
+ onClick={handleViewToggle}
+ >
+ {itemsToRender === sortedOptions.length ? "View less" : "View all"}
+ </button>
+ )}
+ </>
+ ) : (
+ <p className="text-xs italic text-custom-text-400">No matches found</p>
+ )
+ ) : (
+ <Loader className="space-y-2">
+ <Loader.Item height="20px" />
+ <Loader.Item height="20px" />
+ <Loader.Item height="20px" />
+ </Loader>
+ )}
+ </div>
+ )}
+ </>
+ );
+});
diff --git a/web/components/pages/list/filters/index.ts b/web/components/pages/list/filters/index.ts
new file mode 100644
index 0000000000..be7c679b70
--- /dev/null
+++ b/web/components/pages/list/filters/index.ts
@@ -0,0 +1,4 @@
+export * from "./created-at";
+export * from "./created-by";
+export * from "./labels";
+export * from "./root";
diff --git a/web/components/pages/list/filters/labels.tsx b/web/components/pages/list/filters/labels.tsx
new file mode 100644
index 0000000000..9a391ca22a
--- /dev/null
+++ b/web/components/pages/list/filters/labels.tsx
@@ -0,0 +1,93 @@
+import React, { useMemo, useState } from "react";
+import sortBy from "lodash/sortBy";
+import { observer } from "mobx-react";
+// types
+import { IIssueLabel } from "@plane/types";
+// ui
+import { Loader } from "@plane/ui";
+// components
+import { FilterHeader, FilterOption } from "@/components/issues";
+
+const LabelIcons = ({ color }: { color: string }) => (
+ <span className="h-2.5 w-2.5 rounded-full" style={{ backgroundColor: color }} />
+);
+
+type Props = {
+ appliedFilters: string[] | null;
+ handleUpdate: (val: string) => void;
+ labels: IIssueLabel[] | undefined;
+ searchQuery: string;
+};
+
+export const FilterLabels: React.FC<Props> = observer((props) => {
+ const { appliedFilters, handleUpdate, labels, searchQuery } = props;
+
+ const [itemsToRender, setItemsToRender] = useState(5);
+ const [previewEnabled, setPreviewEnabled] = useState(true);
+
+ const appliedFiltersCount = appliedFilters?.length ?? 0;
+
+ const sortedOptions = useMemo(() => {
+ const filteredOptions = (labels || []).filter((label) =>
+ label.name.toLowerCase().includes(searchQuery.toLowerCase())
+ );
+
+ return sortBy(filteredOptions, [
+ (label) => !(appliedFilters ?? []).includes(label.id),
+ (label) => label.name.toLowerCase(),
+ ]);
+ }, [appliedFilters, labels, searchQuery]);
+
+ const handleViewToggle = () => {
+ if (!sortedOptions) return;
+
+ if (itemsToRender === sortedOptions.length) setItemsToRender(5);
+ else setItemsToRender(sortedOptions.length);
+ };
+
+ return (
+ <>
+ <FilterHeader
+ title={`Labels${appliedFiltersCount > 0 ? ` (${appliedFiltersCount})` : ""}`}
+ isPreviewEnabled={previewEnabled}
+ handleIsPreviewEnabled={() => setPreviewEnabled(!previewEnabled)}
+ />
+ {previewEnabled && (
+ <div>
+ {sortedOptions ? (
+ sortedOptions.length > 0 ? (
+ <>
+ {sortedOptions.slice(0, itemsToRender).map((label) => (
+ <FilterOption
+ key={label?.id}
+ isChecked={appliedFilters?.includes(label?.id) ? true : false}
+ onClick={() => handleUpdate(label?.id)}
+ icon={<LabelIcons color={label.color} />}
+ title={label.name}
+ />
+ ))}
+ {sortedOptions.length > 5 && (
+ <button
+ type="button"
+ className="ml-8 text-xs font-medium text-custom-primary-100"
+ onClick={handleViewToggle}
+ >
+ {itemsToRender === sortedOptions.length ? "View less" : "View all"}
+ </button>
+ )}
+ </>
+ ) : (
+ <p className="text-xs italic text-custom-text-400">No matches found</p>
+ )
+ ) : (
+ <Loader className="space-y-2">
+ <Loader.Item height="20px" />
+ <Loader.Item height="20px" />
+ <Loader.Item height="20px" />
+ </Loader>
+ )}
+ </div>
+ )}
+ </>
+ );
+});
diff --git a/web/components/pages/list/filters/root.tsx b/web/components/pages/list/filters/root.tsx
new file mode 100644
index 0000000000..1107bbe950
--- /dev/null
+++ b/web/components/pages/list/filters/root.tsx
@@ -0,0 +1,108 @@
+import { useState } from "react";
+import { observer } from "mobx-react-lite";
+import { Search, X } from "lucide-react";
+import { IIssueLabel, TPageFilterProps, TPageFilters } from "@plane/types";
+// components
+import { FilterOption } from "@/components/issues";
+import { FilterCreatedBy, FilterCreatedDate, FilterLabels } from "@/components/pages";
+
+type Props = {
+ filters: TPageFilters;
+ handleFiltersUpdate: <T extends keyof TPageFilters>(filterKey: T, filterValue: TPageFilters[T]) => void;
+ labels?: IIssueLabel[] | undefined;
+ memberIds?: string[] | undefined;
+};
+
+export const PageFiltersSelection: React.FC<Props> = observer((props) => {
+ const { filters, handleFiltersUpdate, labels, memberIds } = props;
+ // states
+ const [filtersSearchQuery, setFiltersSearchQuery] = useState("");
+
+ const handleFilters = (key: keyof TPageFilterProps, value: boolean | string | string[]) => {
+ const newValues = filters.filters?.[key] ?? [];
+
+ if (typeof newValues === "boolean" && typeof value === "boolean") return;
+
+ if (Array.isArray(newValues)) {
+ if (Array.isArray(value))
+ value.forEach((val) => {
+ if (!newValues.includes(val)) newValues.push(val);
+ });
+ else if (typeof value === "string") {
+ if (newValues?.includes(value)) newValues.splice(newValues.indexOf(value), 1);
+ else newValues.push(value);
+ }
+ }
+
+ handleFiltersUpdate("filters", {
+ ...filters.filters,
+ [key]: newValues,
+ });
+ };
+
+ return (
+ <div className="flex h-full w-full flex-col overflow-hidden">
+ <div className="bg-custom-background-100 p-2.5 pb-0">
+ <div className="flex items-center gap-1.5 rounded border-[0.5px] border-custom-border-200 bg-custom-background-90 px-1.5 py-1 text-xs">
+ <Search className="text-custom-text-400" size={12} strokeWidth={2} />
+ <input
+ type="text"
+ className="w-full bg-custom-background-90 outline-none placeholder:text-custom-text-400"
+ placeholder="Search"
+ value={filtersSearchQuery}
+ onChange={(e) => setFiltersSearchQuery(e.target.value)}
+ autoFocus
+ />
+ {filtersSearchQuery !== "" && (
+ <button type="button" className="grid place-items-center" onClick={() => setFiltersSearchQuery("")}>
+ <X className="text-custom-text-300" size={12} strokeWidth={2} />
+ </button>
+ )}
+ </div>
+ </div>
+ <div className="h-full w-full divide-y divide-custom-border-200 overflow-y-auto px-2.5 vertical-scrollbar scrollbar-sm">
+ <div className="py-2">
+ <FilterOption
+ isChecked={!!filters.filters?.favorites}
+ onClick={() =>
+ handleFiltersUpdate("filters", {
+ ...filters.filters,
+ favorites: !filters.filters?.favorites,
+ })
+ }
+ title="Favorites"
+ />
+ </div>
+
+ {/* created date */}
+ <div className="py-2">
+ <FilterCreatedDate
+ appliedFilters={filters.filters?.created_at ?? null}
+ handleUpdate={(val) => handleFilters("created_at", val)}
+ searchQuery={filtersSearchQuery}
+ />
+ </div>
+
+ {/* created by */}
+ <div className="py-2">
+ <FilterCreatedBy
+ appliedFilters={filters.filters?.created_by ?? null}
+ handleUpdate={(val) => handleFilters("created_by", val)}
+ searchQuery={filtersSearchQuery}
+ memberIds={memberIds}
+ />
+ </div>
+
+ {/* labels */}
+ <div className="py-2">
+ <FilterLabels
+ appliedFilters={filters.filters?.labels ?? null}
+ handleUpdate={(val) => handleFilters("labels", val)}
+ searchQuery={filtersSearchQuery}
+ labels={labels}
+ />
+ </div>
+ </div>
+ </div>
+ );
+});
diff --git a/web/components/pages/list/index.ts b/web/components/pages/list/index.ts
new file mode 100644
index 0000000000..b8270f3f2b
--- /dev/null
+++ b/web/components/pages/list/index.ts
@@ -0,0 +1,7 @@
+export * from "./applied-filters";
+export * from "./filters";
+export * from "./block";
+export * from "./order-by";
+export * from "./root";
+export * from "./search-input";
+export * from "./tab-navigation";
diff --git a/web/components/pages/list/order-by.tsx b/web/components/pages/list/order-by.tsx
new file mode 100644
index 0000000000..5055b68e89
--- /dev/null
+++ b/web/components/pages/list/order-by.tsx
@@ -0,0 +1,77 @@
+import { ArrowDownWideNarrow, Check, ChevronDown } from "lucide-react";
+// types
+import { TPageFiltersSortBy, TPageFiltersSortKey } from "@plane/types";
+// ui
+import { CustomMenu, getButtonStyling } from "@plane/ui";
+// constants
+import { PAGE_SORTING_KEY_OPTIONS } from "@/constants/page";
+// helpers
+import { cn } from "@/helpers/common.helper";
+
+type Props = {
+ onChange: (value: { key?: TPageFiltersSortKey; order?: TPageFiltersSortBy }) => void;
+ sortBy: TPageFiltersSortBy;
+ sortKey: TPageFiltersSortKey;
+};
+
+export const PageOrderByDropdown: React.FC<Props> = (props) => {
+ const { onChange, sortBy, sortKey } = props;
+
+ const orderByDetails = PAGE_SORTING_KEY_OPTIONS.find((option) => sortKey === option.key);
+ const isDescending = sortBy === "desc";
+
+ return (
+ <CustomMenu
+ customButton={
+ <div className={cn(getButtonStyling("neutral-primary", "sm"), "px-2 text-custom-text-300")}>
+ <ArrowDownWideNarrow className="h-3 w-3" />
+ {orderByDetails?.label}
+ <ChevronDown className="h-3 w-3" strokeWidth={2} />
+ </div>
+ }
+ placement="bottom-end"
+ maxHeight="lg"
+ closeOnSelect
+ >
+ {PAGE_SORTING_KEY_OPTIONS.map((option) => (
+ <CustomMenu.MenuItem
+ key={option.key}
+ className="flex items-center justify-between gap-2"
+ onClick={() =>
+ onChange({
+ key: option.key,
+ })
+ }
+ >
+ {option.label}
+ {sortKey === option.key && <Check className="h-3 w-3" />}
+ </CustomMenu.MenuItem>
+ ))}
+ <hr className="my-2" />
+ <CustomMenu.MenuItem
+ className="flex items-center justify-between gap-2"
+ onClick={() => {
+ if (isDescending)
+ onChange({
+ order: "asc",
+ });
+ }}
+ >
+ Ascending
+ {!isDescending && <Check className="h-3 w-3" />}
+ </CustomMenu.MenuItem>
+ <CustomMenu.MenuItem
+ className="flex items-center justify-between gap-2"
+ onClick={() => {
+ if (!isDescending)
+ onChange({
+ order: "desc",
+ });
+ }}
+ >
+ Descending
+ {isDescending && <Check className="h-3 w-3" />}
+ </CustomMenu.MenuItem>
+ </CustomMenu>
+ );
+};
diff --git a/web/components/pages/list/root.tsx b/web/components/pages/list/root.tsx
new file mode 100644
index 0000000000..5833e7851f
--- /dev/null
+++ b/web/components/pages/list/root.tsx
@@ -0,0 +1,26 @@
+import { FC } from "react";
+import { observer } from "mobx-react";
+// hooks
+import { useProjectPages } from "@/hooks/store";
+// components
+import { PageListBlock } from "./";
+
+type TPagesListRoot = {
+ workspaceSlug: string;
+ projectId: string;
+};
+
+export const PagesListRoot: FC<TPagesListRoot> = observer((props) => {
+ const { workspaceSlug, projectId } = props;
+ // hooks
+ const { filteredPageIds } = useProjectPages(projectId);
+
+ if (!filteredPageIds) return <></>;
+ return (
+ <div className="relative w-full h-full overflow-hidden overflow-y-auto divide-y-[0.5px] divide-custom-border-200">
+ {filteredPageIds.map((pageId) => (
+ <PageListBlock key={pageId} workspaceSlug={workspaceSlug} projectId={projectId} pageId={pageId} />
+ ))}
+ </div>
+ );
+});
diff --git a/web/components/pages/list/search-input.tsx b/web/components/pages/list/search-input.tsx
new file mode 100644
index 0000000000..b6aa05790e
--- /dev/null
+++ b/web/components/pages/list/search-input.tsx
@@ -0,0 +1,83 @@
+import { FC, useState, useRef } from "react";
+import { observer } from "mobx-react-lite";
+import { Search, X } from "lucide-react";
+import { cn } from "@/helpers/common.helper";
+import { useProjectPages } from "@/hooks/store";
+import useOutsideClickDetector from "@/hooks/use-outside-click-detector";
+
+export type TPageSearchInput = { projectId: string };
+
+export const PageSearchInput: FC<TPageSearchInput> = observer((props) => {
+ const { projectId } = props;
+ // hooks
+ const {
+ filters: { searchQuery },
+ updateFilters,
+ } = useProjectPages(projectId);
+ // states
+ const [isSearchOpen, setIsSearchOpen] = useState(false);
+ // refs
+ const inputRef = useRef<HTMLInputElement>(null);
+ // outside click detector hook
+ useOutsideClickDetector(inputRef, () => {
+ if (isSearchOpen && searchQuery.trim() === "") setIsSearchOpen(false);
+ });
+
+ const handleInputKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === "Escape") {
+ if (searchQuery && searchQuery.trim() !== "") updateFilters("searchQuery", "");
+ else {
+ setIsSearchOpen(false);
+ inputRef.current?.blur();
+ }
+ }
+ };
+
+ return (
+ <>
+ {!isSearchOpen && (
+ <button
+ type="button"
+ className="flex-shrink-0 hover:bg-custom-background-80 rounded text-custom-text-400 relative flex justify-center items-center w-6 h-6"
+ onClick={() => {
+ setIsSearchOpen(true);
+ inputRef.current?.focus();
+ }}
+ >
+ <Search className="h-3.5 w-3.5" />
+ </button>
+ )}
+
+ <div
+ className={cn(
+ "ml-auto flex items-center justify-start gap-1 rounded-md border border-transparent bg-custom-background-100 text-custom-text-400 w-0 transition-[width] ease-linear overflow-hidden opacity-0",
+ {
+ "w-64 px-2.5 py-1.5 border-custom-border-200 opacity-100": isSearchOpen,
+ }
+ )}
+ >
+ <Search className="h-3.5 w-3.5" />
+ <input
+ ref={inputRef}
+ className="w-full max-w-[234px] border-none bg-transparent text-sm text-custom-text-100 placeholder:text-custom-text-400 focus:outline-none"
+ placeholder="Search pages"
+ value={searchQuery}
+ onChange={(e) => updateFilters("searchQuery", e.target.value)}
+ onKeyDown={handleInputKeyDown}
+ />
+ {isSearchOpen && (
+ <button
+ type="button"
+ className="grid place-items-center"
+ onClick={() => {
+ updateFilters("searchQuery", "");
+ setIsSearchOpen(false);
+ }}
+ >
+ <X className="h-3 w-3" />
+ </button>
+ )}
+ </div>
+ </>
+ );
+});
diff --git a/web/components/pages/list/tab-navigation.tsx b/web/components/pages/list/tab-navigation.tsx
new file mode 100644
index 0000000000..37a1ef64b9
--- /dev/null
+++ b/web/components/pages/list/tab-navigation.tsx
@@ -0,0 +1,64 @@
+import { FC } from "react";
+import Link from "next/link";
+// types
+import { TPageNavigationTabs } from "@plane/types";
+// helpers
+import { cn } from "@/helpers/common.helper";
+
+type TPageTabNavigation = {
+ workspaceSlug: string;
+ projectId: string;
+ pageType: TPageNavigationTabs;
+};
+
+// pages tab options
+const pageTabs: { key: TPageNavigationTabs; label: string }[] = [
+ {
+ key: "public",
+ label: "Public",
+ },
+ {
+ key: "private",
+ label: "Private",
+ },
+ {
+ key: "archived",
+ label: "Archived",
+ },
+];
+
+export const PageTabNavigation: FC<TPageTabNavigation> = (props) => {
+ const { workspaceSlug, projectId, pageType } = props;
+
+ const handleTabClick = (e: React.MouseEvent<HTMLAnchorElement>, tabKey: TPageNavigationTabs) => {
+ if (tabKey === pageType) e.preventDefault();
+ };
+
+ return (
+ <div className="relative flex items-center">
+ {pageTabs.map((tab) => (
+ <Link
+ key={tab.key}
+ href={`/${workspaceSlug}/projects/${projectId}/pages?type=${tab.key}`}
+ onClick={(e) => handleTabClick(e, tab.key)}
+ >
+ <div>
+ <div
+ className={cn(`p-3 py-4 text-sm font-medium transition-all`, {
+ "text-custom-primary-100": tab.key === pageType,
+ })}
+ >
+ {tab.label}
+ </div>
+ <div
+ className={cn(`rounded-t border-t-2 transition-all`, {
+ "border-custom-primary-100": tab.key === pageType,
+ "border-transparent": tab.key !== pageType,
+ })}
+ />
+ </div>
+ </Link>
+ ))}
+ </div>
+ );
+};
diff --git a/web/components/pages/loaders/index.ts b/web/components/pages/loaders/index.ts
new file mode 100644
index 0000000000..f278fa3823
--- /dev/null
+++ b/web/components/pages/loaders/index.ts
@@ -0,0 +1 @@
+export * from "./page-loader";
diff --git a/web/components/pages/loaders/page-loader.tsx b/web/components/pages/loaders/page-loader.tsx
new file mode 100644
index 0000000000..2b3f752b23
--- /dev/null
+++ b/web/components/pages/loaders/page-loader.tsx
@@ -0,0 +1,32 @@
+import { Loader } from "@plane/ui";
+
+export const PageLoader: React.FC = (props) => {
+ const {} = props;
+
+ return (
+ <div className="relative w-full h-full flex flex-col">
+ <div className="px-3 border-b border-custom-border-100 py-3">
+ <Loader className="relative flex items-center gap-2">
+ <Loader.Item width="200px" height="30px" />
+ <div className="relative flex items-center gap-2 ml-auto">
+ <Loader.Item width="100px" height="30px" />
+ <Loader.Item width="100px" height="30px" />
+ </div>
+ </Loader>
+ </div>
+ <div>
+ {Array.from(Array(10)).map((i) => (
+ <Loader key={i} className="relative flex items-center gap-2 p-3 py-4 border-b border-custom-border-100">
+ <Loader.Item width={`${250 + 10 * Math.floor(Math.random() * 10)}px`} height="22px" />
+ <div className="ml-auto relative flex items-center gap-2">
+ <Loader.Item width="60px" height="22px" />
+ <Loader.Item width="22px" height="22px" />
+ <Loader.Item width="22px" height="22px" />
+ <Loader.Item width="22px" height="22px" />
+ </div>
+ </Loader>
+ ))}
+ </div>
+ </div>
+ );
+};
diff --git a/web/components/pages/modals/create-page-modal.tsx b/web/components/pages/modals/create-page-modal.tsx
new file mode 100644
index 0000000000..01ccfb079e
--- /dev/null
+++ b/web/components/pages/modals/create-page-modal.tsx
@@ -0,0 +1,109 @@
+import { FC, Fragment, useState } from "react";
+import { useRouter } from "next/router";
+import { Dialog, Transition } from "@headlessui/react";
+// types
+import { TPage } from "@plane/types";
+// components
+import { PageForm } from "@/components/pages";
+// constants
+import { PAGE_CREATED } from "@/constants/event-tracker";
+import { EPageAccess } from "@/constants/page";
+// hooks
+import { useProjectPages, useEventTracker } from "@/hooks/store";
+
+type Props = {
+ workspaceSlug: string;
+ projectId: string;
+ isModalOpen: boolean;
+ handleModalClose: () => void;
+ redirectionEnabled?: boolean;
+};
+
+export const CreatePageModal: FC<Props> = (props) => {
+ const { workspaceSlug, projectId, isModalOpen, handleModalClose, redirectionEnabled = false } = props;
+ // states
+ const [pageFormData, setPageFormData] = useState<Partial<TPage>>({
+ id: undefined,
+ name: "",
+ access: EPageAccess.PUBLIC,
+ });
+ // router
+ const router = useRouter();
+ // store hooks
+ const { createPage } = useProjectPages(projectId);
+ const { capturePageEvent } = useEventTracker();
+ const handlePageFormData = <T extends keyof TPage>(key: T, value: TPage[T]) =>
+ setPageFormData((prev) => ({ ...prev, [key]: value }));
+
+ const handleStateClear = () => {
+ setPageFormData({ id: undefined, name: "", access: EPageAccess.PUBLIC });
+ handleModalClose();
+ };
+
+ const handleFormSubmit = async () => {
+ if (!workspaceSlug || !projectId) return;
+
+ try {
+ const pageData = await createPage(pageFormData);
+ if (pageData) {
+ capturePageEvent({
+ eventName: PAGE_CREATED,
+ payload: {
+ ...pageData,
+ state: "SUCCESS",
+ },
+ });
+ handleStateClear();
+ if (redirectionEnabled) router.push(`/${workspaceSlug}/projects/${projectId}/pages/${pageData.id}`);
+ }
+ } catch {
+ capturePageEvent({
+ eventName: PAGE_CREATED,
+ payload: {
+ state: "FAILED",
+ },
+ });
+ }
+ };
+
+ return (
+ <Transition.Root show={isModalOpen} as={Fragment}>
+ <Dialog as="div" className="relative z-20" onClose={handleModalClose}>
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0"
+ enterTo="opacity-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100"
+ leaveTo="opacity-0"
+ >
+ <div className="fixed inset-0 bg-custom-backdrop transition-opacity" />
+ </Transition.Child>
+
+ <div className="fixed inset-0 z-20 overflow-y-auto">
+ <div className="my-10 flex justify-center p-4 text-center sm:p-0 md:my-20">
+ <Transition.Child
+ as={Fragment}
+ enter="ease-out duration-300"
+ enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
+ enterTo="opacity-100 translate-y-0 sm:scale-100"
+ leave="ease-in duration-200"
+ leaveFrom="opacity-100 translate-y-0 sm:scale-100"
+ leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
+ >
+ <Dialog.Panel className="relative transform rounded-lg bg-custom-background-100 p-5 px-4 text-left shadow-custom-shadow-md transition-all w-full sm:max-w-2xl">
+ <PageForm
+ formData={pageFormData}
+ handleFormData={handlePageFormData}
+ handleModalClose={handleStateClear}
+ handleFormSubmit={handleFormSubmit}
+ />
+ </Dialog.Panel>
+ </Transition.Child>
+ </div>
+ </div>
+ </Dialog>
+ </Transition.Root>
+ );
+};
diff --git a/web/components/pages/delete-page-modal.tsx b/web/components/pages/modals/delete-page-modal.tsx
similarity index 87%
rename from web/components/pages/delete-page-modal.tsx
rename to web/components/pages/modals/delete-page-modal.tsx
index cedd6382d1..009ff9ab82 100644
--- a/web/components/pages/delete-page-modal.tsx
+++ b/web/components/pages/modals/delete-page-modal.tsx
@@ -1,6 +1,5 @@
import React, { useState } from "react";
import { observer } from "mobx-react-lite";
-import { useRouter } from "next/router";
import { AlertTriangle } from "lucide-react";
import { Dialog, Transition } from "@headlessui/react";
// ui
@@ -8,26 +7,21 @@ import { Button, TOAST_TYPE, setToast } from "@plane/ui";
// constants
import { PAGE_DELETED } from "@/constants/event-tracker";
// hooks
-import { useEventTracker, usePage } from "@/hooks/store";
-import { useProjectPages } from "@/hooks/store/use-project-page";
-// types
+import { useEventTracker, usePage, useProjectPages } from "@/hooks/store";
type TConfirmPageDeletionProps = {
- pageId: string;
isOpen: boolean;
onClose: () => void;
+ pageId: string;
+ projectId: string;
};
export const DeletePageModal: React.FC<TConfirmPageDeletionProps> = observer((props) => {
- const { pageId, isOpen, onClose } = props;
-
+ const { pageId, projectId, isOpen, onClose } = props;
// states
const [isDeleting, setIsDeleting] = useState(false);
- // router
- const router = useRouter();
- const { workspaceSlug, projectId } = router.query;
// store hooks
- const { deletePage } = useProjectPages();
+ const { removePage } = useProjectPages(projectId);
const { capturePageEvent } = useEventTracker();
const pageStore = usePage(pageId);
@@ -41,12 +35,8 @@ export const DeletePageModal: React.FC<TConfirmPageDeletionProps> = observer((pr
};
const handleDelete = async () => {
- if (!pageId || !workspaceSlug || !projectId) return;
-
setIsDeleting(true);
-
- // Delete Page will only delete the page from the archive page map, at this point only archived pages can be deleted
- await deletePage(workspaceSlug.toString(), projectId as string, pageId)
+ await removePage(pageId)
.then(() => {
capturePageEvent({
eventName: PAGE_DELETED,
@@ -75,10 +65,9 @@ export const DeletePageModal: React.FC<TConfirmPageDeletionProps> = observer((pr
title: "Error!",
message: "Page could not be deleted. Please try again.",
});
- })
- .finally(() => {
- setIsDeleting(false);
});
+
+ setIsDeleting(false);
};
return (
diff --git a/web/components/pages/modals/index.ts b/web/components/pages/modals/index.ts
new file mode 100644
index 0000000000..8f52e3adde
--- /dev/null
+++ b/web/components/pages/modals/index.ts
@@ -0,0 +1,3 @@
+export * from "./create-page-modal";
+export * from "./delete-page-modal";
+export * from "./page-form";
diff --git a/web/components/pages/modals/page-form.tsx b/web/components/pages/modals/page-form.tsx
new file mode 100644
index 0000000000..0698b7e2b5
--- /dev/null
+++ b/web/components/pages/modals/page-form.tsx
@@ -0,0 +1,105 @@
+import { FormEvent, useState } from "react";
+// types
+import { TPage } from "@plane/types";
+// ui
+import { Button, Input, Tooltip } from "@plane/ui";
+// constants
+import { PAGE_ACCESS_SPECIFIERS } from "@/constants/page";
+// helpers
+import { cn } from "@/helpers/common.helper";
+// hooks
+import { usePlatformOS } from "@/hooks/use-platform-os";
+
+type Props = {
+ formData: Partial<TPage>;
+ handleFormData: <T extends keyof TPage>(key: T, value: TPage[T]) => void;
+ handleModalClose: () => void;
+ handleFormSubmit: () => Promise<void>;
+};
+
+export const PageForm: React.FC<Props> = (props) => {
+ const { formData, handleFormData, handleModalClose, handleFormSubmit } = props;
+ // hooks
+ const { isMobile } = usePlatformOS();
+ // state
+ const [isSubmitting, setIsSubmitting] = useState(false);
+
+ const handlePageFormSubmit = async (e: FormEvent<HTMLFormElement>) => {
+ e.preventDefault();
+ try {
+ setIsSubmitting(true);
+ await handleFormSubmit();
+ setIsSubmitting(false);
+ } catch {
+ setIsSubmitting(false);
+ }
+ };
+
+ return (
+ <form onSubmit={handlePageFormSubmit}>
+ <div className="space-y-4">
+ <h3 className="text-lg font-medium leading-6 text-custom-text-100">Create Page</h3>
+
+ <div className="space-y-2">
+ <div>
+ <div className="text-custom-text-200">Name</div>
+ <div className="text-xs text-custom-text-300">
+ Max length of the name should be less than 255 characters
+ </div>
+ </div>
+ <Input
+ id="name"
+ type="text"
+ value={formData.name}
+ onChange={(e) => handleFormData("name", e.target.value)}
+ placeholder="Title"
+ className="w-full resize-none text-lg"
+ tabIndex={1}
+ required
+ maxLength={255}
+ />
+ </div>
+ </div>
+
+ <div className="mt-5 relative flex items-center justify-between gap-2">
+ <div className="relative flex items-center gap-2">
+ <div className="flex flex-shrink-0 items-stretch gap-0.5 rounded border-[0.5px] border-custom-border-200 p-1">
+ {PAGE_ACCESS_SPECIFIERS.map((access, index) => (
+ <Tooltip key={access.key} tooltipContent={access.label} isMobile={isMobile}>
+ <button
+ type="button"
+ onClick={() => handleFormData("access", access.key)}
+ className={cn(
+ "flex-shrink-0 relative flex justify-center items-center w-6 h-6 rounded-sm p-1 transition-all",
+ formData.access === access.key ? "bg-custom-background-80" : "hover:bg-custom-background-80"
+ )}
+ tabIndex={2 + index}
+ >
+ <access.icon
+ className={cn(
+ "h-3.5 w-3.5 transition-all",
+ formData.access === access.key ? "text-custom-text-100" : "text-custom-text-400"
+ )}
+ strokeWidth={2}
+ />
+ </button>
+ </Tooltip>
+ ))}
+ </div>
+ <h6 className="text-xs font-medium">
+ {PAGE_ACCESS_SPECIFIERS.find((access) => access.key === formData.access)?.label}
+ </h6>
+ </div>
+
+ <div className="relative flex items-center gap-2 justify-end">
+ <Button variant="neutral-primary" size="sm" onClick={handleModalClose} tabIndex={4}>
+ Cancel
+ </Button>
+ <Button variant="primary" size="sm" type="submit" loading={isSubmitting} tabIndex={5}>
+ {isSubmitting ? "Creating" : "Create Page"}
+ </Button>
+ </div>
+ </div>
+ </form>
+ );
+};
diff --git a/web/components/pages/page-detail/index.ts b/web/components/pages/page-detail/index.ts
new file mode 100644
index 0000000000..4fc6e5bd88
--- /dev/null
+++ b/web/components/pages/page-detail/index.ts
@@ -0,0 +1,3 @@
+export * from "./loader";
+
+export * from "./root";
diff --git a/web/components/pages/page-detail/loader.tsx b/web/components/pages/page-detail/loader.tsx
new file mode 100644
index 0000000000..68fa64abad
--- /dev/null
+++ b/web/components/pages/page-detail/loader.tsx
@@ -0,0 +1,118 @@
+import { FC } from "react";
+// components/ui
+import { Loader } from "@plane/ui";
+
+export const PageDetailRootLoader: FC = () => (
+ <div className=" relative w-full h-full flex flex-col">
+ {/* header */}
+ <div className="px-4 flex-shrink-0 relative flex items-center justify-between h-12 border-b border-custom-border-100">
+ {/* left options */}
+ <Loader className="flex-shrink-0 w-[280px]">
+ <Loader.Item width="26px" height="26px" />
+ </Loader>
+
+ {/* editor options */}
+ <div className="w-full relative flex items-center divide-x divide-custom-border-100">
+ <Loader className="relative flex items-center gap-1 pr-2">
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ </Loader>
+ <Loader className="relative flex items-center gap-1 px-2">
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ </Loader>
+ <Loader className="relative flex items-center gap-1 px-2">
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ </Loader>
+ <Loader className="relative flex items-center gap-1 pl-2">
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ </Loader>
+ </div>
+
+ {/* right options */}
+ <Loader className="w-full relative flex justify-end items-center gap-1">
+ <Loader.Item width="60px" height="26px" />
+ <Loader.Item width="40px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ <Loader.Item width="26px" height="26px" />
+ </Loader>
+ </div>
+
+ {/* content */}
+ <div className="px-4 w-full h-full overflow-hidden relative flex">
+ {/* table of content loader */}
+ <div className="flex-shrink-0 w-[280px] pr-5 py-5">
+ <Loader className="w-full space-y-4">
+ <Loader.Item width="100%" height="24px" />
+ <div className="space-y-2">
+ <Loader.Item width="60%" height="12px" />
+ <div className="ml-6 space-y-2">
+ <Loader.Item width="80%" height="12px" />
+ <Loader.Item width="100%" height="12px" />
+ </div>
+ <Loader.Item width="60%" height="12px" />
+ <div className="ml-6 space-y-2">
+ <Loader.Item width="80%" height="12px" />
+ <Loader.Item width="100%" height="12px" />
+ </div>
+ <Loader.Item width="100%" height="12px" />
+ <Loader.Item width="60%" height="12px" />
+ <div className="ml-6 space-y-2">
+ <Loader.Item width="80%" height="12px" />
+ <Loader.Item width="100%" height="12px" />
+ </div>
+ <Loader.Item width="80%" height="12px" />
+ <Loader.Item width="100%" height="12px" />
+ </div>
+ </Loader>
+ </div>
+
+ {/* editor loader */}
+ <div className="w-full h-full py-5">
+ <Loader className="relative space-y-4">
+ <Loader.Item width="50%" height="36px" />
+ <div className="space-y-2">
+ <div className="py-2">
+ <Loader.Item width="100%" height="36px" />
+ </div>
+ <Loader.Item width="80%" height="22px" />
+ <div className="relative flex items-center gap-2">
+ <Loader.Item width="30px" height="30px" />
+ <Loader.Item width="30%" height="22px" />
+ </div>
+ <div className="py-2">
+ <Loader.Item width="60%" height="36px" />
+ </div>
+ <Loader.Item width="70%" height="22px" />
+ <Loader.Item width="30%" height="22px" />
+ <div className="relative flex items-center gap-2">
+ <Loader.Item width="30px" height="30px" />
+ <Loader.Item width="30%" height="22px" />
+ </div>
+ <div className="py-2">
+ <Loader.Item width="50%" height="30px" />
+ </div>
+ <Loader.Item width="100%" height="22px" />
+ <div className="py-2">
+ <Loader.Item width="30%" height="30px" />
+ </div>
+ <Loader.Item width="30%" height="22px" />
+ <div className="relative flex items-center gap-2">
+ <div className="py-2">
+ <Loader.Item width="30px" height="30px" />
+ </div>
+ <Loader.Item width="30%" height="22px" />
+ </div>
+ </div>
+ </Loader>
+ </div>
+ </div>
+ </div>
+);
diff --git a/web/components/pages/page-detail/root.tsx b/web/components/pages/page-detail/root.tsx
new file mode 100644
index 0000000000..96694be029
--- /dev/null
+++ b/web/components/pages/page-detail/root.tsx
@@ -0,0 +1,54 @@
+import { FC, Fragment } from "react";
+import { observer } from "mobx-react-lite";
+// hooks
+import { PageHead } from "@/components/core";
+import { useProjectPages, usePage } from "@/hooks/store";
+// components
+import { PageDetailRootLoader } from "./";
+
+type TPageDetailRoot = {
+ projectId: string;
+ pageId: string;
+};
+
+export const PageDetailRoot: FC<TPageDetailRoot> = observer((props) => {
+ const { projectId, pageId } = props;
+ // hooks
+ const { loader } = useProjectPages(projectId);
+ const { id, name } = usePage(pageId);
+
+ if (loader === "init-loader") return <PageDetailRootLoader />;
+
+ if (!id) return <div className="">No page is available.</div>;
+
+ return (
+ <Fragment>
+ <PageHead title={name || "Pages"} />
+
+ <div className="relative w-full h-full flex flex-col">
+ <div className="flex-shrink-0 px-4 relative flex items-center justify-between h-12 border-b border-custom-border-100">
+ {/* header left container */}
+ <div className="flex-shrink-0 w-[280px]">Icon</div>
+ {/* header editor tool container */}
+ <div className="w-full relative hidden md:flex items-center divide-x divide-custom-border-100 ">
+ Editor keys
+ </div>
+ {/* header right operations container */}
+ <div className="w-full relative flex justify-end">right saved</div>
+ </div>
+
+ {/* editor container for small screens */}
+ <div className="px-4 h-12 relative flex md:hidden items-center border-b border-custom-border-100">
+ Editor keys
+ </div>
+
+ <div className="px-4 w-full h-full overflow-hidden relative flex">
+ {/* editor table of content content container */}
+ <div className="flex-shrink-0 w-[280px] pr-5 py-5">Table of content</div>
+ {/* editor container */}
+ <div className="w-full h-full py-5">Editor Container</div>
+ </div>
+ </div>
+ </Fragment>
+ );
+});
diff --git a/web/components/pages/page-form.tsx b/web/components/pages/page-form.tsx
deleted file mode 100644
index c1e02504eb..0000000000
--- a/web/components/pages/page-form.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-import { Controller, useForm } from "react-hook-form";
-import { IPage } from "@plane/types";
-// ui
-import { Button, Input, Tooltip } from "@plane/ui";
-// types
-// constants
-import { PAGE_ACCESS_SPECIFIERS } from "@/constants/page";
-import { usePlatformOS } from "@/hooks/use-platform-os";
-import { IPageStore } from "@/store/page.store";
-
-type Props = {
- handleFormSubmit: (values: IPage) => Promise<void>;
- handleClose: () => void;
- pageStore?: IPageStore;
-};
-
-const defaultValues = {
- name: "",
- description: "",
- access: 0,
-};
-
-export const PageForm: React.FC<Props> = (props) => {
- const { handleFormSubmit, handleClose, pageStore } = props;
-
- const {
- formState: { errors, isSubmitting },
- handleSubmit,
- control,
- } = useForm<IPage>({
- defaultValues: pageStore
- ? { name: pageStore.name, description: pageStore.description, access: pageStore.access }
- : defaultValues,
- });
- const { isMobile } = usePlatformOS();
- const handleCreateUpdatePage = (formData: IPage) => handleFormSubmit(formData);
-
- return (
- <form onSubmit={handleSubmit(handleCreateUpdatePage)}>
- <div className="space-y-4">
- <h3 className="text-lg font-medium leading-6 text-custom-text-100">{pageStore ? "Update" : "Create"} Page</h3>
- <div className="space-y-3">
- <div>
- <Controller
- control={control}
- name="name"
- rules={{
- required: "Title is required",
- maxLength: {
- value: 255,
- message: "Title should be less than 255 characters",
- },
- }}
- render={({ field: { value, onChange, ref } }) => (
- <Input
- id="name"
- type="text"
- value={value}
- onChange={onChange}
- ref={ref}
- hasError={Boolean(errors.name)}
- placeholder="Title"
- className="w-full resize-none text-lg"
- tabIndex={1}
- />
- )}
- />
- </div>
- </div>
- </div>
- <div className="mt-5 md:flex items-center justify-between gap-2">
- <Controller
- control={control}
- name="access"
- render={({ field: { value, onChange } }) => (
- <div className="flex items-center gap-2">
- <div className="flex flex-shrink-0 items-stretch gap-0.5 rounded border-[0.5px] border-custom-border-200 p-1">
- {PAGE_ACCESS_SPECIFIERS.map((access, index) => (
- <Tooltip key={access.key} tooltipContent={access.label} isMobile={isMobile}>
- <button
- type="button"
- onClick={() => onChange(access.key)}
- className={`grid aspect-square place-items-center rounded-sm p-1 hover:bg-custom-background-90 ${
- value === access.key ? "bg-custom-background-90" : ""
- }`}
- tabIndex={2 + index}
- >
- <access.icon
- className={`h-3.5 w-3.5 ${
- value === access.key ? "text-custom-text-100" : "text-custom-text-400"
- }`}
- strokeWidth={2}
- />
- </button>
- </Tooltip>
- ))}
- </div>
- <h6 className="text-xs font-medium">
- {PAGE_ACCESS_SPECIFIERS.find((access) => access.key === value)?.label}
- </h6>
- </div>
- )}
- />
- <div className="flex items-center gap-2 justify-end mt-5 md:mt-0">
- <Button variant="neutral-primary" size="sm" onClick={handleClose} tabIndex={4}>
- Cancel
- </Button>
- <Button variant="primary" size="sm" type="submit" loading={isSubmitting} tabIndex={5}>
- {pageStore ? (isSubmitting ? "Updating..." : "Update page") : isSubmitting ? "Creating..." : "Create Page"}
- </Button>
- </div>
- </div>
- </form>
- );
-};
diff --git a/web/components/pages/pages-list-main-content.tsx b/web/components/pages/pages-list-main-content.tsx
new file mode 100644
index 0000000000..e961849ecf
--- /dev/null
+++ b/web/components/pages/pages-list-main-content.tsx
@@ -0,0 +1,55 @@
+import { observer } from "mobx-react";
+import Image from "next/image";
+// types
+import { TPageNavigationTabs } from "@plane/types";
+// components
+import { EmptyState } from "@/components/empty-state";
+import { PageLoader } from "@/components/pages";
+// constants
+import { EmptyStateType } from "@/constants/empty-state";
+// hooks
+import { useProjectPages } from "@/hooks/store";
+// assets
+import AllFiltersImage from "public/empty-state/pages/all-filters.svg";
+import NameFilterImage from "public/empty-state/pages/name-filter.svg";
+
+type Props = {
+ children: React.ReactNode;
+ pageType: TPageNavigationTabs;
+ projectId: string;
+};
+
+export const PagesListMainContent: React.FC<Props> = observer((props) => {
+ const { children, pageType, projectId } = props;
+ // store hooks
+ const { loader, filteredPageIds, pageIds, filters } = useProjectPages(projectId);
+
+ if (loader === "init-loader") return <PageLoader />;
+ // if no pages exist in the active page type
+ if (pageIds?.length === 0) {
+ if (pageType === "public") return <EmptyState type={EmptyStateType.PROJECT_PAGE_PUBLIC} />;
+ if (pageType === "private") return <EmptyState type={EmptyStateType.PROJECT_PAGE_PRIVATE} />;
+ if (pageType === "archived") return <EmptyState type={EmptyStateType.PROJECT_PAGE_ARCHIVED} />;
+ }
+ // if no pages match the filter criteria
+ if (filteredPageIds?.length === 0)
+ return (
+ <div className="h-full w-full grid place-items-center">
+ <div className="text-center">
+ <Image
+ src={filters.searchQuery.length > 0 ? NameFilterImage : AllFiltersImage}
+ className="h-36 sm:h-48 w-36 sm:w-48 mx-auto"
+ alt="No matching modules"
+ />
+ <h5 className="text-xl font-medium mt-7 mb-1">No matching pages</h5>
+ <p className="text-custom-text-400 text-base">
+ {filters.searchQuery.length > 0
+ ? "Remove the search criteria to see all pages"
+ : "Remove the filters to see all pages"}
+ </p>
+ </div>
+ </div>
+ );
+
+ return <div className="h-full w-full overflow-hidden">{children}</div>;
+});
diff --git a/web/components/pages/pages-list-view.tsx b/web/components/pages/pages-list-view.tsx
new file mode 100644
index 0000000000..2ff4aead95
--- /dev/null
+++ b/web/components/pages/pages-list-view.tsx
@@ -0,0 +1,36 @@
+import { observer } from "mobx-react-lite";
+import useSWR from "swr";
+import { TPageNavigationTabs } from "@plane/types";
+// components
+import { PagesListHeaderRoot, PagesListMainContent } from "@/components/pages";
+// hooks
+import { useProjectPages } from "@/hooks/store";
+
+type TPageView = {
+ workspaceSlug: string;
+ projectId: string;
+ pageType: TPageNavigationTabs;
+ children: React.ReactNode;
+};
+
+export const PagesListView: React.FC<TPageView> = observer((props) => {
+ const { workspaceSlug, projectId, pageType, children } = props;
+ // store hooks
+ const { getAllPages } = useProjectPages(projectId);
+ // fetching pages list
+ useSWR(
+ projectId && pageType ? `PROJECT_PAGES_${projectId}_${pageType}` : null,
+ projectId && pageType ? () => getAllPages(pageType) : null
+ );
+
+ // pages loader
+ return (
+ <div className="relative w-full h-full overflow-hidden flex flex-col">
+ {/* tab header */}
+ <PagesListHeaderRoot pageType={pageType} projectId={projectId} workspaceSlug={workspaceSlug} />
+ <PagesListMainContent pageType={pageType} projectId={projectId}>
+ {children}
+ </PagesListMainContent>
+ </div>
+ );
+});
diff --git a/web/components/pages/pages-list/all-pages-list.tsx b/web/components/pages/pages-list/all-pages-list.tsx
deleted file mode 100644
index 3af99ddf6d..0000000000
--- a/web/components/pages/pages-list/all-pages-list.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { FC } from "react";
-import { observer } from "mobx-react-lite";
-// hooks
-import { Loader } from "@plane/ui";
-import { PagesListView } from "@/components/pages/pages-list";
-// ui
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-
-export const AllPagesList: FC = observer(() => {
- const pageStores = useProjectPages();
- // subscribing to the projectPageStore
- const { projectPageIds } = pageStores;
-
- if (!projectPageIds) {
- return (
- <Loader className="space-y-4">
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- </Loader>
- );
- }
- return <PagesListView pageIds={projectPageIds} />;
-});
diff --git a/web/components/pages/pages-list/archived-pages-list.tsx b/web/components/pages/pages-list/archived-pages-list.tsx
deleted file mode 100644
index 4db6f29a89..0000000000
--- a/web/components/pages/pages-list/archived-pages-list.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { FC } from "react";
-import { observer } from "mobx-react-lite";
-// components
-import { Loader, Spinner } from "@plane/ui";
-import { PagesListView } from "@/components/pages/pages-list";
-// hooks
-// ui
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-
-export const ArchivedPagesList: FC = observer(() => {
- const projectPageStore = useProjectPages();
- const { archivedPageIds, archivedPageLoader } = projectPageStore;
-
- if (archivedPageLoader) {
- return (
- <div className="flex items-center justify-center h-full w-full">
- <Spinner />
- </div>
- );
- }
- if (!archivedPageIds)
- return (
- <Loader className="space-y-4">
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- </Loader>
- );
-
- return <PagesListView pageIds={archivedPageIds} />;
-});
diff --git a/web/components/pages/pages-list/favorite-pages-list.tsx b/web/components/pages/pages-list/favorite-pages-list.tsx
deleted file mode 100644
index 227dd7408e..0000000000
--- a/web/components/pages/pages-list/favorite-pages-list.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { FC } from "react";
-import { observer } from "mobx-react-lite";
-// components
-import { Loader } from "@plane/ui";
-import { PagesListView } from "@/components/pages/pages-list";
-// hooks
-// ui
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-
-export const FavoritePagesList: FC = observer(() => {
- const projectPageStore = useProjectPages();
- const { favoriteProjectPageIds } = projectPageStore;
-
- if (!favoriteProjectPageIds)
- return (
- <Loader className="space-y-4">
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- </Loader>
- );
-
- return <PagesListView pageIds={favoriteProjectPageIds} />;
-});
diff --git a/web/components/pages/pages-list/index.ts b/web/components/pages/pages-list/index.ts
deleted file mode 100644
index 1f199296a5..0000000000
--- a/web/components/pages/pages-list/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-export * from "./all-pages-list";
-export * from "./archived-pages-list";
-export * from "./favorite-pages-list";
-export * from "./private-page-list";
-export * from "./shared-pages-list";
-export * from "./recent-pages-list";
-export * from "./types";
-export * from "./list-view";
diff --git a/web/components/pages/pages-list/list-item.tsx b/web/components/pages/pages-list/list-item.tsx
deleted file mode 100644
index 57b41738ff..0000000000
--- a/web/components/pages/pages-list/list-item.tsx
+++ /dev/null
@@ -1,302 +0,0 @@
-import { FC, useState } from "react";
-import { observer } from "mobx-react-lite";
-import Link from "next/link";
-import { useRouter } from "next/router";
-import {
- AlertCircle,
- Archive,
- ArchiveRestoreIcon,
- FileText,
- Globe2,
- LinkIcon,
- Lock,
- Pencil,
- Star,
- Trash2,
-} from "lucide-react";
-import { IIssueLabel } from "@plane/types";
-// ui
-import { CustomMenu, Tooltip } from "@plane/ui";
-// components
-import { CreateUpdatePageModal, DeletePageModal } from "@/components/pages";
-// constants
-import { EUserProjectRoles } from "@/constants/project";
-import { renderFormattedTime, renderFormattedDate } from "@/helpers/date-time.helper";
-import { copyUrlToClipboard } from "@/helpers/string.helper";
-// hooks
-import { useMember, usePage, useUser } from "@/hooks/store";
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-import { usePlatformOS } from "@/hooks/use-platform-os";
-
-export interface IPagesListItem {
- pageId: string;
- projectId: string;
-}
-
-export const PagesListItem: FC<IPagesListItem> = observer(({ pageId, projectId }: IPagesListItem) => {
- const projectPageStore = useProjectPages();
- // Now, I am observing only the projectPages, out of the projectPageStore.
- const { archivePage, restorePage } = projectPageStore;
-
- const pageStore = usePage(pageId);
-
- // states
- const router = useRouter();
- const { workspaceSlug } = router.query;
- const [createUpdatePageModal, setCreateUpdatePageModal] = useState(false);
-
- const [deletePageModal, setDeletePageModal] = useState(false);
- const { isMobile } = usePlatformOS();
- const {
- currentUser,
- membership: { currentProjectRole },
- } = useUser();
-
- const {
- project: { getProjectMemberDetails },
- } = useMember();
-
- if (!pageStore) return null;
-
- const {
- archived_at,
- label_details,
- access,
- is_favorite,
- owned_by,
- name,
- created_at,
- updated_at,
- makePublic,
- makePrivate,
- addToFavorites,
- removeFromFavorites,
- } = pageStore;
-
- const handleCopyUrl = async (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- await copyUrlToClipboard(`${workspaceSlug}/projects/${projectId}/pages/${pageId}`);
- };
-
- const handleAddToFavorites = (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
- addToFavorites();
- };
-
- const handleRemoveFromFavorites = (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- removeFromFavorites();
- };
-
- const handleMakePublic = (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- makePublic();
- };
-
- const handleMakePrivate = (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- makePrivate();
- };
-
- const handleArchivePage = async (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- await archivePage(workspaceSlug as string, projectId as string, pageId as string);
- };
-
- const handleRestorePage = async (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- await restorePage(workspaceSlug as string, projectId as string, pageId as string);
- };
-
- const handleDeletePage = (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- setDeletePageModal(true);
- };
-
- const handleEditPage = (e: React.MouseEvent<HTMLElement>) => {
- e.preventDefault();
- e.stopPropagation();
-
- setCreateUpdatePageModal(true);
- };
-
- const ownerDetails = getProjectMemberDetails(owned_by);
- const isCurrentUserOwner = owned_by === currentUser?.id;
-
- const userCanEdit =
- isCurrentUserOwner ||
- (currentProjectRole && [EUserProjectRoles.ADMIN, EUserProjectRoles.MEMBER].includes(currentProjectRole));
- const userCanChangeAccess = isCurrentUserOwner;
- const userCanArchive = isCurrentUserOwner || currentProjectRole === EUserProjectRoles.ADMIN;
- const userCanDelete = isCurrentUserOwner || currentProjectRole === EUserProjectRoles.ADMIN;
- const isEditingAllowed = !!currentProjectRole && currentProjectRole >= EUserProjectRoles.MEMBER;
-
- return (
- <>
- <CreateUpdatePageModal
- pageStore={pageStore}
- isOpen={createUpdatePageModal}
- handleClose={() => setCreateUpdatePageModal(false)}
- projectId={projectId}
- />
- <DeletePageModal isOpen={deletePageModal} onClose={() => setDeletePageModal(false)} pageId={pageId} />
- <li>
- <Link href={`/${workspaceSlug}/projects/${projectId}/pages/${pageId}`}>
- <div className="relative rounded p-3 md:p-4 text-custom-text-200 hover:bg-custom-background-80">
- <div className="flex items-center justify-between">
- <div className="flex items-center gap-2 overflow-hidden">
- <FileText className="h-4 w-4 shrink-0" />
- <p className="mr-2 truncate text-sm text-custom-text-100">{name}</p>
- {label_details.length > 0 &&
- label_details.map((label: IIssueLabel) => (
- <div
- key={label.id}
- className="group flex items-center gap-1 rounded-2xl border border-custom-border-200 px-2 py-0.5 text-xs"
- style={{
- backgroundColor: `${label?.color}20`,
- }}
- >
- <span
- className="h-1.5 w-1.5 flex-shrink-0 rounded-full"
- style={{
- backgroundColor: label?.color,
- }}
- />
- {label.name}
- </div>
- ))}
- </div>
- <div className="flex items-center gap-2.5">
- {archived_at ? (
- <Tooltip
- isMobile={isMobile}
- tooltipContent={`Archived at ${renderFormattedTime(archived_at)} on ${renderFormattedDate(
- archived_at
- )}`}
- >
- <p className="text-sm text-custom-text-200">{renderFormattedTime(archived_at)}</p>
- </Tooltip>
- ) : (
- updated_at && (
- <Tooltip
- tooltipContent={`Last updated at ${renderFormattedTime(updated_at)} on ${renderFormattedDate(
- updated_at
- )}`}
- >
- <p className="text-sm text-custom-text-200">{renderFormattedTime(updated_at)}</p>
- </Tooltip>
- )
- )}
- {isEditingAllowed && (
- <Tooltip
- tooltipContent={`${is_favorite ? "Remove from favorites" : "Mark as favorite"}`}
- isMobile={isMobile}
- >
- {is_favorite ? (
- <button type="button" onClick={handleRemoveFromFavorites}>
- <Star className="h-3.5 w-3.5 fill-orange-400 text-orange-400" />
- </button>
- ) : (
- <button type="button" onClick={handleAddToFavorites}>
- <Star className="h-3.5 w-3.5" />
- </button>
- )}
- </Tooltip>
- )}
- {userCanChangeAccess && (
- <Tooltip
- isMobile={isMobile}
- tooltipContent={`${
- access ? "This page is only visible to you" : "This page can be viewed by anyone in the project"
- }`}
- >
- {access ? (
- <button type="button" onClick={handleMakePublic}>
- <Lock className="h-3.5 w-3.5" />
- </button>
- ) : (
- <button type="button" onClick={handleMakePrivate}>
- <Globe2 className="h-3.5 w-3.5" />
- </button>
- )}
- </Tooltip>
- )}
- <Tooltip
- isMobile={isMobile}
- position="top-right"
- tooltipContent={`Created by ${ownerDetails?.member?.display_name} on ${renderFormattedDate(
- created_at
- )}`}
- >
- <AlertCircle className="h-3.5 w-3.5" />
- </Tooltip>
- <CustomMenu placement="bottom-end" className="!-m-1" verticalEllipsis>
- {archived_at ? (
- <>
- {userCanArchive && (
- <CustomMenu.MenuItem onClick={handleRestorePage}>
- <div className="flex items-center gap-2">
- <ArchiveRestoreIcon className="h-3 w-3" />
- <span>Restore page</span>
- </div>
- </CustomMenu.MenuItem>
- )}
- {userCanDelete && isEditingAllowed && (
- <CustomMenu.MenuItem onClick={handleDeletePage}>
- <div className="flex items-center gap-2">
- <Trash2 className="h-3 w-3" />
- <span>Delete page</span>
- </div>
- </CustomMenu.MenuItem>
- )}
- </>
- ) : (
- <>
- {userCanEdit && isEditingAllowed && (
- <CustomMenu.MenuItem onClick={handleEditPage}>
- <div className="flex items-center gap-2">
- <Pencil className="h-3 w-3" />
- <span>Edit page</span>
- </div>
- </CustomMenu.MenuItem>
- )}
- {userCanArchive && isEditingAllowed && (
- <CustomMenu.MenuItem onClick={handleArchivePage}>
- <div className="flex items-center gap-2">
- <Archive className="h-3 w-3" />
- <span>Archive page</span>
- </div>
- </CustomMenu.MenuItem>
- )}
- </>
- )}
- <CustomMenu.MenuItem onClick={handleCopyUrl}>
- <div className="flex items-center gap-2">
- <LinkIcon className="h-3 w-3" />
- <span>Copy page link</span>
- </div>
- </CustomMenu.MenuItem>
- </CustomMenu>
- </div>
- </div>
- </div>
- </Link>
- </li>
- </>
- );
-});
diff --git a/web/components/pages/pages-list/list-view.tsx b/web/components/pages/pages-list/list-view.tsx
deleted file mode 100644
index 165a9a6198..0000000000
--- a/web/components/pages/pages-list/list-view.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import { FC } from "react";
-import { useRouter } from "next/router";
-// hooks
-import { Loader } from "@plane/ui";
-import { EmptyState } from "@/components/empty-state";
-import { EMPTY_STATE_DETAILS, EmptyStateType } from "@/constants/empty-state";
-import { useApplication } from "@/hooks/store";
-import useLocalStorage from "@/hooks/use-local-storage";
-// components
-import { PagesListItem } from "./list-item";
-// ui
-// constants
-
-type IPagesListView = {
- pageIds: string[];
-};
-
-export const PagesListView: FC<IPagesListView> = (props) => {
- const { pageIds: projectPageIds } = props;
- // store hooks
- const {
- commandPalette: { toggleCreatePageModal },
- } = useApplication();
- // local storage
- const { storedValue: pageTab } = useLocalStorage("pageTab", "Recent");
- // router
- const router = useRouter();
- const { workspaceSlug, projectId } = router.query;
-
- // here we are only observing the projectPageStore, so that we can re-render the component when the projectPageStore changes
-
- const emptyStateType = pageTab ? `project-page-${pageTab.toLowerCase()}` : EmptyStateType.PROJECT_PAGE_ALL;
- const isButtonVisible = pageTab !== "archived" && pageTab !== "favorites";
-
- return (
- <>
- {projectPageIds && workspaceSlug && projectId ? (
- <div className="h-full space-y-4 overflow-y-auto vertical-scrollbar scrollbar-lg">
- {projectPageIds.length > 0 ? (
- <ul role="list" className="divide-y divide-custom-border-200">
- {projectPageIds.map((pageId: string) => (
- <PagesListItem key={pageId} pageId={pageId} projectId={projectId.toString()} />
- ))}
- </ul>
- ) : (
- <EmptyState
- type={emptyStateType as keyof typeof EMPTY_STATE_DETAILS}
- primaryButtonOnClick={isButtonVisible ? () => toggleCreatePageModal(true) : undefined}
- />
- )}
- </div>
- ) : (
- <Loader className="space-y-4">
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- </Loader>
- )}
- </>
- );
-};
diff --git a/web/components/pages/pages-list/private-page-list.tsx b/web/components/pages/pages-list/private-page-list.tsx
deleted file mode 100644
index db99c69421..0000000000
--- a/web/components/pages/pages-list/private-page-list.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { FC } from "react";
-import { observer } from "mobx-react-lite";
-// hooks
-// components
-import { Loader } from "@plane/ui";
-import { PagesListView } from "@/components/pages/pages-list";
-// ui
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-
-export const PrivatePagesList: FC = observer(() => {
- const projectPageStore = useProjectPages();
- const { privateProjectPageIds } = projectPageStore;
-
- if (!privateProjectPageIds)
- return (
- <Loader className="space-y-4">
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- </Loader>
- );
-
- return <PagesListView pageIds={privateProjectPageIds} />;
-});
diff --git a/web/components/pages/pages-list/recent-pages-list.tsx b/web/components/pages/pages-list/recent-pages-list.tsx
deleted file mode 100644
index 7066fff251..0000000000
--- a/web/components/pages/pages-list/recent-pages-list.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-import React, { FC } from "react";
-import { observer } from "mobx-react-lite";
-// hooks
-import { Loader } from "@plane/ui";
-import { EmptyState } from "@/components/empty-state";
-import { PagesListView } from "@/components/pages/pages-list";
-import { EmptyStateType } from "@/constants/empty-state";
-import { replaceUnderscoreIfSnakeCase } from "@/helpers/string.helper";
-import { useApplication } from "@/hooks/store";
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-// components
-// ui
-// helpers
-// constants
-
-export const RecentPagesList: FC = observer(() => {
- // store hooks
- const { commandPalette: commandPaletteStore } = useApplication();
-
- const { recentProjectPages } = useProjectPages();
-
- // FIXME: replace any with proper type
- const isEmpty = recentProjectPages && Object.values(recentProjectPages).every((value: any) => value.length === 0);
-
- if (!recentProjectPages) {
- return (
- <Loader className="space-y-4">
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- </Loader>
- );
- }
-
- return (
- <>
- {Object.keys(recentProjectPages).length > 0 && !isEmpty ? (
- <>
- {Object.keys(recentProjectPages).map((key) => {
- if (recentProjectPages[key]?.length === 0) return null;
-
- return (
- <div key={key}>
- <h2 className="sticky top-0 z-[1] mb-2 bg-custom-background-100 text-xl font-semibold capitalize px-3 md:p-0">
- {replaceUnderscoreIfSnakeCase(key)}
- </h2>
- <PagesListView pageIds={recentProjectPages[key]} />
- </div>
- );
- })}
- </>
- ) : (
- <>
- <EmptyState
- type={EmptyStateType.PROJECT_PAGE_RECENT}
- primaryButtonOnClick={() => commandPaletteStore.toggleCreatePageModal(true)}
- size="sm"
- />
- </>
- )}
- </>
- );
-});
diff --git a/web/components/pages/pages-list/shared-pages-list.tsx b/web/components/pages/pages-list/shared-pages-list.tsx
deleted file mode 100644
index 600727e062..0000000000
--- a/web/components/pages/pages-list/shared-pages-list.tsx
+++ /dev/null
@@ -1,24 +0,0 @@
-import { FC } from "react";
-import { observer } from "mobx-react-lite";
-// components
-import { Loader } from "@plane/ui";
-import { PagesListView } from "@/components/pages/pages-list";
-// hooks
-// ui
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-
-export const SharedPagesList: FC = observer(() => {
- const projectPageStore = useProjectPages();
- const { publicProjectPageIds } = projectPageStore;
-
- if (!publicProjectPageIds)
- return (
- <Loader className="space-y-4">
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- <Loader.Item height="40px" />
- </Loader>
- );
-
- return <PagesListView pageIds={publicProjectPageIds} />;
-});
diff --git a/web/components/pages/pages-list/types.ts b/web/components/pages/pages-list/types.ts
deleted file mode 100644
index 148ab6aa4b..0000000000
--- a/web/components/pages/pages-list/types.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-import { TPageViewProps } from "@plane/types";
-
-export type TPagesListProps = {
- viewType: TPageViewProps;
-};
diff --git a/web/components/profile/activity/activity-list.tsx b/web/components/profile/activity/activity-list.tsx
index 2926f0637e..c835319662 100644
--- a/web/components/profile/activity/activity-list.tsx
+++ b/web/components/profile/activity/activity-list.tsx
@@ -1,12 +1,12 @@
import { observer } from "mobx-react";
import Link from "next/link";
import { History, MessageSquare } from "lucide-react";
-import { RichReadOnlyEditor } from "@plane/rich-text-editor";
import { IUserActivityResponse } from "@plane/types";
-// editor
// hooks
// components
import { ActivityIcon, ActivityMessage, IssueLink } from "@/components/core";
+// editor
+import { RichTextReadOnlyEditor } from "@/components/editor/rich-text-editor/rich-text-read-only-editor";
// ui
import { ActivitySettingsLoader } from "@/components/ui";
// helpers
@@ -28,7 +28,7 @@ export const ActivityList: React.FC<Props> = observer((props) => {
<>
{activity ? (
<ul role="list">
- {activity.results.map((activityItem: any) => {
+ {activity.results.map((activityItem) => {
if (activityItem.field === "comment")
return (
<div key={activityItem.id} className="mt-2">
@@ -66,11 +66,13 @@ export const ActivityList: React.FC<Props> = observer((props) => {
</p>
</div>
<div className="issue-comments-section p-0">
- <RichReadOnlyEditor
- value={activityItem?.new_value !== "" ? activityItem.new_value : activityItem.old_value}
- customClassName="text-xs border border-custom-border-200 bg-custom-background-100"
- noBorder
- borderOnFocus={false}
+ <RichTextReadOnlyEditor
+ initialValue={
+ activityItem?.new_value !== ""
+ ? (activityItem.new_value?.toString() as string)
+ : (activityItem.old_value?.toString() as string)
+ }
+ containerClassName="text-xs bg-custom-background-100"
/>
</div>
</div>
@@ -80,7 +82,9 @@ export const ActivityList: React.FC<Props> = observer((props) => {
const message =
activityItem.verb === "created" &&
- !["cycles", "modules", "attachment", "link", "estimate"].includes(activityItem.field) &&
+ !["cycles", "modules", "attachment", "link", "estimate"].includes(
+ activityItem.field?.toString() as string
+ ) &&
!activityItem.field ? (
<span>
created <IssueLink activity={activityItem} />
@@ -130,7 +134,7 @@ export const ActivityList: React.FC<Props> = observer((props) => {
<span className="text-gray font-medium">{activityItem.actor_detail.first_name} Bot</span>
) : (
<Link
- href={`/${activityItem.workspace_detail.slug}/profile/${activityItem.actor_detail.id}`}
+ href={`/${activityItem.workspace_detail?.slug}/profile/${activityItem.actor_detail.id}`}
>
<span className="text-gray font-medium">
{currentUser?.id === activityItem.actor_detail.id
diff --git a/web/components/profile/activity/profile-activity-list.tsx b/web/components/profile/activity/profile-activity-list.tsx
index b792671a08..41601d651c 100644
--- a/web/components/profile/activity/profile-activity-list.tsx
+++ b/web/components/profile/activity/profile-activity-list.tsx
@@ -3,16 +3,15 @@ import { observer } from "mobx-react";
import Link from "next/link";
import useSWR from "swr";
import { History, MessageSquare } from "lucide-react";
-import { RichReadOnlyEditor } from "@plane/rich-text-editor";
// hooks
import { ActivityIcon, ActivityMessage, IssueLink } from "@/components/core";
+import { RichTextReadOnlyEditor } from "@/components/editor/rich-text-editor/rich-text-read-only-editor";
import { ActivitySettingsLoader } from "@/components/ui";
import { USER_ACTIVITY } from "@/constants/fetch-keys";
import { calculateTimeAgo } from "@/helpers/date-time.helper";
import { useUser } from "@/hooks/store";
// services
import { UserService } from "@/services/user.service";
-// editor
// components
// ui
// helpers
@@ -94,11 +93,11 @@ export const ProfileActivityListPage: React.FC<Props> = observer((props) => {
</p>
</div>
<div className="issue-comments-section p-0">
- <RichReadOnlyEditor
- value={activityItem?.new_value !== "" ? activityItem.new_value : activityItem.old_value}
- customClassName="text-xs border border-custom-border-200 bg-custom-background-100"
- noBorder
- borderOnFocus={false}
+ <RichTextReadOnlyEditor
+ initialValue={
+ activityItem?.new_value !== "" ? activityItem.new_value : activityItem.old_value
+ }
+ containerClassName="text-xs bg-custom-background-100"
/>
</div>
</div>
diff --git a/web/components/project/card.tsx b/web/components/project/card.tsx
index 81813f3d0f..0540273ebc 100644
--- a/web/components/project/card.tsx
+++ b/web/components/project/card.tsx
@@ -3,7 +3,6 @@ import { observer } from "mobx-react-lite";
import Link from "next/link";
import { useRouter } from "next/router";
import { ArchiveRestoreIcon, Check, LinkIcon, Lock, Pencil, Star, Trash2 } from "lucide-react";
-import { cn } from "@plane/editor-core";
import type { IProject } from "@plane/types";
// ui
import { Avatar, AvatarGroup, Button, Tooltip, TOAST_TYPE, setToast, setPromiseToast } from "@plane/ui";
@@ -11,6 +10,7 @@ import { Avatar, AvatarGroup, Button, Tooltip, TOAST_TYPE, setToast, setPromiseT
import { ArchiveRestoreProjectModal, DeleteProjectModal, JoinProjectModal, ProjectLogo } from "@/components/project";
// helpers
import { EUserProjectRoles } from "@/constants/project";
+import { cn } from "@/helpers/common.helper";
import { renderFormattedDate } from "@/helpers/date-time.helper";
import { copyUrlToClipboard } from "@/helpers/string.helper";
// hooks
diff --git a/web/constants/editor.ts b/web/constants/editor.ts
new file mode 100644
index 0000000000..d80da201cb
--- /dev/null
+++ b/web/constants/editor.ts
@@ -0,0 +1,98 @@
+import {
+ Bold,
+ Code2,
+ Heading1,
+ Heading2,
+ Heading3,
+ Image,
+ Italic,
+ List,
+ ListOrdered,
+ ListTodo,
+ LucideIcon,
+ Quote,
+ Strikethrough,
+ Table,
+ Underline,
+} from "lucide-react";
+// editor
+import { EditorMenuItemNames } from "@plane/document-editor";
+
+type TEditorTypes = "lite" | "document";
+
+export type ToolbarMenuItem = {
+ key: EditorMenuItemNames;
+ name: string;
+ icon: LucideIcon;
+ shortcut?: string[];
+ editors: TEditorTypes[];
+};
+
+export const BASIC_MARK_ITEMS: ToolbarMenuItem[] = [
+ { key: "H1", name: "Heading 1", icon: Heading1, editors: ["document"] },
+ { key: "H2", name: "Heading 2", icon: Heading2, editors: ["document"] },
+ { key: "H3", name: "Heading 3", icon: Heading3, editors: ["document"] },
+ { key: "bold", name: "Bold", icon: Bold, shortcut: ["Cmd", "B"], editors: ["lite", "document"] },
+ { key: "italic", name: "Italic", icon: Italic, shortcut: ["Cmd", "I"], editors: ["lite", "document"] },
+ { key: "underline", name: "Underline", icon: Underline, shortcut: ["Cmd", "U"], editors: ["lite", "document"] },
+ {
+ key: "strike",
+ name: "Strikethrough",
+ icon: Strikethrough,
+ shortcut: ["Cmd", "Shift", "S"],
+ editors: ["lite", "document"],
+ },
+];
+
+export const LIST_ITEMS: ToolbarMenuItem[] = [
+ {
+ key: "bullet-list",
+ name: "Bulleted list",
+ icon: List,
+ shortcut: ["Cmd", "Shift", "7"],
+ editors: ["lite", "document"],
+ },
+ {
+ key: "ordered-list",
+ name: "Numbered list",
+ icon: ListOrdered,
+ shortcut: ["Cmd", "Shift", "8"],
+ editors: ["lite", "document"],
+ },
+ {
+ key: "To-do List",
+ name: "To-do list",
+ icon: ListTodo,
+ shortcut: ["Cmd", "Shift", "9"],
+ editors: ["lite", "document"],
+ },
+];
+
+export const USER_ACTION_ITEMS: ToolbarMenuItem[] = [
+ { key: "quote", name: "Quote", icon: Quote, editors: ["lite", "document"] },
+ { key: "code", name: "Code", icon: Code2, editors: ["lite", "document"] },
+];
+
+export const COMPLEX_ITEMS: ToolbarMenuItem[] = [
+ { key: "table", name: "Table", icon: Table, editors: ["document"] },
+ { key: "image", name: "Image", icon: Image, editors: ["lite", "document"] },
+];
+
+export const TOOLBAR_ITEMS: {
+ [editorType in TEditorTypes]: {
+ [key: string]: ToolbarMenuItem[];
+ };
+} = {
+ lite: {
+ basic: BASIC_MARK_ITEMS.filter((item) => item.editors.includes("lite")),
+ list: LIST_ITEMS.filter((item) => item.editors.includes("lite")),
+ userAction: USER_ACTION_ITEMS.filter((item) => item.editors.includes("lite")),
+ complex: COMPLEX_ITEMS.filter((item) => item.editors.includes("lite")),
+ },
+ document: {
+ basic: BASIC_MARK_ITEMS.filter((item) => item.editors.includes("document")),
+ list: LIST_ITEMS.filter((item) => item.editors.includes("document")),
+ userAction: USER_ACTION_ITEMS.filter((item) => item.editors.includes("document")),
+ complex: COMPLEX_ITEMS.filter((item) => item.editors.includes("document")),
+ },
+};
diff --git a/web/constants/empty-state.ts b/web/constants/empty-state.ts
index 20589db002..6130674fd4 100644
--- a/web/constants/empty-state.ts
+++ b/web/constants/empty-state.ts
@@ -66,12 +66,9 @@ export enum EmptyStateType {
PROJECT_ARCHIVED_NO_MODULES = "project-archived-no-modules",
PROJECT_VIEW = "project-view",
PROJECT_PAGE = "project-page",
- PROJECT_PAGE_ALL = "project-page-all",
- PROJECT_PAGE_FAVORITES = "project-page-favorites",
PROJECT_PAGE_PRIVATE = "project-page-private",
- PROJECT_PAGE_SHARED = "project-page-shared",
+ PROJECT_PAGE_PUBLIC = "project-page-public",
PROJECT_PAGE_ARCHIVED = "project-page-archived",
- PROJECT_PAGE_RECENT = "project-page-recent",
COMMAND_K_SEARCH_EMPTY_STATE = "command-k-search-empty-state",
ISSUE_RELATION_SEARCH_EMPTY_STATE = "issue-relation-search-empty-state",
@@ -498,30 +495,17 @@ const emptyStateDetails = {
accessType: "project",
access: EUserProjectRoles.MEMBER,
},
- [EmptyStateType.PROJECT_PAGE_ALL]: {
- key: EmptyStateType.PROJECT_PAGE_ALL,
- title: "Write a note, a doc, or a full knowledge base",
- description:
- "Pages help you organise your thoughts to create wikis, discussions or even document heated takes for your project. Use it wisely!",
- path: "/empty-state/pages/all",
- },
- [EmptyStateType.PROJECT_PAGE_FAVORITES]: {
- key: EmptyStateType.PROJECT_PAGE_FAVORITES,
- title: "No favorite pages yet",
- description: "Favorites for quick access? mark them and find them right here.",
- path: "/empty-state/pages/favorites",
- },
[EmptyStateType.PROJECT_PAGE_PRIVATE]: {
key: EmptyStateType.PROJECT_PAGE_PRIVATE,
title: "No private pages yet",
description: "Keep your private thoughts here. When you're ready to share, the team's just a click away.",
path: "/empty-state/pages/private",
},
- [EmptyStateType.PROJECT_PAGE_SHARED]: {
- key: EmptyStateType.PROJECT_PAGE_SHARED,
- title: "No shared pages yet",
+ [EmptyStateType.PROJECT_PAGE_PUBLIC]: {
+ key: EmptyStateType.PROJECT_PAGE_PUBLIC,
+ title: "No public pages yet",
description: "See pages shared with everyone in your project right here.",
- path: "/empty-state/pages/shared",
+ path: "/empty-state/pages/public",
},
[EmptyStateType.PROJECT_PAGE_ARCHIVED]: {
key: EmptyStateType.PROJECT_PAGE_ARCHIVED,
@@ -529,18 +513,6 @@ const emptyStateDetails = {
description: "Archive pages not on your radar. Access them here when needed.",
path: "/empty-state/pages/archived",
},
- [EmptyStateType.PROJECT_PAGE_RECENT]: {
- key: EmptyStateType.PROJECT_PAGE_RECENT,
- title: "Write a note, a doc, or a full knowledge base",
- description:
- "Pages help you organise your thoughts to create wikis, discussions or even document heated takes for your project. Use it wisely! Pages will be sorted and grouped by last updated",
- path: "/empty-state/pages/recent",
- primaryButton: {
- text: "Create new page",
- },
- accessType: "project",
- access: EUserProjectRoles.MEMBER,
- },
[EmptyStateType.COMMAND_K_SEARCH_EMPTY_STATE]: {
key: EmptyStateType.COMMAND_K_SEARCH_EMPTY_STATE,
diff --git a/web/constants/issue.ts b/web/constants/issue.ts
index 7e0fd7a06c..c2ac093c04 100644
--- a/web/constants/issue.ts
+++ b/web/constants/issue.ts
@@ -38,6 +38,11 @@ export enum EIssueFilterType {
KANBAN_FILTERS = "kanban_filters",
}
+export enum EIssueCommentAccessSpecifier {
+ EXTERNAL = "EXTERNAL",
+ INTERNAL = "INTERNAL",
+}
+
export const ISSUE_PRIORITIES: {
key: TIssuePriorities;
title: string;
diff --git a/web/constants/page.ts b/web/constants/page.ts
index 4b303ae73b..04b95c163b 100644
--- a/web/constants/page.ts
+++ b/web/constants/page.ts
@@ -1,54 +1,35 @@
-import { Globe2, LayoutGrid, List, Lock } from "lucide-react";
+import { Globe2, Lock, LucideIcon } from "lucide-react";
+// types
+import { TPageFiltersSortKey, TPageFiltersSortBy } from "@plane/types";
-export const PAGE_VIEW_LAYOUTS = [
- {
- key: "list",
- icon: List,
- title: "List layout",
- },
- {
- key: "detailed",
- icon: LayoutGrid,
- title: "Detailed layout",
- },
+export enum EPageAccess {
+ PUBLIC = 0,
+ PRIVATE = 1,
+}
+
+export const PAGE_ACCESS_SPECIFIERS: {
+ key: EPageAccess;
+ label: string;
+ icon: LucideIcon;
+}[] = [
+ { key: EPageAccess.PUBLIC, label: "Public", icon: Globe2 },
+ { key: EPageAccess.PRIVATE, label: "Private", icon: Lock },
];
-export const PAGE_TABS_LIST: { key: string; title: string }[] = [
- {
- key: "recent",
- title: "Recent",
- },
- {
- key: "all",
- title: "All",
- },
- {
- key: "favorites",
- title: "Favorites",
- },
- {
- key: "private",
- title: "Private",
- },
- {
- key: "shared",
- title: "Shared",
- },
- {
- key: "archived-pages",
- title: "Archived",
- },
+export const PAGE_SORTING_KEY_OPTIONS: {
+ key: TPageFiltersSortKey;
+ label: string;
+}[] = [
+ { key: "name", label: "Name" },
+ { key: "created_at", label: "Date created" },
+ { key: "updated_at", label: "Date modified" },
+ { key: "opened_at", label: "Last opened" },
];
-export const PAGE_ACCESS_SPECIFIERS: { key: number; label: string; icon: any }[] = [
- {
- key: 0,
- label: "Public",
- icon: Globe2,
- },
- {
- key: 1,
- label: "Private",
- icon: Lock,
- },
+export const PAGE_SORT_BY_OPTIONS: {
+ key: TPageFiltersSortBy;
+ label: string;
+}[] = [
+ { key: "asc", label: "Ascending" },
+ { key: "desc", label: "Descending" },
];
diff --git a/web/helpers/cycle.helper.ts b/web/helpers/cycle.helper.ts
index 8e3506120e..97cb7348c0 100644
--- a/web/helpers/cycle.helper.ts
+++ b/web/helpers/cycle.helper.ts
@@ -1,9 +1,8 @@
import sortBy from "lodash/sortBy";
+import { ICycle, TCycleFilters } from "@plane/types";
// helpers
-import { satisfiesDateFilter } from "@/helpers/filter.helper";
import { getDate } from "@/helpers/date-time.helper";
-// types
-import { ICycle, TCycleFilters } from "@plane/types";
+import { satisfiesDateFilter } from "@/helpers/filter.helper";
/**
* @description orders cycles based on their status
diff --git a/web/helpers/filter.helper.ts b/web/helpers/filter.helper.ts
index 2b8212f025..433a69085a 100644
--- a/web/helpers/filter.helper.ts
+++ b/web/helpers/filter.helper.ts
@@ -5,7 +5,7 @@ import { getDate } from "./date-time.helper";
// import { IIssueFilterOptions } from "@plane/types";
type TFilters = {
- [key: string]: string[] | null;
+ [key: string]: boolean | string[] | null;
};
/**
@@ -16,13 +16,13 @@ type TFilters = {
export const calculateTotalFilters = (filters: TFilters): number =>
filters && Object.keys(filters).length > 0
? Object.keys(filters)
- .map((key) =>
- filters[key as keyof TFilters] !== null
- ? isNaN((filters[key as keyof TFilters] as string[]).length)
- ? 0
- : (filters[key as keyof TFilters] as string[]).length
- : 0
- )
+ .map((key) => {
+ const value = filters[key as keyof TFilters];
+ if (value === null) return 0;
+ if (Array.isArray(value)) return value.length;
+ if (typeof value === "boolean") return value ? 1 : 0;
+ return 0;
+ })
.reduce((curr, prev) => curr + prev, 0)
: 0;
diff --git a/web/helpers/module.helper.ts b/web/helpers/module.helper.ts
index 31cfff0ff5..14e7f04889 100644
--- a/web/helpers/module.helper.ts
+++ b/web/helpers/module.helper.ts
@@ -1,9 +1,8 @@
import sortBy from "lodash/sortBy";
+import { IModule, TModuleDisplayFilters, TModuleFilters, TModuleOrderByOptions } from "@plane/types";
// helpers
-import { satisfiesDateFilter } from "@/helpers/filter.helper";
import { getDate } from "@/helpers/date-time.helper";
-// types
-import { IModule, TModuleDisplayFilters, TModuleFilters, TModuleOrderByOptions } from "@plane/types";
+import { satisfiesDateFilter } from "@/helpers/filter.helper";
/**
* @description orders modules based on their status
diff --git a/web/helpers/page.helper.ts b/web/helpers/page.helper.ts
new file mode 100644
index 0000000000..a8d34af32c
--- /dev/null
+++ b/web/helpers/page.helper.ts
@@ -0,0 +1,74 @@
+import sortBy from "lodash/sortBy";
+import { TPage, TPageFilterProps, TPageFiltersSortBy, TPageFiltersSortKey, TPageNavigationTabs } from "@plane/types";
+// helpers
+import { getDate } from "@/helpers/date-time.helper";
+import { satisfiesDateFilter } from "@/helpers/filter.helper";
+
+/**
+ * @description filters pages based on the page type
+ * @param {TPageNavigationTabs} pageType
+ * @param {TPage[]} pages
+ * @returns {TPage[]}
+ */
+export const filterPagesByPageType = (pageType: TPageNavigationTabs, pages: TPage[]): TPage[] =>
+ pages.filter((page) => {
+ if (pageType === "public") return page.access === 0 && !page.archived_at;
+ if (pageType === "private") return page.access === 1 && !page.archived_at;
+ if (pageType === "archived") return page.archived_at;
+ return true;
+ });
+
+/**
+ * @description orders pages based on their status
+ * @param {TPage[]} pages
+ * @param {TPageFiltersSortKey | undefined} sortByKey
+ * @param {TPageFiltersSortBy} sortByOrder
+ * @returns {TPage[]}
+ */
+export const orderPages = (
+ pages: TPage[],
+ sortByKey: TPageFiltersSortKey | undefined,
+ sortByOrder: TPageFiltersSortBy
+): TPage[] => {
+ let orderedPages: TPage[] = [];
+ if (pages.length === 0 || !sortByKey) return [];
+
+ if (sortByKey === "name") {
+ orderedPages = sortBy(pages, [(m) => m.name?.toLowerCase()]);
+ if (sortByOrder === "desc") orderedPages = orderedPages.reverse();
+ }
+ if (sortByKey === "created_at") {
+ orderedPages = sortBy(pages, [(m) => m.created_at]);
+ if (sortByOrder === "desc") orderedPages = orderedPages.reverse();
+ }
+ if (sortByKey === "updated_at") {
+ orderedPages = sortBy(pages, [(m) => m.updated_at]);
+ if (sortByOrder === "desc") orderedPages = orderedPages.reverse();
+ }
+
+ return orderedPages;
+};
+
+/**
+ * @description filters pages based on the filters
+ * @param {TPage} page
+ * @param {TPageFilterProps | undefined} filters
+ * @returns {boolean}
+ */
+export const shouldFilterPage = (page: TPage, filters: TPageFilterProps | undefined): boolean => {
+ let fallsInFilters = true;
+ Object.keys(filters ?? {}).forEach((key) => {
+ const filterKey = key as keyof TPageFilterProps;
+ if (filterKey === "created_by" && filters?.created_by && filters.created_by.length > 0)
+ fallsInFilters = fallsInFilters && filters.created_by.includes(`${page.created_by}`);
+ if (filterKey === "created_at" && filters?.created_at && filters.created_at.length > 0) {
+ const createdDate = getDate(page.created_at);
+ filters?.created_at.forEach((dateFilter) => {
+ fallsInFilters = fallsInFilters && !!createdDate && satisfiesDateFilter(createdDate, dateFilter);
+ });
+ }
+ });
+ if (filters?.favorites && !page.is_favorite) fallsInFilters = false;
+
+ return fallsInFilters;
+};
diff --git a/web/hooks/store/index.ts b/web/hooks/store/index.ts
index 950ae00f12..f98ffcbcb6 100644
--- a/web/hooks/store/index.ts
+++ b/web/hooks/store/index.ts
@@ -10,8 +10,11 @@ export * from "./use-label";
export * from "./use-member";
export * from "./use-mention";
export * from "./use-module";
+
+export * from "./pages/use-project-page";
+export * from "./pages/use-page";
+
export * from "./use-module-filter";
-export * from "./use-page";
export * from "./use-project-filter";
export * from "./use-project-publish";
export * from "./use-project-state";
diff --git a/web/hooks/store/use-project-specific-pages.ts b/web/hooks/store/pages/use-page.ts
similarity index 51%
rename from web/hooks/store/use-project-specific-pages.ts
rename to web/hooks/store/pages/use-page.ts
index 6423467802..608c00955b 100644
--- a/web/hooks/store/use-project-specific-pages.ts
+++ b/web/hooks/store/pages/use-page.ts
@@ -1,11 +1,14 @@
import { useContext } from "react";
-// mobx store
+// context
import { StoreContext } from "@/contexts/store-context";
-// types
-import { IProjectPageStore } from "@/store/project-page.store";
+// mobx store
+import { IPageStore } from "@/store/pages/page.store";
-export const useProjectPages = (): IProjectPageStore => {
+export const usePage = (pageId: string | undefined): IPageStore => {
const context = useContext(StoreContext);
if (context === undefined) throw new Error("usePage must be used within StoreProvider");
- return context.projectPages;
+
+ if (!pageId) return {} as IPageStore;
+
+ return context.projectPages.data?.[pageId] ?? {};
};
diff --git a/web/hooks/store/pages/use-project-page.ts b/web/hooks/store/pages/use-project-page.ts
new file mode 100644
index 0000000000..1dcca20ecb
--- /dev/null
+++ b/web/hooks/store/pages/use-project-page.ts
@@ -0,0 +1,14 @@
+import { useContext } from "react";
+// context
+import { StoreContext } from "contexts/store-context";
+// mobx store
+import { IProjectPageStore } from "store/pages/project-page.store";
+
+export const useProjectPages = (projectId: string | undefined): IProjectPageStore => {
+ const context = useContext(StoreContext);
+ if (context === undefined) throw new Error("useProjectPage must be used within StoreProvider");
+
+ if (!projectId) throw new Error("projectId must be passed as a property");
+
+ return context.projectPages;
+};
diff --git a/web/hooks/store/use-mention.ts b/web/hooks/store/use-mention.ts
index 9bbd75c514..b6a1338370 100644
--- a/web/hooks/store/use-mention.ts
+++ b/web/hooks/store/use-mention.ts
@@ -1,11 +1,97 @@
-import { useContext } from "react";
-// mobx store
-import { StoreContext } from "@/contexts/store-context";
+import { useRef, useEffect } from "react";
// types
-import { IMentionStore } from "@/store/mention.store";
+import { IUser, IUserLite } from "@plane/types";
+import { useMember } from "./use-member";
-export const useMention = (): IMentionStore => {
- const context = useContext(StoreContext);
- if (context === undefined) throw new Error("useMention must be used within StoreProvider");
- return context.mention;
+type Props = {
+ workspaceSlug?: string;
+ projectId?: string;
+ members?: IUserLite[] | undefined;
+ user?: IUser | undefined;
+};
+
+export const useMention = ({ workspaceSlug, projectId, members, user }: Props) => {
+ const projectMembersRef = useRef<IUserLite[] | undefined>();
+ const userRef = useRef<IUser | undefined>();
+
+ const {
+ project: { fetchProjectMembers },
+ } = useMember();
+
+ useEffect(() => {
+ if (members) projectMembersRef.current = members;
+ else {
+ if (!workspaceSlug || !projectId) return;
+ fetchProjectMembers(workspaceSlug.toString(), projectId.toString());
+ }
+ }, [fetchProjectMembers, members, projectId, workspaceSlug]);
+
+ useEffect(() => {
+ if (userRef) userRef.current = user;
+ }, [user]);
+
+ const waitForUserData = async () =>
+ new Promise<IUser>((resolve) => {
+ const checkData = () => {
+ if (userRef.current) resolve(userRef.current);
+ else setTimeout(checkData, 100);
+ };
+ checkData();
+ });
+
+ const mentionHighlights = async () => {
+ if (user && userRef.current) {
+ return [userRef.current.id];
+ } else {
+ const userData = await waitForUserData();
+ return [userData.id];
+ }
+ };
+
+ // Polling function to wait for projectMembersRef.current to be populated
+ const waitForData = async () =>
+ new Promise<IUserLite[]>((resolve) => {
+ const checkData = () => {
+ if (projectMembersRef.current && projectMembersRef.current.length > 0) {
+ resolve(projectMembersRef.current);
+ } else {
+ setTimeout(checkData, 100); // Check every 100ms
+ }
+ };
+ checkData();
+ });
+
+ const mentionSuggestions = async () => {
+ if (members && projectMembersRef.current && projectMembersRef.current.length > 0) {
+ // If data is already available, return it immediately
+ return projectMembersRef.current.map((memberDetails) => ({
+ entity_name: "user_mention",
+ entity_identifier: `${memberDetails?.id}`,
+ id: `${memberDetails?.id}`,
+ type: "User",
+ title: `${memberDetails?.display_name}`,
+ subtitle: memberDetails?.email ?? "",
+ avatar: `${memberDetails?.avatar}`,
+ redirect_uri: `/${workspaceSlug}/profile/${memberDetails?.id}`,
+ }));
+ } else {
+ // Wait for data to be available
+ const membersList = await waitForData();
+ return membersList.map((memberDetails) => ({
+ entity_name: "user_mention",
+ entity_identifier: `${memberDetails?.id}`,
+ id: `${memberDetails?.id}`,
+ type: "User",
+ title: `${memberDetails?.display_name}`,
+ subtitle: memberDetails?.email ?? "",
+ avatar: `${memberDetails?.avatar}`,
+ redirect_uri: `/${workspaceSlug}/profile/${memberDetails?.id}`,
+ }));
+ }
+ };
+
+ return {
+ mentionSuggestions,
+ mentionHighlights,
+ };
};
diff --git a/web/hooks/store/use-page.ts b/web/hooks/store/use-page.ts
deleted file mode 100644
index 2df7e0de62..0000000000
--- a/web/hooks/store/use-page.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { useContext } from "react";
-// mobx store
-import { StoreContext } from "@/contexts/store-context";
-
-export const usePage = (pageId: string) => {
- const context = useContext(StoreContext);
- if (context === undefined) throw new Error("usePage must be used within StoreProvider");
-
- const { projectPageMap, projectArchivedPageMap } = context.projectPages;
-
- const { projectId, workspaceSlug } = context.app.router;
- if (!projectId || !workspaceSlug) {
- console.log("usePage must be used within ProjectProvider");
- return;
- }
-
- if (projectPageMap[projectId] && projectPageMap[projectId][pageId]) return projectPageMap[projectId][pageId];
- else if (projectArchivedPageMap[projectId] && projectArchivedPageMap[projectId][pageId])
- return projectArchivedPageMap[projectId][pageId];
- else return;
-};
diff --git a/web/hooks/store/use-project-page.ts b/web/hooks/store/use-project-page.ts
deleted file mode 100644
index 50a70bdbb2..0000000000
--- a/web/hooks/store/use-project-page.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { useContext } from "react";
-// mobx store
-import { StoreContext } from "@/contexts/store-context";
-import { IProjectPageStore } from "@/store/project-page.store";
-
-export const useProjectPages = (): IProjectPageStore => {
- const context = useContext(StoreContext);
- if (context === undefined) throw new Error("useProjectPublish must be used within StoreProvider");
- return context.projectPages;
-};
diff --git a/web/pages/[workspaceSlug]/projects/[projectId]/archives/issues/[archivedIssueId].tsx b/web/pages/[workspaceSlug]/projects/[projectId]/archives/issues/[archivedIssueId].tsx
index 0ff7d7fc50..d10838d969 100644
--- a/web/pages/[workspaceSlug]/projects/[projectId]/archives/issues/[archivedIssueId].tsx
+++ b/web/pages/[workspaceSlug]/projects/[projectId]/archives/issues/[archivedIssueId].tsx
@@ -39,7 +39,7 @@ const ArchivedIssueDetailsPage: NextPageWithLayout = observer(() => {
membership: { currentProjectRole },
} = useUser();
- const { isLoading } = useSWR(
+ const { isLoading, data: swrArchivedIssueDetails } = useSWR(
workspaceSlug && projectId && archivedIssueId
? `ARCHIVED_ISSUE_DETAIL_${workspaceSlug}_${projectId}_${archivedIssueId}`
: null,
@@ -123,6 +123,7 @@ const ArchivedIssueDetailsPage: NextPageWithLayout = observer(() => {
)}
{workspaceSlug && projectId && archivedIssueId && (
<IssueDetailRoot
+ swrIssueDetails={swrArchivedIssueDetails}
workspaceSlug={workspaceSlug.toString()}
projectId={projectId.toString()}
issueId={archivedIssueId.toString()}
diff --git a/web/pages/[workspaceSlug]/projects/[projectId]/issues/[issueId].tsx b/web/pages/[workspaceSlug]/projects/[projectId]/issues/[issueId].tsx
index 539373652a..27dfe92efa 100644
--- a/web/pages/[workspaceSlug]/projects/[projectId]/issues/[issueId].tsx
+++ b/web/pages/[workspaceSlug]/projects/[projectId]/issues/[issueId].tsx
@@ -27,7 +27,7 @@ const IssueDetailsPage: NextPageWithLayout = observer(() => {
const { getProjectById } = useProject();
const { theme: themeStore } = useApplication();
// fetching issue details
- const { isLoading } = useSWR(
+ const { isLoading, data: swrIssueDetails } = useSWR(
workspaceSlug && projectId && issueId ? `ISSUE_DETAIL_${workspaceSlug}_${projectId}_${issueId}` : null,
workspaceSlug && projectId && issueId
? () => fetchIssue(workspaceSlug.toString(), projectId.toString(), issueId.toString())
@@ -77,6 +77,7 @@ const IssueDetailsPage: NextPageWithLayout = observer(() => {
projectId &&
issueId && (
<IssueDetailRoot
+ swrIssueDetails={swrIssueDetails}
workspaceSlug={workspaceSlug.toString()}
projectId={projectId.toString()}
issueId={issueId.toString()}
diff --git a/web/pages/[workspaceSlug]/projects/[projectId]/pages/[pageId].tsx b/web/pages/[workspaceSlug]/projects/[projectId]/pages/[pageId].tsx
index 02fb238fea..3f165c1288 100644
--- a/web/pages/[workspaceSlug]/projects/[projectId]/pages/[pageId].tsx
+++ b/web/pages/[workspaceSlug]/projects/[projectId]/pages/[pageId].tsx
@@ -1,370 +1,149 @@
import { ReactElement, useEffect, useRef, useState } from "react";
import { observer } from "mobx-react-lite";
import { useRouter } from "next/router";
-import { Controller, useForm } from "react-hook-form";
+import { useForm } from "react-hook-form";
import useSWR from "swr";
-import { Sparkle } from "lucide-react";
-import { DocumentEditorWithRef, DocumentReadOnlyEditorWithRef } from "@plane/document-editor";
-import { IPage } from "@plane/types";
-// hooks
-
+// document-editor
+import { EditorRefApi, useEditorMarkings } from "@plane/document-editor";
+// types
+import { TPage } from "@plane/types";
+// ui
import { Spinner, TOAST_TYPE, setToast } from "@plane/ui";
-import { GptAssistantPopover, PageHead } from "@/components/core";
-import { PageDetailsHeader } from "@/components/headers/page-details";
+// components
+import { PageHead } from "@/components/core";
+import { PageDetailsHeader } from "@/components/headers";
import { IssuePeekOverview } from "@/components/issues";
-import { EUserProjectRoles } from "@/constants/project";
-import { getDate } from "@/helpers/date-time.helper";
-import { useApplication, usePage, useUser, useWorkspace } from "@/hooks/store";
-import { useProjectPages } from "@/hooks/store/use-project-specific-pages";
-import useReloadConfirmations from "@/hooks/use-reload-confirmation";
-// services
+import { PageEditorBody, PageEditorHeaderRoot } from "@/components/pages";
+// hooks
+import { usePage, useProjectPages } from "@/hooks/store";
+// layouts
import { AppLayout } from "@/layouts/app-layout";
+// lib
import { NextPageWithLayout } from "@/lib/types";
-import { FileService } from "@/services/file.service";
-// layouts
-// components
-// ui
-// assets
-// helpers
-// types
-// fetch-keys
-// constants
-
-// services
-const fileService = new FileService();
const PageDetailsPage: NextPageWithLayout = observer(() => {
// states
- const [gptModalOpen, setGptModal] = useState(false);
+ const [sidePeekVisible, setSidePeekVisible] = useState(true);
+ const [editorReady, setEditorReady] = useState(false);
+ const [readOnlyEditorReady, setReadOnlyEditorReady] = useState(false);
// refs
- const editorRef = useRef<any>(null);
+ const editorRef = useRef<EditorRefApi>(null);
+ const readOnlyEditorRef = useRef<EditorRefApi>(null);
// router
const router = useRouter();
-
const { workspaceSlug, projectId, pageId } = router.query;
- const workspaceStore = useWorkspace();
- const workspaceId = workspaceStore.getWorkspaceBySlug(workspaceSlug as string)?.id as string;
-
// store hooks
- const {
- config: { envConfig },
- } = useApplication();
- const {
- currentUser,
- membership: { currentProjectRole },
- } = useUser();
-
- const { handleSubmit, getValues, control, reset } = useForm<IPage>({
- defaultValues: { name: "", description_html: "" },
+ const { createPage, getPageById } = useProjectPages(projectId?.toString() ?? "");
+ const pageStore = usePage(pageId?.toString() ?? "");
+ // editor markings hook
+ const { markings, updateMarkings } = useEditorMarkings();
+ // form info
+ const { handleSubmit, getValues, control } = useForm<TPage>({
+ defaultValues: {
+ name: "",
+ description_html: "",
+ },
});
- const {
- archivePage: archivePageAction,
- restorePage: restorePageAction,
- createPage: createPageAction,
- projectPageMap,
- projectArchivedPageMap,
- fetchProjectPages,
- fetchArchivedProjectPages,
- } = useProjectPages();
-
- useSWR(
- workspaceSlug && projectId ? `ALL_PAGES_LIST_${projectId}` : null,
- workspaceSlug && projectId && !projectPageMap[projectId as string] && !projectArchivedPageMap[projectId as string]
- ? () => fetchProjectPages(workspaceSlug.toString(), projectId.toString())
- : null
- );
- // fetching archived pages from API
- useSWR(
- workspaceSlug && projectId ? `ALL_ARCHIVED_PAGES_LIST_${projectId}` : null,
- workspaceSlug && projectId && !projectArchivedPageMap[projectId as string] && !projectPageMap[projectId as string]
- ? () => fetchArchivedProjectPages(workspaceSlug.toString(), projectId.toString())
- : null
+ // fetching page details
+ const { data: swrPageDetails } = useSWR(
+ pageId ? `PAGE_DETAILS_${pageId}` : null,
+ pageId ? () => getPageById(pageId.toString()) : null,
+ {
+ revalidateIfStale: false,
+ revalidateOnFocus: true,
+ revalidateOnReconnect: true,
+ }
);
-
- const pageStore = usePage(pageId as string);
-
- const { setShowAlert } = useReloadConfirmations(pageStore?.isSubmitting === "submitting");
-
useEffect(
() => () => {
- if (pageStore) {
- pageStore.cleanup();
- }
+ if (pageStore.cleanup) pageStore.cleanup();
},
[pageStore]
);
- if (!pageStore) {
+ const handleEditorReady = (value: boolean) => setEditorReady(value);
+
+ const handleReadOnlyEditorReady = () => setReadOnlyEditorReady(true);
+
+ if (!pageStore || !pageStore.id)
return (
- <div className="grid h-full w-full place-items-center">
+ <div className="h-full w-full grid place-items-center">
<Spinner />
</div>
);
- }
- // We need to get the values of title and description from the page store but we don't have to subscribe to those values
+ // we need to get the values of title and description from the page store but we don't have to subscribe to those values
const pageTitle = pageStore?.name;
- const pageDescription = pageStore?.description_html;
- const {
- lockPage: lockPageAction,
- unlockPage: unlockPageAction,
- updateName: updateNameAction,
- updateDescription: updateDescriptionAction,
- id: pageIdMobx,
- isSubmitting,
- setIsSubmitting,
- owned_by,
- is_locked,
- archived_at,
- created_at,
- created_by,
- updated_at,
- updated_by,
- } = pageStore;
- const updatePage = async (formData: IPage) => {
- if (!workspaceSlug || !projectId || !pageId) return;
- updateDescriptionAction(formData.description_html);
- };
+ const handleCreatePage = async (payload: Partial<TPage>) => await createPage(payload);
- const handleAiAssistance = async (response: string) => {
- if (!workspaceSlug || !projectId || !pageId) return;
-
- editorRef.current?.setEditorValueAtCursorPosition(response);
- };
-
- const actionCompleteAlert = ({
- title,
- message,
- type,
- }: {
- title: string;
- message: string;
- type: "success" | "error" | "warning" | "info";
- }) => {
- setToast({
- title,
- message,
- type: type as TOAST_TYPE,
- });
- };
-
- const updatePageTitle = (title: string) => {
- if (!workspaceSlug || !projectId || !pageId) return;
- updateNameAction(title);
- };
-
- const createPage = async (payload: Partial<IPage>) => {
- if (!workspaceSlug || !projectId) return;
- await createPageAction(workspaceSlug as string, projectId as string, payload);
+ const handleUpdatePage = async (formData: TPage) => {
+ let updatedDescription = formData.description_html;
+ if (!updatedDescription || updatedDescription.trim() === "") updatedDescription = "<p></p>";
+ pageStore.updateDescription(updatedDescription);
};
- // ================ Page Menu Actions ==================
- const duplicate_page = async () => {
+ const handleDuplicatePage = async () => {
const currentPageValues = getValues();
if (!currentPageValues?.description_html) {
// TODO: We need to get latest data the above variable will give us stale data
- currentPageValues.description_html = pageDescription as string;
+ currentPageValues.description_html = pageStore.description_html;
}
- const formData: Partial<IPage> = {
- name: "Copy of " + pageTitle,
+ const formData: Partial<TPage> = {
+ name: "Copy of " + pageStore.name,
description_html: currentPageValues.description_html,
};
- try {
- await createPage(formData);
- } catch (error) {
- actionCompleteAlert({
- title: `Page could not be duplicated`,
- message: `Sorry, page could not be duplicated, please try again later`,
- type: "error",
- });
- }
- };
-
- const archivePage = async () => {
- if (!workspaceSlug || !projectId || !pageId) return;
- try {
- await archivePageAction(workspaceSlug as string, projectId as string, pageId as string);
- } catch (error) {
- actionCompleteAlert({
- title: `Page could not be archived`,
- message: `Sorry, page could not be archived, please try again later`,
- type: "error",
- });
- }
- };
-
- const unArchivePage = async () => {
- if (!workspaceSlug || !projectId || !pageId) return;
- try {
- await restorePageAction(workspaceSlug as string, projectId as string, pageId as string);
- } catch (error) {
- actionCompleteAlert({
- title: `Page could not be restored`,
- message: `Sorry, page could not be restored, please try again later`,
- type: "error",
- });
- }
- };
-
- const lockPage = async () => {
- if (!workspaceSlug || !projectId || !pageId) return;
- try {
- await lockPageAction();
- } catch (error) {
- actionCompleteAlert({
- title: `Page could not be locked`,
- message: `Sorry, page could not be locked, please try again later`,
- type: "error",
- });
- }
- };
-
- const unlockPage = async () => {
- if (!workspaceSlug || !projectId || !pageId) return;
- try {
- await unlockPageAction();
- } catch (error) {
- actionCompleteAlert({
- title: `Page could not be unlocked`,
- message: `Sorry, page could not be unlocked, please try again later`,
- type: "error",
- });
- }
+ await handleCreatePage(formData)
+ .then((res) => router.push(`/${workspaceSlug}/projects/${projectId}/pages/${res?.id}`))
+ .catch(() =>
+ setToast({
+ type: TOAST_TYPE.ERROR,
+ title: "Error!",
+ message: "Page could not be duplicated. Please try again later.",
+ })
+ );
};
- const isPageReadOnly =
- is_locked ||
- archived_at ||
- (currentProjectRole && [EUserProjectRoles.VIEWER, EUserProjectRoles.GUEST].includes(currentProjectRole));
-
- const isCurrentUserOwner = owned_by === currentUser?.id;
-
- const userCanDuplicate =
- currentProjectRole && [EUserProjectRoles.ADMIN, EUserProjectRoles.MEMBER].includes(currentProjectRole);
- const userCanArchive = isCurrentUserOwner || currentProjectRole === EUserProjectRoles.ADMIN;
- const userCanLock =
- currentProjectRole && [EUserProjectRoles.ADMIN, EUserProjectRoles.MEMBER].includes(currentProjectRole);
-
- return pageIdMobx ? (
+ return (
<>
<PageHead title={pageTitle} />
<div className="flex h-full flex-col justify-between">
- <div className="h-full w-full overflow-hidden">
- {isPageReadOnly ? (
- <DocumentReadOnlyEditorWithRef
- onActionCompleteHandler={actionCompleteAlert}
- ref={editorRef}
- value={pageDescription}
- customClassName={"tracking-tight w-full px-0"}
- borderOnFocus={false}
- noBorder
- documentDetails={{
- title: pageTitle,
- created_by: created_by,
- created_on: getDate(created_at) ?? new Date(created_at ?? ""),
- last_updated_at: getDate(updated_at) ?? new Date(created_at ?? ""),
- last_updated_by: updated_by,
- }}
- pageLockConfig={userCanLock && !archived_at ? { action: unlockPage, is_locked: is_locked } : undefined}
- pageDuplicationConfig={userCanDuplicate && !archived_at ? { action: duplicate_page } : undefined}
- pageArchiveConfig={
- userCanArchive
- ? {
- action: archived_at ? unArchivePage : archivePage,
- is_archived: archived_at ? true : false,
- archived_at: getDate(archived_at),
- }
- : undefined
- }
+ <div className="h-full w-full flex-shrink-0 flex flex-col overflow-hidden">
+ {projectId && (
+ <PageEditorHeaderRoot
+ editorRef={editorRef}
+ readOnlyEditorRef={readOnlyEditorRef}
+ editorReady={editorReady}
+ readOnlyEditorReady={readOnlyEditorReady}
+ handleDuplicatePage={handleDuplicatePage}
+ markings={markings}
+ pageStore={pageStore}
+ projectId={projectId.toString()}
+ sidePeekVisible={sidePeekVisible}
+ setSidePeekVisible={(state) => setSidePeekVisible(state)}
/>
- ) : (
- <div className="relative h-full w-full overflow-hidden">
- <Controller
- name="description_html"
- control={control}
- render={({ field: { onChange } }) => (
- <DocumentEditorWithRef
- isSubmitting={isSubmitting}
- documentDetails={{
- title: pageTitle,
- created_by: created_by,
- created_on: getDate(created_at) ?? new Date(created_at ?? ""),
- last_updated_at: getDate(updated_at) ?? new Date(created_at ?? ""),
- last_updated_by: updated_by,
- }}
- uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
- deleteFile={fileService.getDeleteImageFunction(workspaceId)}
- restoreFile={fileService.getRestoreImageFunction(workspaceId)}
- value={pageDescription}
- setShouldShowAlert={setShowAlert}
- cancelUploadImage={fileService.cancelUpload}
- ref={editorRef}
- debouncedUpdatesEnabled={false}
- setIsSubmitting={setIsSubmitting}
- updatePageTitle={updatePageTitle}
- onActionCompleteHandler={actionCompleteAlert}
- customClassName="tracking-tight self-center h-full w-full right-[0.675rem]"
- onChange={(_description_json: any, description_html: string) => {
- setShowAlert(true);
- onChange(description_html);
- handleSubmit(updatePage)();
- }}
- duplicationConfig={userCanDuplicate ? { action: duplicate_page } : undefined}
- pageArchiveConfig={
- userCanArchive
- ? {
- is_archived: archived_at ? true : false,
- action: archived_at ? unArchivePage : archivePage,
- }
- : undefined
- }
- pageLockConfig={userCanLock ? { is_locked: false, action: lockPage } : undefined}
- />
- )}
- />
- {projectId && envConfig?.has_openai_configured && (
- <div className="absolute right-[68px] top-2.5">
- <GptAssistantPopover
- isOpen={gptModalOpen}
- projectId={projectId.toString()}
- handleClose={() => {
- setGptModal((prevData) => !prevData);
- // this is done so that the title do not reset after gpt popover closed
- reset(getValues());
- }}
- onResponse={(response) => {
- handleAiAssistance(response);
- }}
- placement="top-end"
- button={
- <button
- type="button"
- className="flex items-center gap-1 rounded px-1.5 py-1 text-xs hover:bg-custom-background-90"
- onClick={() => setGptModal((prevData) => !prevData)}
- >
- <Sparkle className="h-4 w-4" />
- AI
- </button>
- }
- className="!min-w-[38rem]"
- />
- </div>
- )}
- </div>
)}
+ <PageEditorBody
+ swrPageDetails={swrPageDetails}
+ control={control}
+ editorRef={editorRef}
+ handleEditorReady={handleEditorReady}
+ readOnlyEditorRef={readOnlyEditorRef}
+ handleReadOnlyEditorReady={handleReadOnlyEditorReady}
+ handleSubmit={() => handleSubmit(handleUpdatePage)()}
+ markings={markings}
+ pageStore={pageStore}
+ sidePeekVisible={sidePeekVisible}
+ updateMarkings={updateMarkings}
+ />
<IssuePeekOverview />
</div>
</div>
</>
- ) : (
- <div className="grid h-full w-full place-items-center">
- <Spinner />
- </div>
);
});
diff --git a/web/pages/[workspaceSlug]/projects/[projectId]/pages/index.tsx b/web/pages/[workspaceSlug]/projects/[projectId]/pages/index.tsx
index e7e7a3e2bd..6869c242e6 100644
--- a/web/pages/[workspaceSlug]/projects/[projectId]/pages/index.tsx
+++ b/web/pages/[workspaceSlug]/projects/[projectId]/pages/index.tsx
@@ -1,231 +1,43 @@
-import { useState, Fragment, ReactElement } from "react";
-import { observer } from "mobx-react-lite";
-import dynamic from "next/dynamic";
+import { ReactElement } from "react";
+import { observer } from "mobx-react";
import { useRouter } from "next/router";
-import useSWR from "swr";
-import { Tab } from "@headlessui/react";
-// hooks
-import { PageHead } from "@/components/core";
-import { EmptyState } from "@/components/empty-state";
+// types
+import { TPageNavigationTabs } from "@plane/types";
+// components
import { PagesHeader } from "@/components/headers";
-import { RecentPagesList, CreateUpdatePageModal } from "@/components/pages";
-import { PagesLoader } from "@/components/ui";
-import { EmptyStateType } from "@/constants/empty-state";
-import { PAGE_TABS_LIST } from "@/constants/page";
-import { useApplication, useEventTracker, useUser, useProject } from "@/hooks/store";
-import { useProjectPages } from "@/hooks/store/use-project-page";
-import useLocalStorage from "@/hooks/use-local-storage";
-import useUserAuth from "@/hooks/use-user-auth";
-import useSize from "@/hooks/use-window-size";
+import { PagesListRoot, PagesListView } from "@/components/pages";
+// hooks
+import { useApplication } from "@/hooks/store";
// layouts
import { AppLayout } from "@/layouts/app-layout";
-// components
-// types
+// lib
import { NextPageWithLayout } from "@/lib/types";
-// constants
-
-const AllPagesList = dynamic<any>(() => import("@/components/pages").then((a) => a.AllPagesList), {
- ssr: false,
-});
-
-const FavoritePagesList = dynamic<any>(() => import("@/components/pages").then((a) => a.FavoritePagesList), {
- ssr: false,
-});
-
-const PrivatePagesList = dynamic<any>(() => import("@/components/pages").then((a) => a.PrivatePagesList), {
- ssr: false,
-});
-
-const ArchivedPagesList = dynamic<any>(() => import("@/components/pages").then((a) => a.ArchivedPagesList), {
- ssr: false,
-});
-
-const SharedPagesList = dynamic<any>(() => import("@/components/pages").then((a) => a.SharedPagesList), {
- ssr: false,
-});
const ProjectPagesPage: NextPageWithLayout = observer(() => {
// router
const router = useRouter();
- const { workspaceSlug, projectId } = router.query;
- // states
- const [createUpdatePageModal, setCreateUpdatePageModal] = useState(false);
+ const { type } = router.query;
// store hooks
- const { currentUser, currentUserLoader } = useUser();
const {
- commandPalette: { toggleCreatePageModal },
+ router: { workspaceSlug, projectId },
} = useApplication();
- const { setTrackElement } = useEventTracker();
- const { getProjectById, currentProjectDetails } = useProject();
- const { fetchProjectPages, fetchArchivedProjectPages, loader, archivedPageLoader, projectPageIds, archivedPageIds } =
- useProjectPages();
- // hooks
- const {} = useUserAuth({ user: currentUser, isLoading: currentUserLoader });
- const [windowWidth] = useSize();
- // local storage
- const { storedValue: pageTab, setValue: setPageTab } = useLocalStorage("pageTab", "Recent");
- // fetching pages from API
- useSWR(
- workspaceSlug && projectId ? `ALL_PAGES_LIST_${projectId}` : null,
- workspaceSlug && projectId ? () => fetchProjectPages(workspaceSlug.toString(), projectId.toString()) : null
- );
- // fetching archived pages from API
- useSWR(
- workspaceSlug && projectId ? `ALL_ARCHIVED_PAGES_LIST_${projectId}` : null,
- workspaceSlug && projectId ? () => fetchArchivedProjectPages(workspaceSlug.toString(), projectId.toString()) : null
- );
-
- if (!workspaceSlug || !projectId) return <></>;
-
- // No access to
- if (currentProjectDetails?.page_view === false)
- return (
- <div className="flex items-center justify-center h-full w-full">
- <EmptyState
- type={EmptyStateType.DISABLED_PROJECT_PAGE}
- primaryButtonLink={`/${workspaceSlug}/projects/${projectId}/settings/features`}
- />
- </div>
- );
- const currentTabValue = (tab: string | null) => {
- switch (tab) {
- case "Recent":
- return 0;
- case "All":
- return 1;
- case "Favorites":
- return 2;
- case "Private":
- return 3;
- case "Shared":
- return 4;
- case "Archived":
- return 5;
- default:
- return 0;
- }
+ const currentPageType = (): TPageNavigationTabs => {
+ const pageType = type?.toString();
+ if (pageType === "private") return "private";
+ if (pageType === "archived") return "archived";
+ return "public";
};
- // derived values
- const project = projectId ? getProjectById(projectId.toString()) : undefined;
- const pageTitle = project?.name ? `${project?.name} - Pages` : undefined;
-
- const MobileTabList = () => (
- <Tab.List as="div" className="flex items-center justify-between border-b border-custom-border-200 px-3 pt-3 mb-4">
- <div className="flex flex-wrap items-center gap-4">
- {PAGE_TABS_LIST.map((tab) => (
- <Tab
- key={tab.key}
- className={({ selected }) =>
- `text-sm outline-none pb-3 ${
- selected ? "border-custom-primary-100 text-custom-primary-100 border-b" : ""
- }`
- }
- >
- {tab.title}
- </Tab>
- ))}
- </div>
- </Tab.List>
- );
-
- if (loader || archivedPageLoader) return <PagesLoader />;
-
+ if (!workspaceSlug || !projectId) return <></>;
return (
- <>
- <PageHead title={pageTitle} />
- {projectPageIds && archivedPageIds && projectPageIds.length + archivedPageIds.length > 0 ? (
- <>
- {workspaceSlug && projectId && (
- <CreateUpdatePageModal
- isOpen={createUpdatePageModal}
- handleClose={() => setCreateUpdatePageModal(false)}
- projectId={projectId.toString()}
- />
- )}
- <div className="flex h-full flex-col md:space-y-5 overflow-hidden md:py-6">
- <div className="justify-between gap-4 hidden md:flex px-6">
- <h3 className="text-2xl font-semibold text-custom-text-100">Pages</h3>
- </div>
- <Tab.Group
- as={Fragment}
- defaultIndex={currentTabValue(pageTab)}
- onChange={(i) => {
- switch (i) {
- case 0:
- return setPageTab("Recent");
- case 1:
- return setPageTab("All");
- case 2:
- return setPageTab("Favorites");
- case 3:
- return setPageTab("Private");
- case 4:
- return setPageTab("Shared");
- case 5:
- return setPageTab("Archived");
- default:
- return setPageTab("All");
- }
- }}
- >
- {windowWidth < 768 ? (
- <MobileTabList />
- ) : (
- <Tab.List as="div" className="mb-6 items-center justify-between hidden md:flex px-6">
- <div className="flex flex-wrap items-center gap-4">
- {PAGE_TABS_LIST.map((tab) => (
- <Tab
- key={tab.key}
- className={({ selected }) =>
- `rounded-full border px-5 py-1.5 text-sm outline-none ${
- selected
- ? "border-custom-primary bg-custom-primary text-white"
- : "border-custom-border-200 bg-custom-background-100 hover:bg-custom-background-90"
- }`
- }
- >
- {tab.title}
- </Tab>
- ))}
- </div>
- </Tab.List>
- )}
-
- <Tab.Panels as={Fragment}>
- <Tab.Panel as="div" className="h-full space-y-5 overflow-y-auto vertical-scrollbar scrollbar-lg pl-6">
- <RecentPagesList />
- </Tab.Panel>
- <Tab.Panel as="div" className="h-full overflow-hidden pl-6">
- <AllPagesList />
- </Tab.Panel>
- <Tab.Panel as="div" className="h-full overflow-hidden pl-6">
- <FavoritePagesList />
- </Tab.Panel>
- <Tab.Panel as="div" className="h-full overflow-hidden pl-6">
- <PrivatePagesList />
- </Tab.Panel>
- <Tab.Panel as="div" className="h-full overflow-hidden pl-6">
- <SharedPagesList />
- </Tab.Panel>
- <Tab.Panel as="div" className="h-full overflow-hidden pl-6">
- <ArchivedPagesList />
- </Tab.Panel>
- </Tab.Panels>
- </Tab.Group>
- </div>
- </>
- ) : (
- <EmptyState
- type={EmptyStateType.PROJECT_PAGE}
- primaryButtonOnClick={() => {
- setTrackElement("Pages empty state");
- toggleCreatePageModal(true);
- }}
- />
- )}
- </>
+ <PagesListView
+ workspaceSlug={workspaceSlug.toString()}
+ projectId={projectId.toString()}
+ pageType={currentPageType()}
+ >
+ <PagesListRoot workspaceSlug={workspaceSlug.toString()} projectId={projectId.toString()} />
+ </PagesListView>
);
});
diff --git a/web/public/empty-state/pages/all-filters.svg b/web/public/empty-state/pages/all-filters.svg
new file mode 100644
index 0000000000..d0ecffbc69
--- /dev/null
+++ b/web/public/empty-state/pages/all-filters.svg
@@ -0,0 +1,45 @@
+<svg width="206" height="217" viewBox="0 0 206 217" fill="none" xmlns="http://www.w3.org/2000/svg">
+<circle cx="103.5" cy="102.5" r="102.5" fill="url(#paint0_linear_8002_162251)"/>
+<path d="M118.625 40.5H65.5C62.1848 40.5 59.0054 41.817 56.6612 44.1612C54.317 46.5054 53 49.6848 53 53V153C53 156.315 54.317 159.495 56.6612 161.839C59.0054 164.183 62.1848 165.5 65.5 165.5H140.5C143.815 165.5 146.995 164.183 149.339 161.839C151.683 159.495 153 156.315 153 153V74.875L118.625 40.5Z" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M115.5 40.5V78H153" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M128 109.25H78" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M128 134.25H78" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M90.5 84.25H78" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<g filter="url(#filter0_ddd_8002_162251)">
+<circle cx="103.754" cy="173.828" r="31" fill="#3A5BC7"/>
+<path d="M92.75 166.5H115.25" stroke="#F9F9FB" stroke-width="3.57143" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M97.75 174H110.25" stroke="#F9F9FB" stroke-width="3.57143" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M101.5 181.5H106.5" stroke="#F9F9FB" stroke-width="3.57143" stroke-linecap="round" stroke-linejoin="round"/>
+</g>
+<defs>
+<filter id="filter0_ddd_8002_162251" x="64.7539" y="137.828" width="78" height="79" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feMorphology radius="2" operator="erode" in="SourceAlpha" result="effect1_dropShadow_8002_162251"/>
+<feOffset dy="2"/>
+<feGaussianBlur stdDeviation="1.5"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.24 0 0 0 0.051 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_8002_162251"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feMorphology radius="4" operator="erode" in="SourceAlpha" result="effect2_dropShadow_8002_162251"/>
+<feOffset dy="3"/>
+<feGaussianBlur stdDeviation="6"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.055 0"/>
+<feBlend mode="normal" in2="effect1_dropShadow_8002_162251" result="effect2_dropShadow_8002_162251"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feMorphology radius="8" operator="erode" in="SourceAlpha" result="effect3_dropShadow_8002_162251"/>
+<feOffset dy="4"/>
+<feGaussianBlur stdDeviation="8"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.078 0"/>
+<feBlend mode="normal" in2="effect2_dropShadow_8002_162251" result="effect3_dropShadow_8002_162251"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect3_dropShadow_8002_162251" result="shape"/>
+</filter>
+<linearGradient id="paint0_linear_8002_162251" x1="103.5" y1="0" x2="103.5" y2="207.52" gradientUnits="userSpaceOnUse">
+<stop stop-color="#F7F7F7"/>
+<stop offset="1" stop-color="#F8F9FA" stop-opacity="0"/>
+</linearGradient>
+</defs>
+</svg>
diff --git a/web/public/empty-state/pages/favorites-dark.webp b/web/public/empty-state/pages/favorites-dark.webp
deleted file mode 100644
index c58b0aab36..0000000000
Binary files a/web/public/empty-state/pages/favorites-dark.webp and /dev/null differ
diff --git a/web/public/empty-state/pages/favorites-light.webp b/web/public/empty-state/pages/favorites-light.webp
deleted file mode 100644
index bd8d061321..0000000000
Binary files a/web/public/empty-state/pages/favorites-light.webp and /dev/null differ
diff --git a/web/public/empty-state/pages/name-filter.svg b/web/public/empty-state/pages/name-filter.svg
new file mode 100644
index 0000000000..2d8ff017d9
--- /dev/null
+++ b/web/public/empty-state/pages/name-filter.svg
@@ -0,0 +1,44 @@
+<svg width="206" height="217" viewBox="0 0 206 217" fill="none" xmlns="http://www.w3.org/2000/svg">
+<circle cx="103.5" cy="102.5" r="102.5" fill="url(#paint0_linear_8002_161873)"/>
+<path d="M118.625 40.5H65.5C62.1848 40.5 59.0054 41.817 56.6612 44.1612C54.317 46.5054 53 49.6848 53 53V153C53 156.315 54.317 159.495 56.6612 161.839C59.0054 164.183 62.1848 165.5 65.5 165.5H140.5C143.815 165.5 146.995 164.183 149.339 161.839C151.683 159.495 153 156.315 153 153V74.875L118.625 40.5Z" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M115.5 40.5V78H153" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M128 109.25H78" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M128 134.25H78" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M90.5 84.25H78" stroke="#80838D" stroke-width="4" stroke-linecap="round" stroke-linejoin="round"/>
+<g filter="url(#filter0_ddd_8002_161873)">
+<circle cx="103.754" cy="173.828" r="31" fill="#3A5BC7"/>
+<path d="M102.075 185.582C109.494 185.582 115.508 179.567 115.508 172.148C115.508 164.729 109.494 158.715 102.075 158.715C94.6559 158.715 88.6416 164.729 88.6416 172.148C88.6416 179.567 94.6559 185.582 102.075 185.582Z" stroke="white" stroke-width="2.52049" stroke-linecap="round" stroke-linejoin="round"/>
+<path d="M118.866 188.939L111.646 181.719" stroke="white" stroke-width="2.52049" stroke-linecap="round" stroke-linejoin="round"/>
+</g>
+<defs>
+<filter id="filter0_ddd_8002_161873" x="64.7539" y="137.828" width="78" height="79" filterUnits="userSpaceOnUse" color-interpolation-filters="sRGB">
+<feFlood flood-opacity="0" result="BackgroundImageFix"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feMorphology radius="2" operator="erode" in="SourceAlpha" result="effect1_dropShadow_8002_161873"/>
+<feOffset dy="2"/>
+<feGaussianBlur stdDeviation="1.5"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.24 0 0 0 0.051 0"/>
+<feBlend mode="normal" in2="BackgroundImageFix" result="effect1_dropShadow_8002_161873"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feMorphology radius="4" operator="erode" in="SourceAlpha" result="effect2_dropShadow_8002_161873"/>
+<feOffset dy="3"/>
+<feGaussianBlur stdDeviation="6"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.055 0"/>
+<feBlend mode="normal" in2="effect1_dropShadow_8002_161873" result="effect2_dropShadow_8002_161873"/>
+<feColorMatrix in="SourceAlpha" type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 127 0" result="hardAlpha"/>
+<feMorphology radius="8" operator="erode" in="SourceAlpha" result="effect3_dropShadow_8002_161873"/>
+<feOffset dy="4"/>
+<feGaussianBlur stdDeviation="8"/>
+<feComposite in2="hardAlpha" operator="out"/>
+<feColorMatrix type="matrix" values="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.078 0"/>
+<feBlend mode="normal" in2="effect2_dropShadow_8002_161873" result="effect3_dropShadow_8002_161873"/>
+<feBlend mode="normal" in="SourceGraphic" in2="effect3_dropShadow_8002_161873" result="shape"/>
+</filter>
+<linearGradient id="paint0_linear_8002_161873" x1="103.5" y1="0" x2="103.5" y2="207.52" gradientUnits="userSpaceOnUse">
+<stop stop-color="#F7F7F7"/>
+<stop offset="1" stop-color="#F8F9FA" stop-opacity="0"/>
+</linearGradient>
+</defs>
+</svg>
diff --git a/web/public/empty-state/pages/shared-dark.webp b/web/public/empty-state/pages/public-dark.webp
similarity index 100%
rename from web/public/empty-state/pages/shared-dark.webp
rename to web/public/empty-state/pages/public-dark.webp
diff --git a/web/public/empty-state/pages/shared-light.webp b/web/public/empty-state/pages/public-light.webp
similarity index 100%
rename from web/public/empty-state/pages/shared-light.webp
rename to web/public/empty-state/pages/public-light.webp
diff --git a/web/public/empty-state/pages/recent-dark.webp b/web/public/empty-state/pages/recent-dark.webp
deleted file mode 100644
index f96ef1564d..0000000000
Binary files a/web/public/empty-state/pages/recent-dark.webp and /dev/null differ
diff --git a/web/public/empty-state/pages/recent-light.webp b/web/public/empty-state/pages/recent-light.webp
deleted file mode 100644
index 9c8d64a4f6..0000000000
Binary files a/web/public/empty-state/pages/recent-light.webp and /dev/null differ
diff --git a/web/services/file.service.ts b/web/services/file.service.ts
index a962af4cdd..ab5cabcf57 100644
--- a/web/services/file.service.ts
+++ b/web/services/file.service.ts
@@ -63,13 +63,20 @@ export class FileService extends APIService {
this.cancelSource.cancel("Upload cancelled");
}
- getUploadFileFunction(workspaceSlug: string): (file: File) => Promise<string> {
+ getUploadFileFunction(
+ workspaceSlug: string,
+ setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
+ ): (file: File) => Promise<string> {
return async (file: File) => {
try {
const formData = new FormData();
formData.append("asset", file);
formData.append("attributes", JSON.stringify({}));
+ // the submitted state will be resolved by the page rendering the editor
+ // once the patch request of saving the editor contents is resolved
+ setIsSubmitting?.("submitting");
+
const data = await this.uploadFile(workspaceSlug, formData);
return data.asset;
} catch (e) {
diff --git a/web/services/page.service.ts b/web/services/page.service.ts
index 461cdb6292..f84f547542 100644
--- a/web/services/page.service.ts
+++ b/web/services/page.service.ts
@@ -1,5 +1,5 @@
// types
-import { IPage, IPageBlock, TIssue } from "@plane/types";
+import { TPage } from "@plane/types";
// helpers
import { API_BASE_URL } from "@/helpers/common.helper";
// services
@@ -10,159 +10,85 @@ export class PageService extends APIService {
super(API_BASE_URL);
}
- async createPage(workspaceSlug: string, projectId: string, data: Partial<IPage>): Promise<IPage> {
- return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/`, data)
- .then((response) => response?.data)
- .catch((error) => {
- throw error?.response?.data;
- });
- }
-
- async patchPage(workspaceSlug: string, projectId: string, pageId: string, data: Partial<IPage>): Promise<IPage> {
- return this.patch(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/`, data)
- .then((response) => response?.data)
- .catch((error) => {
- console.error("error", error?.response?.data);
- throw error?.response?.data;
- });
- }
-
- async deletePage(workspaceSlug: string, projectId: string, pageId: string): Promise<any> {
- return this.delete(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/`)
- .then((response) => response?.data)
- .catch((error) => {
- throw error?.response?.data;
- });
- }
-
- async addPageToFavorites(workspaceSlug: string, projectId: string, pageId: string): Promise<any> {
- return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/user-favorite-pages/`, { page: pageId })
- .then((response) => response?.data)
- .catch((error) => {
- throw error?.response?.data;
- });
- }
-
- async removePageFromFavorites(workspaceSlug: string, projectId: string, pageId: string) {
- return this.delete(`/api/workspaces/${workspaceSlug}/projects/${projectId}/user-favorite-pages/${pageId}`)
+ async fetchAll(workspaceSlug: string, projectId: string): Promise<TPage[]> {
+ return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async getProjectPages(workspaceSlug: string, projectId: string): Promise<IPage[]> {
- return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/`)
+ async fetchById(workspaceSlug: string, projectId: string, pageId: string): Promise<TPage> {
+ return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async getPagesWithParams(
- workspaceSlug: string,
- projectId: string,
- pageType: "all" | "favorite" | "private" | "shared"
- ): Promise<IPage[]> {
- return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/`, {
- params: {
- page_view: pageType,
- },
- })
+ async create(workspaceSlug: string, projectId: string, data: Partial<TPage>): Promise<TPage> {
+ return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async getPageDetails(workspaceSlug: string, projectId: string, pageId: string): Promise<IPage> {
- return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/`)
+ async update(workspaceSlug: string, projectId: string, pageId: string, data: Partial<TPage>): Promise<TPage> {
+ return this.patch(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/`, data)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async createPageBlock(
- workspaceSlug: string,
- projectId: string,
- pageId: string,
- data: Partial<IPageBlock>
- ): Promise<IPageBlock> {
- return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/page-blocks/`, data)
+ async remove(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
+ return this.delete(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async getPageBlock(
- workspaceSlug: string,
- projectId: string,
- pageId: string,
- pageBlockId: string
- ): Promise<IPageBlock[]> {
- return this.get(
- `/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/page-blocks/${pageBlockId}/`
- )
+ async fetchFavorites(workspaceSlug: string, projectId: string): Promise<TPage[]> {
+ return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/favorite-pages/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async patchPageBlock(
- workspaceSlug: string,
- projectId: string,
- pageId: string,
- pageBlockId: string,
- data: Partial<IPageBlock>
- ): Promise<IPage> {
- return this.patch(
- `/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/page-blocks/${pageBlockId}/`,
- data
- )
+ async addToFavorites(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
+ return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/favorite-pages/${pageId}/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async deletePageBlock(workspaceSlug: string, projectId: string, pageId: string, pageBlockId: string): Promise<any> {
- return this.delete(
- `/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/page-blocks/${pageBlockId}/`
- )
+ async removeFromFavorites(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
+ return this.delete(`/api/workspaces/${workspaceSlug}/projects/${projectId}/favorite-pages/${pageId}/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async listPageBlocks(workspaceSlug: string, projectId: string, pageId: string): Promise<IPageBlock[]> {
- return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/page-blocks/`)
+ async fetchArchived(workspaceSlug: string, projectId: string): Promise<TPage[]> {
+ return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/archived-pages/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async convertPageBlockToIssue(
+ async archive(
workspaceSlug: string,
projectId: string,
- pageId: string,
- blockId: string
- ): Promise<TIssue> {
- return this.post(
- `/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/page-blocks/${blockId}/issues/`
- )
- .then((response) => response?.data)
- .catch((error) => {
- throw error?.response?.data;
- });
- }
-
- // =============== Archiving & Unarchiving Pages =================
- async archivePage(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
+ pageId: string
+ ): Promise<{
+ archived_at: string;
+ }> {
return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/archive/`)
.then((response) => response?.data)
.catch((error) => {
@@ -170,23 +96,15 @@ export class PageService extends APIService {
});
}
- async restorePage(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
- return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/unarchive/`)
+ async restore(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
+ return this.delete(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/archive/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
});
}
- async getArchivedPages(workspaceSlug: string, projectId: string): Promise<IPage[]> {
- return this.get(`/api/workspaces/${workspaceSlug}/projects/${projectId}/archived-pages/`)
- .then((response) => response?.data)
- .catch((error) => {
- throw error;
- });
- }
- // ==================== Pages Locking Services ==========================
- async lockPage(workspaceSlug: string, projectId: string, pageId: string): Promise<any> {
+ async lock(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/lock/`)
.then((response) => response?.data)
.catch((error) => {
@@ -194,8 +112,8 @@ export class PageService extends APIService {
});
}
- async unlockPage(workspaceSlug: string, projectId: string, pageId: string): Promise<any> {
- return this.post(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/unlock/`)
+ async unlock(workspaceSlug: string, projectId: string, pageId: string): Promise<void> {
+ return this.delete(`/api/workspaces/${workspaceSlug}/projects/${projectId}/pages/${pageId}/lock/`)
.then((response) => response?.data)
.catch((error) => {
throw error?.response?.data;
diff --git a/web/services/project/project-member.service.ts b/web/services/project/project-member.service.ts
index 43b19ae992..cdf6567780 100644
--- a/web/services/project/project-member.service.ts
+++ b/web/services/project/project-member.service.ts
@@ -1,8 +1,8 @@
+// types
+import type { IProjectBulkAddFormData, IProjectMember, IProjectMembership } from "@plane/types";
import { API_BASE_URL } from "@/helpers/common.helper";
// services
import { APIService } from "@/services/api.service";
-// types
-import type { IProjectBulkAddFormData, IProjectMember, IProjectMembership } from "@plane/types";
export class ProjectMemberService extends APIService {
constructor() {
diff --git a/web/store/inbox/project-inbox.store.ts b/web/store/inbox/project-inbox.store.ts
index 289187cc9c..07013e83dd 100644
--- a/web/store/inbox/project-inbox.store.ts
+++ b/web/store/inbox/project-inbox.store.ts
@@ -56,7 +56,7 @@ export interface IProjectInboxStore {
handleInboxIssueSorting: <T extends keyof TInboxIssueSorting>(key: T, value: TInboxIssueSorting[T]) => void; // if user sends me undefined, I will remove the value from the filter key
fetchInboxIssues: (workspaceSlug: string, projectId: string, loadingType?: TLoader) => Promise<void>;
fetchInboxPaginationIssues: (workspaceSlug: string, projectId: string) => Promise<void>;
- fetchInboxIssueById: (workspaceSlug: string, projectId: string, inboxIssueId: string) => Promise<void>;
+ fetchInboxIssueById: (workspaceSlug: string, projectId: string, inboxIssueId: string) => Promise<TInboxIssue>;
createInboxIssue: (
workspaceSlug: string,
projectId: string,
@@ -216,8 +216,6 @@ export class ProjectInboxStore implements IProjectInboxStore {
set(this, "inboxFilters", undefined);
set(this, ["inboxSorting", "order_by"], "issue__created_at");
set(this, ["inboxSorting", "sort_by"], "desc");
- set(this, ["inboxIssues"], {});
- set(this, ["inboxIssuePaginationInfo"], undefined);
if (tab === "closed") set(this, ["inboxFilters", "status"], [-1, 1, 2]);
else set(this, ["inboxFilters", "status"], [-2]);
const { workspaceSlug, projectId } = this.store.app.router;
@@ -226,16 +224,12 @@ export class ProjectInboxStore implements IProjectInboxStore {
handleInboxIssueFilters = <T extends keyof TInboxIssueFilter>(key: T, value: TInboxIssueFilter[T]) => {
set(this.inboxFilters, key, value);
- set(this, ["inboxIssues"], {});
- set(this, ["inboxIssuePaginationInfo"], undefined);
const { workspaceSlug, projectId } = this.store.app.router;
if (workspaceSlug && projectId) this.fetchInboxIssues(workspaceSlug, projectId, "filter-loading");
};
handleInboxIssueSorting = <T extends keyof TInboxIssueSorting>(key: T, value: TInboxIssueSorting[T]) => {
set(this.inboxSorting, key, value);
- set(this, ["inboxIssues"], {});
- set(this, ["inboxIssuePaginationInfo"], undefined);
const { workspaceSlug, projectId } = this.store.app.router;
if (workspaceSlug && projectId) this.fetchInboxIssues(workspaceSlug, projectId, "filter-loading");
};
@@ -342,7 +336,11 @@ export class ProjectInboxStore implements IProjectInboxStore {
* @param projectId
* @param inboxIssueId
*/
- fetchInboxIssueById = async (workspaceSlug: string, projectId: string, inboxIssueId: string) => {
+ fetchInboxIssueById = async (
+ workspaceSlug: string,
+ projectId: string,
+ inboxIssueId: string
+ ): Promise<TInboxIssue> => {
try {
this.isLoading = "issue-loading";
const inboxIssue = await this.inboxIssueService.retrieve(workspaceSlug, projectId, inboxIssueId);
@@ -360,9 +358,11 @@ export class ProjectInboxStore implements IProjectInboxStore {
await this.store.issue.issueDetail.fetchComments(workspaceSlug, projectId, issueId);
this.isLoading = undefined;
}
- } catch {
+ return inboxIssue;
+ } catch (error) {
console.error("Error fetching the inbox issue with inbox issue id");
this.isLoading = undefined;
+ throw error;
}
};
diff --git a/web/store/member/project-member.store.ts b/web/store/member/project-member.store.ts
index 02a00375a2..18759384bc 100644
--- a/web/store/member/project-member.store.ts
+++ b/web/store/member/project-member.store.ts
@@ -2,6 +2,8 @@ import set from "lodash/set";
import sortBy from "lodash/sortBy";
import { action, computed, makeObservable, observable, runInAction } from "mobx";
import { computedFn } from "mobx-utils";
+// types
+import { IProjectBulkAddFormData, IProjectMember, IProjectMembership, IUserLite } from "@plane/types";
// services
import { EUserProjectRoles } from "@/constants/project";
import { ProjectMemberService } from "@/services/project";
@@ -9,7 +11,6 @@ import { ProjectMemberService } from "@/services/project";
import { IRouterStore } from "@/store/application/router.store";
import { RootStore } from "@/store/root.store";
import { IUserRootStore } from "@/store/user";
-import { IProjectBulkAddFormData, IProjectMember, IProjectMembership, IUserLite } from "@plane/types";
// constants
import { IMemberRootStore } from ".";
diff --git a/web/store/mention.store.ts b/web/store/mention.store.ts
deleted file mode 100644
index d523a9d55b..0000000000
--- a/web/store/mention.store.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { IMentionHighlight, IMentionSuggestion } from "@plane/lite-text-editor";
-import { computed, makeObservable } from "mobx";
-// editor
-// types
-import { RootStore } from "@/store/root.store";
-
-export interface IMentionStore {
- // computed
- mentionSuggestions: IMentionSuggestion[];
- mentionHighlights: IMentionHighlight[];
-}
-
-export class MentionStore implements IMentionStore {
- // root store
- rootStore;
-
- constructor(_rootStore: RootStore) {
- makeObservable(this, {
- // computed
- mentionHighlights: computed,
- mentionSuggestions: computed,
- });
- // rootStore
- this.rootStore = _rootStore;
- }
-
- /**
- * @description returns a list of mention suggestions
- */
- get mentionSuggestions() {
- const workspaceSlug = this.rootStore.app.router.workspaceSlug;
- const projectMemberIds = this.rootStore.memberRoot.project.projectMemberIds;
-
- const suggestions = (projectMemberIds ?? [])?.map((memberId) => {
- const memberDetails = this.rootStore.memberRoot.project.getProjectMemberDetails(memberId);
-
- return {
- id: `${memberDetails?.member?.id}`,
- type: "User",
- title: `${memberDetails?.member?.display_name}`,
- subtitle: memberDetails?.member?.email ?? "",
- avatar: `${memberDetails?.member?.avatar}`,
- redirect_uri: `/${workspaceSlug}/profile/${memberDetails?.member?.id}`,
- };
- });
-
- return suggestions;
- }
-
- get mentionHighlights() {
- const user = this.rootStore.user.currentUser;
- return user ? [user.id] : [];
- }
-}
diff --git a/web/store/page.store.ts b/web/store/page.store.ts
deleted file mode 100644
index 60b8e3c691..0000000000
--- a/web/store/page.store.ts
+++ /dev/null
@@ -1,277 +0,0 @@
-import { action, makeObservable, observable, reaction, runInAction } from "mobx";
-
-import { PageService } from "@/services/page.service";
-import { IIssueLabel, IPage } from "@plane/types";
-
-import { RootStore } from "./root.store";
-
-export interface IPageStore {
- // Page Properties
- access: number;
- archived_at: string | null;
- color: string;
- created_at: string | null;
- created_by: string;
- description: string;
- description_html: string;
- description_stripped: string | null;
- id: string;
- is_favorite: boolean;
- label_details: IIssueLabel[];
- is_locked: boolean;
- labels: string[];
- name: string;
- owned_by: string;
- project: string;
- updated_at: string | null;
- updated_by: string;
- workspace: string;
-
- // Actions
- makePublic: () => Promise<void>;
- makePrivate: () => Promise<void>;
- lockPage: () => Promise<void>;
- unlockPage: () => Promise<void>;
- addToFavorites: () => Promise<void>;
- removeFromFavorites: () => Promise<void>;
- updateName: (name: string) => Promise<void>;
- updateDescription: (description: string) => void;
-
- // Reactions
- disposers: Array<() => void>;
-
- // Helpers
- oldName: string;
- cleanup: () => void;
- isSubmitting: "submitting" | "submitted" | "saved";
- setIsSubmitting: (isSubmitting: "submitting" | "submitted" | "saved") => void;
-}
-
-export class PageStore implements IPageStore {
- access = 0;
- isSubmitting: "submitting" | "submitted" | "saved" = "saved";
- archived_at: string | null;
- color: string;
- created_at: string | null;
- created_by: string;
- description: string;
- description_html = "";
- description_stripped: string | null;
- id: string;
- is_favorite = false;
- is_locked = true;
- labels: string[];
- name = "";
- owned_by: string;
- project: string;
- updated_at: string | null;
- updated_by: string;
- workspace: string;
- oldName = "";
- label_details: IIssueLabel[] = [];
- disposers: Array<() => void> = [];
-
- pageService;
- // root store
- rootStore;
-
- constructor(page: IPage, _rootStore: RootStore) {
- makeObservable(this, {
- name: observable.ref,
- description_html: observable.ref,
- is_favorite: observable.ref,
- is_locked: observable.ref,
- isSubmitting: observable.ref,
- access: observable.ref,
-
- makePublic: action,
- makePrivate: action,
- addToFavorites: action,
- removeFromFavorites: action,
- updateName: action,
- updateDescription: action.bound,
- setIsSubmitting: action,
- cleanup: action,
- });
- this.created_by = page?.created_by || "";
- this.created_at = page?.created_at ?? "";
- this.color = page?.color || "";
- this.archived_at = page?.archived_at ?? null;
- this.name = page?.name || "";
- this.description = page?.description || "";
- this.description_stripped = page?.description_stripped || "";
- this.description_html = page?.description_html || "";
- this.access = page?.access || 0;
- this.workspace = page?.workspace || "";
- this.updated_by = page?.updated_by || "";
- this.updated_at = page?.updated_at ?? "";
- this.project = page?.project || "";
- this.owned_by = page?.owned_by || "";
- this.labels = page?.labels || [];
- this.label_details = page?.label_details || [];
- this.is_locked = page?.is_locked || false;
- this.id = page?.id || "";
- this.is_favorite = page?.is_favorite || false;
- this.oldName = page?.name || "";
-
- this.rootStore = _rootStore;
- this.pageService = new PageService();
-
- const descriptionDisposer = reaction(
- () => this.description_html,
- (description_html) => {
- //TODO: Fix reaction to only run when the data is changed, not when the page is loaded
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
- this.isSubmitting = "submitting";
- this.pageService.patchPage(workspaceSlug, projectId, this.id, { description_html }).finally(() => {
- runInAction(() => {
- this.isSubmitting = "submitted";
- });
- });
- },
- { delay: 3000 }
- );
-
- const pageTitleDisposer = reaction(
- () => this.name,
- (name) => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
- this.isSubmitting = "submitting";
- this.pageService
- .patchPage(workspaceSlug, projectId, this.id, { name })
- .catch(() => {
- runInAction(() => {
- this.name = this.oldName;
- });
- })
- .finally(() => {
- runInAction(() => {
- this.isSubmitting = "submitted";
- });
- });
- },
- { delay: 2000 }
- );
-
- this.disposers.push(descriptionDisposer, pageTitleDisposer);
- }
-
- updateName = action("updateName", async (name: string) => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.oldName = this.name;
- this.name = name;
- });
-
- updateDescription = action("updateDescription", (description_html: string) => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.description_html = description_html;
- });
-
- cleanup = action("cleanup", () => {
- this.disposers.forEach((disposer) => {
- disposer();
- });
- });
-
- setIsSubmitting = action("setIsSubmitting", (isSubmitting: "submitting" | "submitted" | "saved") => {
- this.isSubmitting = isSubmitting;
- });
-
- lockPage = action("lockPage", async () => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.is_locked = true;
-
- await this.pageService.lockPage(workspaceSlug, projectId, this.id).catch(() => {
- runInAction(() => {
- this.is_locked = false;
- });
- });
- });
-
- unlockPage = action("unlockPage", async () => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.is_locked = false;
-
- await this.pageService.unlockPage(workspaceSlug, projectId, this.id).catch(() => {
- runInAction(() => {
- this.is_locked = true;
- });
- });
- });
-
- /**
- * Add Page to users favorites list
- */
- addToFavorites = action("addToFavorites", async () => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.is_favorite = true;
-
- await this.pageService.addPageToFavorites(workspaceSlug, projectId, this.id).catch(() => {
- runInAction(() => {
- this.is_favorite = false;
- });
- });
- });
-
- /**
- * Remove page from the users favorites list
- */
- removeFromFavorites = action("removeFromFavorites", async () => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.is_favorite = false;
-
- await this.pageService.removePageFromFavorites(workspaceSlug, projectId, this.id).catch(() => {
- runInAction(() => {
- this.is_favorite = true;
- });
- });
- });
-
- /**
- * make a page public
- * @returns
- */
- makePublic = action("makePublic", async () => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.access = 0;
-
- this.pageService.patchPage(workspaceSlug, projectId, this.id, { access: 0 }).catch(() => {
- runInAction(() => {
- this.access = 1;
- });
- });
- });
-
- /**
- * Make a page private
- * @returns
- */
- makePrivate = action("makePrivate", async () => {
- const { projectId, workspaceSlug } = this.rootStore.app.router;
- if (!projectId || !workspaceSlug) return;
-
- this.access = 1;
-
- this.pageService.patchPage(workspaceSlug, projectId, this.id, { access: 1 }).catch(() => {
- runInAction(() => {
- this.access = 0;
- });
- });
- });
-}
diff --git a/web/store/pages/page.store.ts b/web/store/pages/page.store.ts
new file mode 100644
index 0000000000..81d821e7e1
--- /dev/null
+++ b/web/store/pages/page.store.ts
@@ -0,0 +1,488 @@
+import set from "lodash/set";
+import { action, computed, makeObservable, observable, reaction, runInAction } from "mobx";
+// types
+import { TPage, TPageViewProps } from "@plane/types";
+// constants
+import { EPageAccess } from "@/constants/page";
+import { EUserProjectRoles } from "@/constants/project";
+// services
+import { PageService } from "@/services/page.service";
+import { RootStore } from "../root.store";
+
+export type TLoader = "submitting" | "submitted" | "saved" | undefined;
+
+export interface IPageStore extends TPage {
+ // observables
+ isSubmitting: "submitting" | "submitted" | "saved";
+ loader: TLoader;
+ // computed
+ asJSON: TPage | undefined;
+ isCurrentUserOwner: boolean; // it will give the user is the owner of the page or not
+ canCurrentUserEditPage: boolean; // it will give the user permission to read the page or write the page
+ canCurrentUserDuplicatePage: boolean;
+ canCurrentUserLockPage: boolean;
+ canCurrentUserArchivePage: boolean;
+ canCurrentUserDeletePage: boolean;
+ isContentEditable: boolean;
+ // helpers
+ oldName: string;
+ updateTitle: (name: string) => void;
+ updateDescription: (description: string) => void;
+ setIsSubmitting: (isSubmitting: "submitting" | "submitted" | "saved") => void;
+ cleanup: () => void;
+ // actions
+ update: (pageData: Partial<TPage>) => Promise<TPage | undefined>;
+ updateViewProps: (viewProps: Partial<TPageViewProps>) => void;
+ makePublic: () => Promise<void>;
+ makePrivate: () => Promise<void>;
+ lock: () => Promise<void>;
+ unlock: () => Promise<void>;
+ archive: () => Promise<void>;
+ restore: () => Promise<void>;
+ addToFavorites: () => Promise<void>;
+ removeFromFavorites: () => Promise<void>;
+}
+
+export class PageStore implements IPageStore {
+ // loaders
+ isSubmitting: "submitting" | "submitted" | "saved" = "saved";
+ loader: TLoader = undefined;
+ // page properties
+ id: string | undefined;
+ name: string | undefined;
+ description_html: string | undefined;
+ color: string | undefined;
+ labels: string[] | undefined;
+ owned_by: string | undefined;
+ access: EPageAccess | undefined;
+ is_favorite: boolean;
+ is_locked: boolean;
+ archived_at: string | null | undefined;
+ workspace: string | undefined;
+ project: string | undefined;
+ created_by: string | undefined;
+ updated_by: string | undefined;
+ created_at: Date | undefined;
+ updated_at: Date | undefined;
+ view_props: TPageViewProps | undefined;
+ // helpers
+ oldName: string = "";
+ // reactions
+ disposers: Array<() => void> = [];
+ // service
+ pageService: PageService;
+
+ constructor(private store: RootStore, page: TPage) {
+ this.id = page?.id || undefined;
+ this.name = page?.name || undefined;
+ this.description_html = page?.description_html || undefined;
+ this.color = page?.color || undefined;
+ this.labels = page?.labels || undefined;
+ this.owned_by = page?.owned_by || undefined;
+ this.access = page?.access || EPageAccess.PUBLIC;
+ this.is_favorite = page?.is_favorite || false;
+ this.is_locked = page?.is_locked || false;
+ this.archived_at = page?.archived_at || undefined;
+ this.workspace = page?.workspace || undefined;
+ this.project = page?.project || undefined;
+ this.created_by = page?.created_by || undefined;
+ this.updated_by = page?.updated_by || undefined;
+ this.created_at = page?.created_at || undefined;
+ this.updated_at = page?.updated_at || undefined;
+ this.view_props = page?.view_props || undefined;
+ this.oldName = page?.name || "";
+
+ makeObservable(this, {
+ // loaders
+ isSubmitting: observable.ref,
+ loader: observable.ref,
+ // page properties
+ id: observable.ref,
+ name: observable.ref,
+ description_html: observable.ref,
+ color: observable.ref,
+ labels: observable,
+ owned_by: observable.ref,
+ access: observable.ref,
+ is_favorite: observable.ref,
+ is_locked: observable.ref,
+ archived_at: observable.ref,
+ workspace: observable.ref,
+ project: observable.ref,
+ created_by: observable.ref,
+ updated_by: observable.ref,
+ created_at: observable.ref,
+ updated_at: observable.ref,
+ view_props: observable,
+ // helpers
+ oldName: observable,
+ // computed
+ asJSON: computed,
+ isCurrentUserOwner: computed,
+ canCurrentUserEditPage: computed,
+ canCurrentUserDuplicatePage: computed,
+ canCurrentUserLockPage: computed,
+ canCurrentUserArchivePage: computed,
+ canCurrentUserDeletePage: computed,
+ isContentEditable: computed,
+ // helper actions
+ updateTitle: action,
+ updateDescription: action.bound,
+ setIsSubmitting: action,
+ cleanup: action,
+ // actions
+ update: action,
+ updateViewProps: action,
+ makePublic: action,
+ makePrivate: action,
+ lock: action,
+ unlock: action,
+ archive: action,
+ restore: action,
+ addToFavorites: action,
+ removeFromFavorites: action,
+ });
+
+ this.pageService = new PageService();
+
+ const titleDisposer = reaction(
+ () => this.name,
+ (name) => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return;
+ this.isSubmitting = "submitting";
+ this.pageService
+ .update(workspaceSlug, projectId, this.id, {
+ name,
+ })
+ .catch(() =>
+ runInAction(() => {
+ this.name = this.oldName;
+ })
+ )
+ .finally(() =>
+ runInAction(() => {
+ this.isSubmitting = "submitted";
+ })
+ );
+ },
+ { delay: 2000 }
+ );
+
+ const descriptionDisposer = reaction(
+ () => this.description_html,
+ (description_html) => {
+ //TODO: Fix reaction to only run when the data is changed, not when the page is loaded
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return;
+ this.isSubmitting = "submitting";
+ this.pageService
+ .update(workspaceSlug, projectId, this.id, {
+ description_html,
+ })
+ .finally(() =>
+ runInAction(() => {
+ this.isSubmitting = "submitted";
+ })
+ );
+ },
+ { delay: 3000 }
+ );
+
+ this.disposers.push(titleDisposer, descriptionDisposer);
+ }
+
+ // computed
+ get asJSON() {
+ return {
+ id: this.id,
+ name: this.name,
+ description_html: this.description_html,
+ color: this.color,
+ labels: this.labels,
+ owned_by: this.owned_by,
+ access: this.access,
+ is_favorite: this.is_favorite,
+ is_locked: this.is_locked,
+ archived_at: this.archived_at,
+ workspace: this.workspace,
+ project: this.project,
+ created_by: this.created_by,
+ updated_by: this.updated_by,
+ created_at: this.created_at,
+ updated_at: this.updated_at,
+ view_props: this.view_props,
+ };
+ }
+
+ get isCurrentUserOwner() {
+ const currentUserId = this.store.user.currentUser?.id;
+ if (!currentUserId) return false;
+ return this.owned_by === currentUserId;
+ }
+
+ /**
+ * @description returns true if the current logged in user can edit the page
+ */
+ get canCurrentUserEditPage() {
+ const currentUserProjectRole = this.store.user.membership.currentProjectRole;
+ return this.isCurrentUserOwner || (!!currentUserProjectRole && currentUserProjectRole >= EUserProjectRoles.MEMBER);
+ }
+
+ /**
+ * @description returns true if the current logged in user can create a duplicate the page
+ */
+ get canCurrentUserDuplicatePage() {
+ const currentUserProjectRole = this.store.user.membership.currentProjectRole;
+ return this.isCurrentUserOwner || (!!currentUserProjectRole && currentUserProjectRole >= EUserProjectRoles.MEMBER);
+ }
+
+ /**
+ * @description returns true if the current logged in user can lock the page
+ */
+ get canCurrentUserLockPage() {
+ const currentUserProjectRole = this.store.user.membership.currentProjectRole;
+ return this.isCurrentUserOwner || (!!currentUserProjectRole && currentUserProjectRole >= EUserProjectRoles.MEMBER);
+ }
+
+ /**
+ * @description returns true if the current logged in user can archive the page
+ */
+ get canCurrentUserArchivePage() {
+ const currentUserProjectRole = this.store.user.membership.currentProjectRole;
+ return this.isCurrentUserOwner || (!!currentUserProjectRole && currentUserProjectRole >= EUserProjectRoles.MEMBER);
+ }
+
+ /**
+ * @description returns true if the current logged in user can delete the page
+ */
+ get canCurrentUserDeletePage() {
+ const currentUserProjectRole = this.store.user.membership.currentProjectRole;
+ return this.isCurrentUserOwner || currentUserProjectRole === EUserProjectRoles.ADMIN;
+ }
+
+ /**
+ * @description returns true if the page can be edited
+ */
+ get isContentEditable() {
+ const isOwner = this.isCurrentUserOwner;
+ const currentUserRole = this.store.user.membership.currentProjectRole;
+ const isPublic = this.access === EPageAccess.PUBLIC;
+ const isArchived = this.archived_at;
+ const isLocked = this.is_locked;
+
+ return (
+ !isArchived &&
+ !isLocked &&
+ (isOwner || (isPublic && !!currentUserRole && currentUserRole >= EUserProjectRoles.MEMBER))
+ );
+ }
+
+ updateTitle = action("updateTitle", (name: string) => {
+ this.oldName = this.name ?? "";
+ this.name = name;
+ });
+
+ updateDescription = action("updateDescription", (description_html: string) => {
+ this.description_html = description_html;
+ });
+
+ setIsSubmitting = action("setIsSubmitting", (isSubmitting: "submitting" | "submitted" | "saved") => {
+ this.isSubmitting = isSubmitting;
+ });
+
+ cleanup = action("cleanup", () => {
+ this.disposers.forEach((disposer) => {
+ disposer();
+ });
+ });
+
+ /**
+ * @description update the page
+ * @param {Partial<TPage>} pageData
+ */
+ update = async (pageData: Partial<TPage>) => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const currentPage = this.asJSON;
+ try {
+ const currentPageResponse = await this.pageService.update(workspaceSlug, projectId, this.id, currentPage);
+ if (currentPageResponse)
+ runInAction(() => {
+ Object.keys(pageData).forEach((key) => {
+ const currentPageKey = key as keyof TPage;
+ set(this, key, currentPageResponse?.[currentPageKey] || undefined);
+ });
+ });
+ } catch {
+ runInAction(() => {
+ Object.keys(pageData).forEach((key) => {
+ const currentPageKey = key as keyof TPage;
+ set(this, key, currentPage?.[currentPageKey] || undefined);
+ });
+ });
+ }
+ };
+
+ /**
+ * @description update the page view props
+ * @param {Partial<TPageViewProps>} updatedProps
+ */
+ updateViewProps = async (updatedProps: Partial<TPageViewProps>) => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const currentViewProps = { ...this.view_props };
+
+ runInAction(() => {
+ Object.keys(updatedProps).forEach((key) => {
+ const currentPageKey = key as keyof TPageViewProps;
+ if (this.view_props) set(this.view_props, key, updatedProps[currentPageKey]);
+ });
+ });
+
+ try {
+ await this.pageService.update(workspaceSlug, projectId, this.id, {
+ view_props: {
+ ...this.view_props,
+ ...updatedProps,
+ },
+ });
+ } catch {
+ runInAction(() => {
+ this.view_props = currentViewProps;
+ });
+ }
+ };
+
+ /**
+ * @description make the page public
+ */
+ makePublic = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const pageAccess = this.access;
+ runInAction(() => (this.access = EPageAccess.PUBLIC));
+
+ await this.pageService
+ .update(workspaceSlug, projectId, this.id, {
+ access: EPageAccess.PUBLIC,
+ })
+ .catch(() => {
+ runInAction(() => (this.access = pageAccess));
+ });
+ };
+
+ /**
+ * @description make the page private
+ */
+ makePrivate = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const pageAccess = this.access;
+ runInAction(() => (this.access = EPageAccess.PRIVATE));
+
+ await this.pageService
+ .update(workspaceSlug, projectId, this.id, {
+ access: EPageAccess.PRIVATE,
+ })
+ .catch(() => {
+ runInAction(() => (this.access = pageAccess));
+ });
+ };
+
+ /**
+ * @description lock the page
+ */
+ lock = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const pageIsLocked = this.is_locked;
+ runInAction(() => (this.is_locked = true));
+
+ await this.pageService.lock(workspaceSlug, projectId, this.id).catch(() => {
+ runInAction(() => (this.is_locked = pageIsLocked));
+ });
+ };
+
+ /**
+ * @description archive the page
+ */
+ archive = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ await this.pageService.archive(workspaceSlug, projectId, this.id).then((res) => {
+ runInAction(() => {
+ this.archived_at = res.archived_at;
+ });
+ });
+ };
+
+ /**
+ * @description restore the page
+ */
+ restore = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ await this.pageService.restore(workspaceSlug, projectId, this.id).then(() => {
+ runInAction(() => {
+ this.archived_at = null;
+ });
+ });
+ };
+
+ /**
+ * @description unlock the page
+ */
+ unlock = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const pageIsLocked = this.is_locked;
+ runInAction(() => (this.is_locked = false));
+
+ await this.pageService.unlock(workspaceSlug, projectId, this.id).catch(() => {
+ runInAction(() => (this.is_locked = pageIsLocked));
+ });
+ };
+
+ /**
+ * @description add the page to favorites
+ */
+ addToFavorites = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const pageIsFavorite = this.is_favorite;
+ runInAction(() => {
+ this.is_favorite = true;
+ });
+
+ await this.pageService.addToFavorites(workspaceSlug, projectId, this.id).catch(() => {
+ runInAction(() => (this.is_favorite = pageIsFavorite));
+ });
+ };
+
+ /**
+ * @description remove the page from favorites
+ */
+ removeFromFavorites = async () => {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !this.id) return undefined;
+
+ const pageIsFavorite = this.is_favorite;
+ runInAction(() => {
+ this.is_favorite = false;
+ });
+
+ await this.pageService.removeFromFavorites(workspaceSlug, projectId, this.id).catch(() => {
+ runInAction(() => (this.is_favorite = pageIsFavorite));
+ });
+ };
+}
diff --git a/web/store/pages/project-page.store.ts b/web/store/pages/project-page.store.ts
new file mode 100644
index 0000000000..ef1560350f
--- /dev/null
+++ b/web/store/pages/project-page.store.ts
@@ -0,0 +1,247 @@
+import set from "lodash/set";
+import unset from "lodash/unset";
+import { makeObservable, observable, runInAction, action, computed } from "mobx";
+import { computedFn } from "mobx-utils";
+import { TPage, TPageFilters, TPageNavigationTabs } from "@plane/types";
+// helpers
+import { filterPagesByPageType, orderPages, shouldFilterPage } from "@/helpers/page.helper";
+// services
+import { PageService } from "@/services/page.service";
+import { IPageStore, PageStore } from "@/store/pages/page.store";
+import { RootStore } from "../root.store";
+
+type TLoader = "init-loader" | "mutation-loader" | undefined;
+
+type TError = { title: string; description: string };
+
+export interface IProjectPageStore {
+ // observables
+ loader: TLoader;
+ pageType: TPageNavigationTabs;
+ data: Record<string, IPageStore>; // pageId => PageStore
+ error: TError | undefined;
+ filters: TPageFilters;
+ // computed
+ pageIds: string[] | undefined;
+ filteredPageIds: string[] | undefined;
+ // helper actions
+ pageById: (pageId: string) => IPageStore | undefined;
+ updateFilters: <T extends keyof TPageFilters>(filterKey: T, filterValue: TPageFilters[T]) => void;
+ clearAllFilters: () => void;
+ // actions
+ getAllPages: (pageType: TPageNavigationTabs) => Promise<TPage[] | undefined>;
+ getPageById: (pageId: string) => Promise<TPage | undefined>;
+ createPage: (pageData: Partial<TPage>) => Promise<TPage | undefined>;
+ removePage: (pageId: string) => Promise<void>;
+}
+
+export class ProjectPageStore implements IProjectPageStore {
+ // observables
+ loader: TLoader = "init-loader";
+ pageType: TPageNavigationTabs = "public";
+ data: Record<string, IPageStore> = {}; // pageId => PageStore
+ error: TError | undefined = undefined;
+ filters: TPageFilters = {
+ searchQuery: "",
+ sortKey: "name",
+ sortBy: "asc",
+ };
+ // service
+ service: PageService;
+
+ constructor(private store: RootStore) {
+ makeObservable(this, {
+ // observables
+ loader: observable.ref,
+ pageType: observable.ref,
+ data: observable,
+ error: observable,
+ filters: observable,
+ // computed
+ pageIds: computed,
+ filteredPageIds: computed,
+ // helper actions
+ updateFilters: action,
+ clearAllFilters: action,
+ // actions
+ getAllPages: action,
+ getPageById: action,
+ createPage: action,
+ removePage: action,
+ });
+
+ this.service = new PageService();
+ }
+
+ get pageIds() {
+ const { projectId } = this.store.app.router;
+ if (!projectId) return undefined;
+
+ // helps to filter pages based on the pageType
+ const pagesByType = filterPagesByPageType(this.pageType, Object.values(this?.data || {}));
+
+ const pages = (pagesByType.map((page) => page.id) as string[]) || undefined;
+
+ return pages ?? undefined;
+ }
+
+ get filteredPageIds() {
+ const { projectId } = this.store.app.router;
+ if (!projectId) return undefined;
+
+ // helps to filter pages based on the pageType
+ const pagesByType = filterPagesByPageType(this.pageType, Object.values(this?.data || {}));
+ let filteredPages = pagesByType.filter(
+ (p) =>
+ p.name?.toLowerCase().includes(this.filters.searchQuery.toLowerCase()) &&
+ shouldFilterPage(p, this.filters.filters)
+ );
+ filteredPages = orderPages(filteredPages, this.filters.sortKey, this.filters.sortBy);
+
+ const pages = (filteredPages.map((page) => page.id) as string[]) || undefined;
+
+ return pages ?? undefined;
+ }
+
+ pageById = computedFn((pageId: string) => {
+ const { projectId } = this.store.app.router;
+ if (!projectId) return undefined;
+
+ return this.data?.[pageId] || undefined;
+ });
+
+ updateFilters = <T extends keyof TPageFilters>(filterKey: T, filterValue: TPageFilters[T]) => {
+ runInAction(() => {
+ set(this.filters, [filterKey], filterValue);
+ });
+ };
+
+ /**
+ * @description clear all the filters
+ */
+ clearAllFilters = () =>
+ runInAction(() => {
+ set(this.filters, ["filters"], {});
+ });
+
+ /**
+ * @description fetch all the pages based on the navigation tab
+ * @param {TPageNavigationTabs} pageType
+ */
+ getAllPages = async (pageType: TPageNavigationTabs) => {
+ try {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId) return undefined;
+
+ const currentPageIds = this.pageIds;
+ runInAction(() => {
+ this.pageType = pageType;
+ this.loader = currentPageIds && currentPageIds.length > 0 ? `mutation-loader` : `init-loader`;
+ this.error = undefined;
+ });
+
+ const pages = await this.service.fetchAll(workspaceSlug, projectId);
+ runInAction(() => {
+ for (const page of pages) if (page?.id) set(this.data, [page.id], new PageStore(this.store, page));
+ this.loader = undefined;
+ });
+
+ return pages;
+ } catch {
+ runInAction(() => {
+ this.loader = undefined;
+ this.error = {
+ title: "Failed",
+ description: "Failed to fetch the pages, Please try again later.",
+ };
+ });
+ }
+ };
+
+ /**
+ * @description fetch the details of a page
+ * @param {string} pageId
+ */
+ getPageById = async (pageId: string) => {
+ try {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !pageId) return undefined;
+
+ const currentPageId = this.pageById(pageId);
+ runInAction(() => {
+ this.loader = currentPageId ? `mutation-loader` : `init-loader`;
+ this.error = undefined;
+ });
+
+ const page = await this.service.fetchById(workspaceSlug, projectId, pageId);
+ runInAction(() => {
+ if (page?.id) set(this.data, [page.id], new PageStore(this.store, page));
+ this.loader = undefined;
+ });
+
+ return page;
+ } catch {
+ runInAction(() => {
+ this.loader = undefined;
+ this.error = {
+ title: "Failed",
+ description: "Failed to fetch the page, Please try again later.",
+ };
+ });
+ }
+ };
+
+ /**
+ * @description create a page
+ * @param {Partial<TPage>} pageData
+ */
+ createPage = async (pageData: Partial<TPage>) => {
+ try {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId) return undefined;
+
+ runInAction(() => {
+ this.loader = "mutation-loader";
+ this.error = undefined;
+ });
+
+ const page = await this.service.create(workspaceSlug, projectId, pageData);
+ runInAction(() => {
+ if (page?.id) set(this.data, [page.id], new PageStore(this.store, page));
+ this.loader = undefined;
+ });
+
+ return page;
+ } catch {
+ runInAction(() => {
+ this.loader = undefined;
+ this.error = {
+ title: "Failed",
+ description: "Failed to create a page, Please try again later.",
+ };
+ });
+ }
+ };
+
+ /**
+ * @description delete a page
+ * @param {string} pageId
+ */
+ removePage = async (pageId: string) => {
+ try {
+ const { workspaceSlug, projectId } = this.store.app.router;
+ if (!workspaceSlug || !projectId || !pageId) return undefined;
+
+ await this.service.remove(workspaceSlug, projectId, pageId);
+ runInAction(() => unset(this.data, [pageId]));
+ } catch {
+ runInAction(() => {
+ this.loader = undefined;
+ this.error = {
+ title: "Failed",
+ description: "Failed to delete a page, Please try again later.",
+ };
+ });
+ }
+ };
+}
diff --git a/web/store/project-page.store.ts b/web/store/project-page.store.ts
deleted file mode 100644
index 0e451602d6..0000000000
--- a/web/store/project-page.store.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-import { isThisWeek, isToday, isYesterday } from "date-fns";
-import { set } from "lodash";
-import { makeObservable, observable, runInAction, action, computed } from "mobx";
-// services
-import { PageService } from "@/services/page.service";
-// store
-import { PageStore, IPageStore } from "@/store/page.store";
-// types
-import { IPage, IRecentPages } from "@plane/types";
-import { RootStore } from "./root.store";
-//helpers
-import { getDate } from "helpers/date-time.helper";
-
-export interface IProjectPageStore {
- loader: boolean;
- archivedPageLoader: boolean;
- projectPageMap: Record<string, Record<string, IPageStore>>;
- projectArchivedPageMap: Record<string, Record<string, IPageStore>>;
-
- projectPageIds: string[] | undefined;
- archivedPageIds: string[] | undefined;
- favoriteProjectPageIds: string[] | undefined;
- privateProjectPageIds: string[] | undefined;
- publicProjectPageIds: string[] | undefined;
- recentProjectPages: IRecentPages | undefined;
- // fetch actions
- fetchProjectPages: (workspaceSlug: string, projectId: string) => Promise<void>;
- fetchArchivedProjectPages: (workspaceSlug: string, projectId: string) => Promise<void>;
- // crud actions
- createPage: (workspaceSlug: string, projectId: string, data: Partial<IPage>) => Promise<IPage>;
- deletePage: (workspaceSlug: string, projectId: string, pageId: string) => Promise<void>;
- archivePage: (workspaceSlug: string, projectId: string, pageId: string) => Promise<void>;
- restorePage: (workspaceSlug: string, projectId: string, pageId: string) => Promise<void>;
-}
-
-export class ProjectPageStore implements IProjectPageStore {
- loader: boolean = false;
- archivedPageLoader: boolean = false;
- projectPageMap: Record<string, Record<string, IPageStore>> = {}; // { projectId: [page1, page2] }
- projectArchivedPageMap: Record<string, Record<string, IPageStore>> = {}; // { projectId: [page1, page2] }
-
- // root store
- rootStore;
-
- pageService;
- constructor(_rootStore: RootStore) {
- makeObservable(this, {
- loader: observable.ref,
- archivedPageLoader: observable.ref,
- projectPageMap: observable,
- projectArchivedPageMap: observable,
-
- projectPageIds: computed,
- archivedPageIds: computed,
- favoriteProjectPageIds: computed,
- privateProjectPageIds: computed,
- publicProjectPageIds: computed,
- recentProjectPages: computed,
-
- // fetch actions
- fetchProjectPages: action,
- fetchArchivedProjectPages: action,
- // crud actions
- createPage: action,
- deletePage: action,
- });
- this.rootStore = _rootStore;
-
- this.pageService = new PageService();
- }
-
- get projectPageIds() {
- const projectId = this.rootStore.app.router.projectId;
- if (!projectId || !this.projectPageMap?.[projectId]) return [];
-
- const allProjectIds = Object.keys(this.projectPageMap[projectId]);
- return allProjectIds.sort((a, b) => {
- const dateA = getDate(this.projectPageMap[projectId]?.[a]?.created_at)?.getTime() ?? 0;
- const dateB = getDate(this.projectPageMap[projectId]?.[b]?.created_at)?.getTime() ?? 0;
- return dateB - dateA;
- });
- }
-
- get archivedPageIds() {
- const projectId = this.rootStore.app.router.projectId;
- if (!projectId || !this.projectArchivedPageMap[projectId]) return [];
- const archivedPages = Object.keys(this.projectArchivedPageMap[projectId]);
- return archivedPages.sort((a, b) => {
- const dateA = getDate(this.projectArchivedPageMap[projectId]?.[a]?.created_at)?.getTime() ?? 0;
- const dateB = getDate(this.projectArchivedPageMap[projectId]?.[b]?.created_at)?.getTime() ?? 0;
- return dateB - dateA;
- });
- }
-
- get favoriteProjectPageIds() {
- const projectId = this.rootStore.app.router.projectId;
- if (!this.projectPageIds || !projectId) return [];
-
- const favouritePages: string[] = this.projectPageIds.filter(
- (page) => this.projectPageMap[projectId][page].is_favorite
- );
- return favouritePages;
- }
-
- get privateProjectPageIds() {
- const projectId = this.rootStore.app.router.projectId;
- if (!this.projectPageIds || !projectId) return [];
-
- const privatePages: string[] = this.projectPageIds.filter(
- (page) => this.projectPageMap[projectId][page].access === 1
- );
- return privatePages;
- }
-
- get publicProjectPageIds() {
- const projectId = this.rootStore.app.router.projectId;
- const userId = this.rootStore.user.currentUser?.id;
- if (!this.projectPageIds || !projectId || !userId) return [];
-
- const publicPages: string[] = this.projectPageIds.filter(
- (page) =>
- this.projectPageMap[projectId][page].access === 0 && this.projectPageMap[projectId][page].owned_by === userId
- );
- return publicPages;
- }
-
- get recentProjectPages() {
- const projectId = this.rootStore.app.router.projectId;
- if (!this.projectPageIds || !projectId) return;
-
- const today: string[] = this.projectPageIds.filter((page) => {
- const updatedAt = getDate(this.projectPageMap[projectId]?.[page]?.updated_at);
- return updatedAt && isToday(updatedAt);
- });
-
- const yesterday: string[] = this.projectPageIds.filter((page) => {
- const updatedAt = getDate(this.projectPageMap[projectId]?.[page]?.updated_at);
- return updatedAt && isYesterday(updatedAt);
- });
-
- const this_week: string[] = this.projectPageIds.filter((page) => {
- const pageUpdatedAt = getDate(this.projectPageMap[projectId]?.[page]?.updated_at);
- return pageUpdatedAt && isThisWeek(pageUpdatedAt) && !isToday(pageUpdatedAt) && !isYesterday(pageUpdatedAt);
- });
-
- const older: string[] = this.projectPageIds.filter((page) => {
- const pageUpdatedAt = getDate(this.projectPageMap[projectId]?.[page]?.updated_at);
- return pageUpdatedAt && !isThisWeek(pageUpdatedAt) && !isYesterday(pageUpdatedAt);
- });
-
- return { today, yesterday, this_week, older };
- }
-
- /**
- * Fetching all the pages for a specific project
- * @param workspaceSlug
- * @param projectId
- */
- fetchProjectPages = async (workspaceSlug: string, projectId: string) => {
- try {
- this.loader = true;
- await this.pageService.getProjectPages(workspaceSlug, projectId).then((response) => {
- runInAction(() => {
- for (const page of response) {
- set(this.projectPageMap, [projectId, page.id], new PageStore(page, this.rootStore));
- }
- this.loader = false;
- });
- return response;
- });
- } catch (e) {
- this.loader = false;
-
- throw e;
- }
- };
-
- /**
- * fetches all archived pages for a project.
- * @param workspaceSlug
- * @param projectId
- * @returns Promise<IPage[]>
- */
- fetchArchivedProjectPages = async (workspaceSlug: string, projectId: string) => {
- try {
- this.archivedPageLoader = true;
- await this.pageService.getArchivedPages(workspaceSlug, projectId).then((response) => {
- runInAction(() => {
- for (const page of response) {
- set(this.projectArchivedPageMap, [projectId, page.id], new PageStore(page, this.rootStore));
- }
- this.archivedPageLoader = false;
- });
- return response;
- });
- } catch (e) {
- this.archivedPageLoader = false;
- throw e;
- }
- };
-
- /**
- * Creates a new page using the api and updated the local state in store
- * @param workspaceSlug
- * @param projectId
- * @param data
- */
- createPage = async (workspaceSlug: string, projectId: string, data: Partial<IPage>) => {
- const response = await this.pageService.createPage(workspaceSlug, projectId, data);
- runInAction(() => {
- set(this.projectPageMap, [projectId, response.id], new PageStore(response, this.rootStore));
- });
- return response;
- };
-
- /**
- * delete a page using the api and updates the local state in store
- * @param workspaceSlug
- * @param projectId
- * @param pageId
- * @returns
- */
- deletePage = async (workspaceSlug: string, projectId: string, pageId: string) => {
- const response = await this.pageService.deletePage(workspaceSlug, projectId, pageId);
- runInAction(() => {
- delete this.projectArchivedPageMap[projectId][pageId];
- });
- return response;
- };
-
- /**
- * Mark a page archived
- * @param workspaceSlug
- * @param projectId
- * @param pageId
- */
- archivePage = async (workspaceSlug: string, projectId: string, pageId: string) => {
- runInAction(() => {
- set(this.projectArchivedPageMap, [projectId, pageId], this.projectPageMap[projectId][pageId]);
- set(this.projectArchivedPageMap[projectId][pageId], "archived_at", new Date().toISOString());
- delete this.projectPageMap[projectId][pageId];
- });
- const response = await this.pageService.archivePage(workspaceSlug, projectId, pageId).catch(() => {
- runInAction(() => {
- set(this.projectPageMap, [projectId, pageId], this.projectArchivedPageMap[projectId][pageId]);
- set(this.projectPageMap[projectId][pageId], "archived_at", null);
- delete this.projectArchivedPageMap[projectId][pageId];
- });
- });
- return response;
- };
-
- /**
- * Restore a page from archived pages to pages
- * @param workspaceSlug
- * @param projectId
- * @param pageId
- */
- restorePage = async (workspaceSlug: string, projectId: string, pageId: string) => {
- const pageArchivedAt = this.projectArchivedPageMap[projectId][pageId].archived_at;
- runInAction(() => {
- set(this.projectPageMap, [projectId, pageId], this.projectArchivedPageMap[projectId][pageId]);
- set(this.projectPageMap[projectId][pageId], "archived_at", null);
- delete this.projectArchivedPageMap[projectId][pageId];
- });
- await this.pageService.restorePage(workspaceSlug, projectId, pageId).catch(() => {
- runInAction(() => {
- set(this.projectArchivedPageMap, [projectId, pageId], this.projectPageMap[projectId][pageId]);
- set(this.projectArchivedPageMap[projectId][pageId], "archived_at", pageArchivedAt);
- delete this.projectPageMap[projectId][pageId];
- });
- });
- };
-}
diff --git a/web/store/root.store.ts b/web/store/root.store.ts
index d0be5b452c..d28c417992 100644
--- a/web/store/root.store.ts
+++ b/web/store/root.store.ts
@@ -11,11 +11,10 @@ import { GlobalViewStore, IGlobalViewStore } from "./global-view.store";
import { IssueRootStore, IIssueRootStore } from "./issue/root.store";
import { ILabelStore, LabelStore } from "./label.store";
import { IMemberRootStore, MemberRootStore } from "./member";
-import { IMentionStore, MentionStore } from "./mention.store";
import { IModuleStore, ModulesStore } from "./module.store";
import { IModuleFilterStore, ModuleFilterStore } from "./module_filter.store";
+import { IProjectPageStore, ProjectPageStore } from "./pages/project-page.store";
import { IProjectRootStore, ProjectRootStore } from "./project";
-import { IProjectPageStore, ProjectPageStore } from "./project-page.store";
import { IProjectViewStore, ProjectViewStore } from "./project-view.store";
import { IStateStore, StateStore } from "./state.store";
import { IUserRootStore, UserRootStore } from "./user";
@@ -40,7 +39,6 @@ export class RootStore {
state: IStateStore;
label: ILabelStore;
estimate: IEstimateStore;
- mention: IMentionStore;
dashboard: IDashboardStore;
projectPages: IProjectPageStore;
projectInbox: IProjectInboxStore;
@@ -63,7 +61,6 @@ export class RootStore {
this.state = new StateStore(this);
this.label = new LabelStore(this);
this.estimate = new EstimateStore(this);
- this.mention = new MentionStore(this);
this.dashboard = new DashboardStore(this);
// inbox
this.projectInbox = new ProjectInboxStore(this);
@@ -85,7 +82,6 @@ export class RootStore {
this.state = new StateStore(this);
this.label = new LabelStore(this);
this.estimate = new EstimateStore(this);
- this.mention = new MentionStore(this);
this.dashboard = new DashboardStore(this);
this.projectInbox = new ProjectInboxStore(this);
this.projectPages = new ProjectPageStore(this);
diff --git a/web/styles/globals.css b/web/styles/globals.css
index b687bca93c..cc9c0b2738 100644
--- a/web/styles/globals.css
+++ b/web/styles/globals.css
@@ -44,8 +44,8 @@
--color-primary-900: 13, 24, 51;
--color-background-100: 255, 255, 255; /* primary bg */
- --color-background-90: 250, 250, 250; /* secondary bg */
- --color-background-80: 245, 245, 245; /* tertiary bg */
+ --color-background-90: 247, 247, 247; /* secondary bg */
+ --color-background-80: 232, 232, 232; /* tertiary bg */
--color-text-100: 23, 23, 23; /* primary text */
--color-text-200: 58, 58, 58; /* secondary text */
@@ -110,8 +110,8 @@
color-scheme: light !important;
--color-background-100: 255, 255, 255; /* primary bg */
- --color-background-90: 250, 250, 250; /* secondary bg */
- --color-background-80: 245, 245, 245; /* tertiary bg */
+ --color-background-90: 247, 247, 247; /* secondary bg */
+ --color-background-80: 232, 232, 232; /* tertiary bg */
}
[data-theme="light"] {
@@ -189,9 +189,9 @@
[data-theme="dark-contrast"] {
color-scheme: dark !important;
- --color-background-100: 7, 7, 7; /* primary bg */
- --color-background-90: 11, 11, 11; /* secondary bg */
- --color-background-80: 23, 23, 23; /* tertiary bg */
+ --color-background-100: 25, 25, 25; /* primary bg */
+ --color-background-90: 32, 32, 32; /* secondary bg */
+ --color-background-80: 44, 44, 44; /* tertiary bg */
--color-shadow-2xs: 0px 0px 1px 0px rgba(0, 0, 0, 0.15), 0px 1px 3px 0px rgba(0, 0, 0, 0.5);
--color-shadow-xs: 0px 0px 2px 0px rgba(0, 0, 0, 0.2), 0px 2px 4px 0px rgba(0, 0, 0, 0.5);
diff --git a/yarn.lock b/yarn.lock
index 88f5d4e553..d8cca2a772 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -6907,6 +6907,11 @@ prosemirror-changeset@^2.2.0:
dependencies:
prosemirror-transform "^1.0.0"
+prosemirror-codemark@^0.4.2:
+ version "0.4.2"
+ resolved "https://registry.yarnpkg.com/prosemirror-codemark/-/prosemirror-codemark-0.4.2.tgz#b4d0a57c0f1f6c6667e2a1ae7cfb6ba031dfb2e5"
+ integrity sha512-4n+PnGQToa/vTjn0OiivUvE8/moLtguUAfry8UA4Q8p47MhqT2Qpf2zBLustX5Upi4mSp3z1ZYBqLLovZC6abA==
+
prosemirror-collab@^1.3.0:
version "1.3.1"
resolved "https://registry.yarnpkg.com/prosemirror-collab/-/prosemirror-collab-1.3.1.tgz#0e8c91e76e009b53457eb3b3051fb68dad029a33"