conflict: merge conflicts resolved

This commit is contained in:
Ramesh Kumar Chandra 2023-11-09 16:28:45 +05:30
commit 0aa5a4bdb7
286 changed files with 3257 additions and 3262 deletions

View File

@ -1,8 +1,10 @@
# Environment Variables
Environment variables are distributed in various files. Please refer them carefully.
## {PROJECT_FOLDER}/.env
File is available in the project root folder
```
@ -41,25 +43,37 @@ USE_MINIO=1
# Nginx Configuration
NGINX_PORT=80
```
## {PROJECT_FOLDER}/web/.env.example
```
# Enable/Disable OAUTH - default 0 for selfhosted instance
NEXT_PUBLIC_ENABLE_OAUTH=0
# Public boards deploy URL
NEXT_PUBLIC_DEPLOY_URL="http://localhost/spaces"
```
## {PROJECT_FOLDER}/spaces/.env.example
```
# Flag to toggle OAuth
NEXT_PUBLIC_ENABLE_OAUTH=0
```
## {PROJECT_FOLDER}/apiserver/.env
```
# Backend
# Debug value for api server use it as 0 for production use
@ -126,7 +140,9 @@ ENABLE_SIGNUP="1"
# Email Redirection URL
WEB_URL="http://localhost"
```
## Updates
- The environment variable NEXT_PUBLIC_API_BASE_URL has been removed from both the web and space projects.
- The naming convention for containers and images has been updated.
- The plane-worker image will no longer be maintained, as it has been merged with plane-backend.

View File

@ -7,8 +7,6 @@ from plane.db.models import State
class StateSerializer(BaseSerializer):
workspace_detail = WorkspaceLiteSerializer(read_only=True, source="workspace")
project_detail = ProjectLiteSerializer(read_only=True, source="project")
class Meta:
model = State

View File

@ -20,11 +20,19 @@ urlpatterns = [
StateViewSet.as_view(
{
"get": "retrieve",
"put": "update",
"patch": "partial_update",
"delete": "destroy",
}
),
name="project-state",
),
path(
"workspaces/<str:slug>/projects/<uuid:project_id>/states/<uuid:pk>/mark-default/",
StateViewSet.as_view(
{
"post": "mark_as_default",
}
),
name="project-state",
),
]

View File

@ -47,36 +47,45 @@ class StateViewSet(BaseViewSet):
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def list(self, request, slug, project_id):
state_dict = dict()
states = StateSerializer(self.get_queryset(), many=True).data
grouped = request.GET.get("grouped", False)
if grouped == "true":
state_dict = {}
for key, value in groupby(
sorted(states, key=lambda state: state["group"]),
lambda state: state.get("group"),
):
state_dict[str(key)] = list(value)
return Response(state_dict, status=status.HTTP_200_OK)
return Response(states, status=status.HTTP_200_OK)
def mark_as_default(self, request, slug, project_id, pk):
# Select all the states which are marked as default
_ = State.objects.filter(
workspace__slug=slug, project_id=project_id, default=True
).update(default=False)
_ = State.objects.filter(
workspace__slug=slug, project_id=project_id, pk=pk
).update(default=True)
return Response(status=status.HTTP_204_NO_CONTENT)
def destroy(self, request, slug, project_id, pk):
state = State.objects.get(
~Q(name="Triage"),
pk=pk, project_id=project_id, workspace__slug=slug,
pk=pk,
project_id=project_id,
workspace__slug=slug,
)
if state.default:
return Response(
{"error": "Default state cannot be deleted"}, status=False
)
return Response({"error": "Default state cannot be deleted"}, status=False)
# Check for any issues in the state
issue_exist = Issue.issue_objects.filter(state=pk).exists()
if issue_exist:
return Response(
{
"error": "The state is not empty, only empty states can be deleted"
},
{"error": "The state is not empty, only empty states can be deleted"},
status=status.HTTP_400_BAD_REQUEST,
)

View File

@ -20,7 +20,7 @@ This allows for extensive customization and flexibility in the Editors created u
1. useEditor - A hook that you can use to extend the Plane editor.
| Prop | Type | Description |
| --- | --- | --- |
| ------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `extensions` | `Extension[]` | An array of custom extensions you want to add into the editor to extend it's core features |
| `editorProps` | `EditorProps` | Extend the editor props by passing in a custom props object |
| `uploadFile` | `(file: File) => Promise<string>` | A function that handles file upload. It takes a file as input and handles the process of uploading that file. |
@ -35,7 +35,7 @@ This allows for extensive customization and flexibility in the Editors created u
2. useReadOnlyEditor - A hook that can be used to extend a Read Only instance of the core editor.
| Prop | Type | Description |
| --- | --- | --- |
| -------------- | ------------- | ------------------------------------------------------------------------------------------ |
| `value` | `string` | The initial content of the editor. |
| `forwardedRef` | `any` | Pass this in whenever you want to control the editor's state from an external component |
| `extensions` | `Extension[]` | An array of custom extensions you want to add into the editor to extend it's core features |
@ -51,7 +51,11 @@ This allows for extensive customization and flexibility in the Editors created u
5. Extending with Custom Styles
```ts
const customEditorClassNames = getEditorClassNames({ noBorder, borderOnFocus, customClassName });
const customEditorClassNames = getEditorClassNames({
noBorder,
borderOnFocus,
customClassName,
});
```
## Core features

View File

@ -3,18 +3,36 @@ import { UploadImage } from "../types/upload-image";
import { startImageUpload } from "../ui/plugins/upload-image";
export const toggleHeadingOne = (editor: Editor, range?: Range) => {
if (range) editor.chain().focus().deleteRange(range).setNode("heading", { level: 1 }).run();
else editor.chain().focus().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).setNode("heading", { level: 2 }).run();
else editor.chain().focus().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).setNode("heading", { level: 3 }).run();
else editor.chain().focus().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,7 +55,8 @@ export const toggleCode = (editor: Editor, range?: Range) => {
else editor.chain().focus().toggleCode().run();
};
export const toggleOrderedList = (editor: Editor, range?: Range) => {
if (range) editor.chain().focus().deleteRange(range).toggleOrderedList().run();
if (range)
editor.chain().focus().deleteRange(range).toggleOrderedList().run();
else editor.chain().focus().toggleOrderedList().run();
};
@ -48,7 +67,7 @@ export const toggleBulletList = (editor: Editor, range?: Range) => {
export const toggleTaskList = (editor: Editor, range?: Range) => {
if (range) editor.chain().focus().deleteRange(range).toggleTaskList().run();
else editor.chain().focus().toggleTaskList().run()
else editor.chain().focus().toggleTaskList().run();
};
export const toggleStrike = (editor: Editor, range?: Range) => {
@ -57,13 +76,37 @@ export const toggleStrike = (editor: Editor, range?: Range) => {
};
export const toggleBlockquote = (editor: Editor, range?: Range) => {
if (range) editor.chain().focus().deleteRange(range).toggleNode("paragraph", "paragraph").toggleBlockquote().run();
else editor.chain().focus().toggleNode("paragraph", "paragraph").toggleBlockquote().run();
if (range)
editor
.chain()
.focus()
.deleteRange(range)
.toggleNode("paragraph", "paragraph")
.toggleBlockquote()
.run();
else
editor
.chain()
.focus()
.toggleNode("paragraph", "paragraph")
.toggleBlockquote()
.run();
};
export const insertTableCommand = (editor: Editor, range?: Range) => {
if (range) editor.chain().focus().deleteRange(range).insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run();
else editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run();
if (range)
editor
.chain()
.focus()
.deleteRange(range)
.insertTable({ rows: 3, cols: 3, withHeaderRow: true })
.run();
else
editor
.chain()
.focus()
.insertTable({ rows: 3, cols: 3, withHeaderRow: true })
.run();
};
export const unsetLinkEditor = (editor: Editor) => {
@ -74,7 +117,14 @@ export const setLinkEditor = (editor: Editor, url: string) => {
editor.chain().focus().setLink({ href: url }).run();
};
export const insertImageCommand = (editor: Editor, uploadFile: UploadImage, setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void, range?: Range) => {
export const insertImageCommand = (
editor: Editor,
uploadFile: UploadImage,
setIsSubmitting?: (
isSubmitting: "submitting" | "submitted" | "saved",
) => void,
range?: Range,
) => {
if (range) editor.chain().focus().deleteRange(range).run();
const input = document.createElement("input");
input.type = "file";
@ -88,4 +138,3 @@ export const insertImageCommand = (editor: Editor, uploadFile: UploadImage, setI
};
input.click();
};

View File

@ -6,19 +6,24 @@ interface EditorClassNames {
customClassName?: string;
}
export const getEditorClassNames = ({ noBorder, borderOnFocus, customClassName }: 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
);
export const getEditorClassNames = ({
noBorder,
borderOnFocus,
customClassName,
}: 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,
);
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
}
export const findTableAncestor = (
node: Node | null
node: Node | null,
): HTMLTableElement | null => {
while (node !== null && node.nodeName !== "TABLE") {
node = node.parentNode;
@ -27,10 +32,10 @@ export const findTableAncestor = (
};
export const getTrimmedHTML = (html: string) => {
html = html.replace(/^(<p><\/p>)+/, '');
html = html.replace(/(<p><\/p>)+$/, '');
html = html.replace(/^(<p><\/p>)+/, "");
html = html.replace(/(<p><\/p>)+$/, "");
return html;
}
};
export const isValidHttpUrl = (string: string): boolean => {
let url: URL;
@ -42,4 +47,4 @@ export const isValidHttpUrl = (string: string): boolean => {
}
return url.protocol === "http:" || url.protocol === "https:";
}
};

View File

@ -5,6 +5,6 @@ export type IMentionSuggestion = {
title: string;
subtitle: string;
redirect_uri: string;
}
};
export type IMentionHighlight = string
export type IMentionHighlight = string;

View File

@ -8,10 +8,16 @@ interface EditorContentProps {
children?: ReactNode;
}
export const EditorContentWrapper = ({ editor, editorContentCustomClassNames = '', children }: EditorContentProps) => (
export const EditorContentWrapper = ({
editor,
editorContentCustomClassNames = "",
children,
}: EditorContentProps) => (
<div className={`contentEditor ${editorContentCustomClassNames}`}>
<EditorContent editor={editor} />
{(editor?.isActive("image") && editor?.isEditable) && <ImageResizer editor={editor} />}
{editor?.isActive("image") && editor?.isEditable && (
<ImageResizer editor={editor} />
)}
{children}
</div>
);

View File

@ -3,7 +3,9 @@ import Moveable from "react-moveable";
export const ImageResizer = ({ editor }: { editor: Editor }) => {
const updateMediaSize = () => {
const imageInfo = document.querySelector(".ProseMirror-selectednode") as HTMLImageElement;
const imageInfo = document.querySelector(
".ProseMirror-selectednode",
) as HTMLImageElement;
if (imageInfo) {
const selection = editor.state.selection;
editor.commands.setImage({

View File

@ -3,9 +3,16 @@ import TrackImageDeletionPlugin from "../../plugins/delete-image";
import UploadImagesPlugin from "../../plugins/upload-image";
import { DeleteImage } from "../../../types/delete-image";
const ImageExtension = (deleteImage: DeleteImage) => Image.extend({
const ImageExtension = (
deleteImage: DeleteImage,
cancelUploadImage?: () => any,
) =>
Image.extend({
addProseMirrorPlugins() {
return [UploadImagesPlugin(), TrackImageDeletionPlugin(deleteImage)];
return [
UploadImagesPlugin(cancelUploadImage),
TrackImageDeletionPlugin(deleteImage),
];
},
addAttributes() {
return {
@ -18,6 +25,6 @@ const ImageExtension = (deleteImage: DeleteImage) => Image.extend({
},
};
},
});
});
export default ImageExtension;

View File

@ -20,10 +20,13 @@ import { isValidHttpUrl } from "../../lib/utils";
import { IMentionSuggestion } from "../../types/mention-suggestion";
import { Mentions } from "../mentions";
export const CoreEditorExtensions = (
mentionConfig: { mentionSuggestions: IMentionSuggestion[], mentionHighlights: string[] },
mentionConfig: {
mentionSuggestions: IMentionSuggestion[];
mentionHighlights: string[];
},
deleteFile: DeleteImage,
cancelUploadImage?: () => any,
) => [
StarterKit.configure({
bulletList: {
@ -70,7 +73,7 @@ export const CoreEditorExtensions = (
"text-custom-primary-300 underline underline-offset-[3px] hover:text-custom-primary-500 transition-colors cursor-pointer",
},
}),
ImageExtension(deleteFile).configure({
ImageExtension(deleteFile, cancelUploadImage).configure({
HTMLAttributes: {
class: "rounded-lg border border-custom-border-300",
},
@ -97,5 +100,9 @@ export const CoreEditorExtensions = (
TableHeader,
TableCell,
TableRow,
Mentions(mentionConfig.mentionSuggestions, mentionConfig.mentionHighlights, false),
];
Mentions(
mentionConfig.mentionSuggestions,
mentionConfig.mentionHighlights,
false,
),
];

View File

@ -1 +1 @@
export { default as default } from "./table-cell"
export { default as default } from "./table-cell";

View File

@ -1,7 +1,7 @@
import { mergeAttributes, Node } from "@tiptap/core"
import { mergeAttributes, Node } from "@tiptap/core";
export interface TableCellOptions {
HTMLAttributes: Record<string, any>
HTMLAttributes: Record<string, any>;
}
export default Node.create<TableCellOptions>({
@ -9,8 +9,8 @@ export default Node.create<TableCellOptions>({
addOptions() {
return {
HTMLAttributes: {}
}
HTMLAttributes: {},
};
},
content: "paragraph+",
@ -18,24 +18,24 @@ export default Node.create<TableCellOptions>({
addAttributes() {
return {
colspan: {
default: 1
default: 1,
},
rowspan: {
default: 1
default: 1,
},
colwidth: {
default: null,
parseHTML: (element) => {
const colwidth = element.getAttribute("colwidth")
const value = colwidth ? [parseInt(colwidth, 10)] : null
const colwidth = element.getAttribute("colwidth");
const value = colwidth ? [parseInt(colwidth, 10)] : null;
return value
}
return value;
},
},
background: {
default: "none"
}
}
default: "none",
},
};
},
tableRole: "cell",
@ -43,16 +43,16 @@ export default Node.create<TableCellOptions>({
isolating: true,
parseHTML() {
return [{ tag: "td" }]
return [{ tag: "td" }];
},
renderHTML({ node, HTMLAttributes }) {
return [
"td",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
style: `background-color: ${node.attrs.background}`
style: `background-color: ${node.attrs.background}`,
}),
0
]
}
})
0,
];
},
});

View File

@ -1 +1 @@
export { default as default } from "./table-header"
export { default as default } from "./table-header";

View File

@ -1,15 +1,15 @@
import { mergeAttributes, Node } from "@tiptap/core"
import { mergeAttributes, Node } from "@tiptap/core";
export interface TableHeaderOptions {
HTMLAttributes: Record<string, any>
HTMLAttributes: Record<string, any>;
}
export default Node.create<TableHeaderOptions>({
name: "tableHeader",
addOptions() {
return {
HTMLAttributes: {}
}
HTMLAttributes: {},
};
},
content: "paragraph+",
@ -17,24 +17,24 @@ export default Node.create<TableHeaderOptions>({
addAttributes() {
return {
colspan: {
default: 1
default: 1,
},
rowspan: {
default: 1
default: 1,
},
colwidth: {
default: null,
parseHTML: (element) => {
const colwidth = element.getAttribute("colwidth")
const value = colwidth ? [parseInt(colwidth, 10)] : null
const colwidth = element.getAttribute("colwidth");
const value = colwidth ? [parseInt(colwidth, 10)] : null;
return value
}
return value;
},
},
background: {
default: "rgb(var(--color-primary-100))"
}
}
default: "rgb(var(--color-primary-100))",
},
};
},
tableRole: "header_cell",
@ -42,16 +42,16 @@ export default Node.create<TableHeaderOptions>({
isolating: true,
parseHTML() {
return [{ tag: "th" }]
return [{ tag: "th" }];
},
renderHTML({ node, HTMLAttributes }) {
return [
"th",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes, {
style: `background-color: ${node.attrs.background}`
style: `background-color: ${node.attrs.background}`,
}),
0
]
}
})
0,
];
},
});

View File

@ -1 +1 @@
export { default as default } from "./table-row"
export { default as default } from "./table-row";

View File

@ -1,7 +1,7 @@
import { mergeAttributes, Node } from "@tiptap/core"
import { mergeAttributes, Node } from "@tiptap/core";
export interface TableRowOptions {
HTMLAttributes: Record<string, any>
HTMLAttributes: Record<string, any>;
}
export default Node.create<TableRowOptions>({
@ -9,8 +9,8 @@ export default Node.create<TableRowOptions>({
addOptions() {
return {
HTMLAttributes: {}
}
HTMLAttributes: {},
};
},
content: "(tableCell | tableHeader)*",
@ -18,14 +18,14 @@ export default Node.create<TableRowOptions>({
tableRole: "row",
parseHTML() {
return [{ tag: "tr" }]
return [{ tag: "tr" }];
},
renderHTML({ HTMLAttributes }) {
return [
"tr",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
0
]
}
})
0,
];
},
});

View File

@ -38,7 +38,7 @@ const icons = {
/>
</svg>
`,
insertBottomTableIcon:`<svg
insertBottomTableIcon: `<svg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}

View File

@ -1 +1 @@
export { default as default } from "./table"
export { default as default } from "./table";

View File

@ -68,7 +68,12 @@ export function tableControls() {
const { hoveredTable, hoveredCell } = pluginState.values;
const docSize = state.doc.content.size;
if (hoveredTable && hoveredCell && hoveredTable.pos < docSize && hoveredCell.pos < docSize) {
if (
hoveredTable &&
hoveredCell &&
hoveredTable.pos < docSize &&
hoveredCell.pos < docSize
) {
const decorations = [
Decoration.node(
hoveredTable.pos,

View File

@ -202,6 +202,7 @@ function createToolbox({
"div",
{
className: "toolboxItem",
itemType: "button",
onClick() {
onClickItem(item);
},
@ -253,6 +254,7 @@ function createColorPickerToolbox({
"div",
{
className: "toolboxItem",
itemType: "button",
onClick: () => {
onSelectColor(value);
colorPicker.hide();
@ -331,7 +333,9 @@ export class TableView implements NodeView {
this.rowsControl = h(
"div",
{ className: "rowsControl" },
h("button", {
h("div", {
itemType: "button",
className: "rowsControlDiv",
onClick: () => this.selectRow(),
}),
);
@ -339,7 +343,9 @@ export class TableView implements NodeView {
this.columnsControl = h(
"div",
{ className: "columnsControl" },
h("button", {
h("div", {
itemType: "button",
className: "columnsControlDiv",
onClick: () => this.selectColumn(),
}),
);
@ -352,7 +358,7 @@ export class TableView implements NodeView {
);
this.columnsToolbox = createToolbox({
triggerButton: this.columnsControl.querySelector("button"),
triggerButton: this.columnsControl.querySelector(".columnsControlDiv"),
items: columnsToolboxItems,
tippyOptions: {
...defaultTippyOptions,

View File

@ -1,6 +1,12 @@
import { TextSelection } from "@tiptap/pm/state"
import { TextSelection } from "@tiptap/pm/state";
import { callOrReturn, getExtensionField, mergeAttributes, Node, ParentConfig } from "@tiptap/core"
import {
callOrReturn,
getExtensionField,
mergeAttributes,
Node,
ParentConfig,
} from "@tiptap/core";
import {
addColumnAfter,
addColumnBefore,
@ -18,64 +24,64 @@ import {
splitCell,
tableEditing,
toggleHeader,
toggleHeaderCell
} from "@tiptap/prosemirror-tables"
toggleHeaderCell,
} from "@tiptap/prosemirror-tables";
import { tableControls } from "./table-controls"
import { TableView } from "./table-view"
import { createTable } from "./utilities/create-table"
import { deleteTableWhenAllCellsSelected } from "./utilities/delete-table-when-all-cells-selected"
import { tableControls } from "./table-controls";
import { TableView } from "./table-view";
import { createTable } from "./utilities/create-table";
import { deleteTableWhenAllCellsSelected } from "./utilities/delete-table-when-all-cells-selected";
export interface TableOptions {
HTMLAttributes: Record<string, any>
resizable: boolean
handleWidth: number
cellMinWidth: number
lastColumnResizable: boolean
allowTableNodeSelection: boolean
HTMLAttributes: Record<string, any>;
resizable: boolean;
handleWidth: number;
cellMinWidth: number;
lastColumnResizable: boolean;
allowTableNodeSelection: boolean;
}
declare module "@tiptap/core" {
interface Commands<ReturnType> {
table: {
insertTable: (options?: {
rows?: number
cols?: number
withHeaderRow?: boolean
}) => ReturnType
addColumnBefore: () => ReturnType
addColumnAfter: () => ReturnType
deleteColumn: () => ReturnType
addRowBefore: () => ReturnType
addRowAfter: () => ReturnType
deleteRow: () => ReturnType
deleteTable: () => ReturnType
mergeCells: () => ReturnType
splitCell: () => ReturnType
toggleHeaderColumn: () => ReturnType
toggleHeaderRow: () => ReturnType
toggleHeaderCell: () => ReturnType
mergeOrSplit: () => ReturnType
setCellAttribute: (name: string, value: any) => ReturnType
goToNextCell: () => ReturnType
goToPreviousCell: () => ReturnType
fixTables: () => ReturnType
rows?: number;
cols?: number;
withHeaderRow?: boolean;
}) => ReturnType;
addColumnBefore: () => ReturnType;
addColumnAfter: () => ReturnType;
deleteColumn: () => ReturnType;
addRowBefore: () => ReturnType;
addRowAfter: () => ReturnType;
deleteRow: () => ReturnType;
deleteTable: () => ReturnType;
mergeCells: () => ReturnType;
splitCell: () => ReturnType;
toggleHeaderColumn: () => ReturnType;
toggleHeaderRow: () => ReturnType;
toggleHeaderCell: () => ReturnType;
mergeOrSplit: () => ReturnType;
setCellAttribute: (name: string, value: any) => ReturnType;
goToNextCell: () => ReturnType;
goToPreviousCell: () => ReturnType;
fixTables: () => ReturnType;
setCellSelection: (position: {
anchorCell: number
headCell?: number
}) => ReturnType
}
anchorCell: number;
headCell?: number;
}) => ReturnType;
};
}
interface NodeConfig<Options, Storage> {
tableRole?:
| string
| ((this: {
name: string
options: Options
storage: Storage
parent: ParentConfig<NodeConfig<Options>>["tableRole"]
}) => string)
name: string;
options: Options;
storage: Storage;
parent: ParentConfig<NodeConfig<Options>>["tableRole"];
}) => string);
}
}
@ -89,8 +95,8 @@ export default Node.create({
handleWidth: 5,
cellMinWidth: 100,
lastColumnResizable: true,
allowTableNodeSelection: true
}
allowTableNodeSelection: true,
};
},
content: "tableRow+",
@ -104,103 +110,111 @@ export default Node.create({
allowGapCursor: false,
parseHTML() {
return [{ tag: "table" }]
return [{ tag: "table" }];
},
renderHTML({ HTMLAttributes }) {
return [
"table",
mergeAttributes(this.options.HTMLAttributes, HTMLAttributes),
["tbody", 0]
]
["tbody", 0],
];
},
addCommands() {
return {
insertTable:
({ rows = 3, cols = 3, withHeaderRow = true} = {}) =>
({ rows = 3, cols = 3, withHeaderRow = true } = {}) =>
({ tr, dispatch, editor }) => {
const node = createTable(
editor.schema,
rows,
cols,
withHeaderRow
)
const node = createTable(editor.schema, rows, cols, withHeaderRow);
if (dispatch) {
const offset = tr.selection.anchor + 1
const offset = tr.selection.anchor + 1;
tr.replaceSelectionWith(node)
.scrollIntoView()
.setSelection(
TextSelection.near(tr.doc.resolve(offset))
)
.setSelection(TextSelection.near(tr.doc.resolve(offset)));
}
return true
return true;
},
addColumnBefore:
() =>
({ state, dispatch }) => addColumnBefore(state, dispatch),
({ state, dispatch }) =>
addColumnBefore(state, dispatch),
addColumnAfter:
() =>
({ state, dispatch }) => addColumnAfter(state, dispatch),
({ state, dispatch }) =>
addColumnAfter(state, dispatch),
deleteColumn:
() =>
({ state, dispatch }) => deleteColumn(state, dispatch),
({ state, dispatch }) =>
deleteColumn(state, dispatch),
addRowBefore:
() =>
({ state, dispatch }) => addRowBefore(state, dispatch),
({ state, dispatch }) =>
addRowBefore(state, dispatch),
addRowAfter:
() =>
({ state, dispatch }) => addRowAfter(state, dispatch),
({ state, dispatch }) =>
addRowAfter(state, dispatch),
deleteRow:
() =>
({ state, dispatch }) => deleteRow(state, dispatch),
({ state, dispatch }) =>
deleteRow(state, dispatch),
deleteTable:
() =>
({ state, dispatch }) => deleteTable(state, dispatch),
({ state, dispatch }) =>
deleteTable(state, dispatch),
mergeCells:
() =>
({ state, dispatch }) => mergeCells(state, dispatch),
({ state, dispatch }) =>
mergeCells(state, dispatch),
splitCell:
() =>
({ state, dispatch }) => splitCell(state, dispatch),
({ state, dispatch }) =>
splitCell(state, dispatch),
toggleHeaderColumn:
() =>
({ state, dispatch }) => toggleHeader("column")(state, dispatch),
({ state, dispatch }) =>
toggleHeader("column")(state, dispatch),
toggleHeaderRow:
() =>
({ state, dispatch }) => toggleHeader("row")(state, dispatch),
({ state, dispatch }) =>
toggleHeader("row")(state, dispatch),
toggleHeaderCell:
() =>
({ state, dispatch }) => toggleHeaderCell(state, dispatch),
({ state, dispatch }) =>
toggleHeaderCell(state, dispatch),
mergeOrSplit:
() =>
({ state, dispatch }) => {
if (mergeCells(state, dispatch)) {
return true
return true;
}
return splitCell(state, dispatch)
return splitCell(state, dispatch);
},
setCellAttribute:
(name, value) =>
({ state, dispatch }) => setCellAttr(name, value)(state, dispatch),
({ state, dispatch }) =>
setCellAttr(name, value)(state, dispatch),
goToNextCell:
() =>
({ state, dispatch }) => goToNextCell(1)(state, dispatch),
({ state, dispatch }) =>
goToNextCell(1)(state, dispatch),
goToPreviousCell:
() =>
({ state, dispatch }) => goToNextCell(-1)(state, dispatch),
({ state, dispatch }) =>
goToNextCell(-1)(state, dispatch),
fixTables:
() =>
({ state, dispatch }) => {
if (dispatch) {
fixTables(state)
fixTables(state);
}
return true
return true;
},
setCellSelection:
(position) =>
@ -209,62 +223,62 @@ export default Node.create({
const selection = CellSelection.create(
tr.doc,
position.anchorCell,
position.headCell
)
position.headCell,
);
// @ts-ignore
tr.setSelection(selection)
tr.setSelection(selection);
}
return true
}
}
return true;
},
};
},
addKeyboardShortcuts() {
return {
Tab: () => {
if (this.editor.commands.goToNextCell()) {
return true
return true;
}
if (!this.editor.can().addRowAfter()) {
return false
return false;
}
return this.editor.chain().addRowAfter().goToNextCell().run()
return this.editor.chain().addRowAfter().goToNextCell().run();
},
"Shift-Tab": () => this.editor.commands.goToPreviousCell(),
Backspace: deleteTableWhenAllCellsSelected,
"Mod-Backspace": deleteTableWhenAllCellsSelected,
Delete: deleteTableWhenAllCellsSelected,
"Mod-Delete": deleteTableWhenAllCellsSelected
}
"Mod-Delete": deleteTableWhenAllCellsSelected,
};
},
addNodeView() {
return ({ editor, getPos, node, decorations }) => {
const { cellMinWidth } = this.options
const { cellMinWidth } = this.options;
return new TableView(
node,
cellMinWidth,
decorations,
editor,
getPos as () => number
)
}
getPos as () => number,
);
};
},
addProseMirrorPlugins() {
const isResizable = this.options.resizable && this.editor.isEditable
const isResizable = this.options.resizable && this.editor.isEditable;
const plugins = [
tableEditing({
allowTableNodeSelection: this.options.allowTableNodeSelection
allowTableNodeSelection: this.options.allowTableNodeSelection,
}),
tableControls()
]
tableControls(),
];
if (isResizable) {
plugins.unshift(
@ -274,25 +288,25 @@ export default Node.create({
// View: TableView,
// @ts-ignore
lastColumnResizable: this.options.lastColumnResizable
})
)
lastColumnResizable: this.options.lastColumnResizable,
}),
);
}
return plugins
return plugins;
},
extendNodeSchema(extension) {
const context = {
name: extension.name,
options: extension.options,
storage: extension.storage
}
storage: extension.storage,
};
return {
tableRole: callOrReturn(
getExtensionField(extension, "tableRole", context)
)
}
}
})
getExtensionField(extension, "tableRole", context),
),
};
},
});

View File

@ -1,12 +1,12 @@
import { Fragment, Node as ProsemirrorNode, NodeType } from "prosemirror-model"
import { Fragment, Node as ProsemirrorNode, NodeType } from "prosemirror-model";
export function createCell(
cellType: NodeType,
cellContent?: Fragment | ProsemirrorNode | Array<ProsemirrorNode>
cellContent?: Fragment | ProsemirrorNode | Array<ProsemirrorNode>,
): ProsemirrorNode | null | undefined {
if (cellContent) {
return cellType.createChecked(null, cellContent)
return cellType.createChecked(null, cellContent);
}
return cellType.createAndFill()
return cellType.createAndFill();
}

View File

@ -1,45 +1,45 @@
import { Fragment, Node as ProsemirrorNode, Schema } from "@tiptap/pm/model"
import { Fragment, Node as ProsemirrorNode, Schema } from "@tiptap/pm/model";
import { createCell } from "./create-cell"
import { getTableNodeTypes } from "./get-table-node-types"
import { createCell } from "./create-cell";
import { getTableNodeTypes } from "./get-table-node-types";
export function createTable(
schema: Schema,
rowsCount: number,
colsCount: number,
withHeaderRow: boolean,
cellContent?: Fragment | ProsemirrorNode | Array<ProsemirrorNode>
cellContent?: Fragment | ProsemirrorNode | Array<ProsemirrorNode>,
): ProsemirrorNode {
const types = getTableNodeTypes(schema)
const headerCells: ProsemirrorNode[] = []
const cells: ProsemirrorNode[] = []
const types = getTableNodeTypes(schema);
const headerCells: ProsemirrorNode[] = [];
const cells: ProsemirrorNode[] = [];
for (let index = 0; index < colsCount; index += 1) {
const cell = createCell(types.cell, cellContent)
const cell = createCell(types.cell, cellContent);
if (cell) {
cells.push(cell)
cells.push(cell);
}
if (withHeaderRow) {
const headerCell = createCell(types.header_cell, cellContent)
const headerCell = createCell(types.header_cell, cellContent);
if (headerCell) {
headerCells.push(headerCell)
headerCells.push(headerCell);
}
}
}
const rows: ProsemirrorNode[] = []
const rows: ProsemirrorNode[] = [];
for (let index = 0; index < rowsCount; index += 1) {
rows.push(
types.row.createChecked(
null,
withHeaderRow && index === 0 ? headerCells : cells
)
)
withHeaderRow && index === 0 ? headerCells : cells,
),
);
}
return types.table.createChecked(null, rows)
return types.table.createChecked(null, rows);
}

View File

@ -1,39 +1,42 @@
import { findParentNodeClosestToPos, KeyboardShortcutCommand } from "@tiptap/core"
import {
findParentNodeClosestToPos,
KeyboardShortcutCommand,
} from "@tiptap/core";
import { isCellSelection } from "./is-cell-selection"
import { isCellSelection } from "./is-cell-selection";
export const deleteTableWhenAllCellsSelected: KeyboardShortcutCommand = ({
editor
editor,
}) => {
const { selection } = editor.state
const { selection } = editor.state;
if (!isCellSelection(selection)) {
return false
return false;
}
let cellCount = 0
let cellCount = 0;
const table = findParentNodeClosestToPos(
selection.ranges[0].$from,
(node) => node.type.name === "table"
)
(node) => node.type.name === "table",
);
table?.node.descendants((node) => {
if (node.type.name === "table") {
return false
return false;
}
if (["tableCell", "tableHeader"].includes(node.type.name)) {
cellCount += 1
cellCount += 1;
}
})
});
const allCellsSelected = cellCount === selection.ranges.length
const allCellsSelected = cellCount === selection.ranges.length;
if (!allCellsSelected) {
return false
return false;
}
editor.commands.deleteTable()
editor.commands.deleteTable();
return true
}
return true;
};

View File

@ -1,21 +1,21 @@
import { NodeType, Schema } from "prosemirror-model"
import { NodeType, Schema } from "prosemirror-model";
export function getTableNodeTypes(schema: Schema): { [key: string]: NodeType } {
if (schema.cached.tableNodeTypes) {
return schema.cached.tableNodeTypes
return schema.cached.tableNodeTypes;
}
const roles: { [key: string]: NodeType } = {}
const roles: { [key: string]: NodeType } = {};
Object.keys(schema.nodes).forEach((type) => {
const nodeType = schema.nodes[type]
const nodeType = schema.nodes[type];
if (nodeType.spec.tableRole) {
roles[nodeType.spec.tableRole] = nodeType
roles[nodeType.spec.tableRole] = nodeType;
}
})
});
schema.cached.tableNodeTypes = roles
schema.cached.tableNodeTypes = roles;
return roles
return roles;
}

View File

@ -1,5 +1,5 @@
import { CellSelection } from "@tiptap/prosemirror-tables"
import { CellSelection } from "@tiptap/prosemirror-tables";
export function isCellSelection(value: unknown): value is CellSelection {
return value instanceof CellSelection
return value instanceof CellSelection;
}

View File

@ -29,11 +29,13 @@ interface CustomEditorProps {
forwardedRef?: any;
mentionHighlights?: string[];
mentionSuggestions?: IMentionSuggestion[];
cancelUploadImage?: () => any;
}
export const useEditor = ({
uploadFile,
deleteFile,
cancelUploadImage,
editorProps = {},
value,
extensions = [],
@ -42,7 +44,7 @@ export const useEditor = ({
forwardedRef,
setShouldShowAlert,
mentionHighlights,
mentionSuggestions
mentionSuggestions,
}: CustomEditorProps) => {
const editor = useCustomEditor(
{
@ -50,7 +52,17 @@ export const useEditor = ({
...CoreEditorProps(uploadFile, setIsSubmitting),
...editorProps,
},
extensions: [...CoreEditorExtensions({ mentionSuggestions: mentionSuggestions ?? [], mentionHighlights: mentionHighlights ?? []}, deleteFile), ...extensions],
extensions: [
...CoreEditorExtensions(
{
mentionSuggestions: mentionSuggestions ?? [],
mentionHighlights: mentionHighlights ?? [],
},
deleteFile,
cancelUploadImage,
),
...extensions,
],
content:
typeof value === "string" && value.trim() !== "" ? value : "<p></p>",
onUpdate: async ({ editor }) => {

View File

@ -7,7 +7,7 @@ import {
} from "react";
import { CoreReadOnlyEditorExtensions } from "../../ui/read-only/extensions";
import { CoreReadOnlyEditorProps } from "../../ui/read-only/props";
import { EditorProps } from '@tiptap/pm/view';
import { EditorProps } from "@tiptap/pm/view";
import { IMentionSuggestion } from "../../types/mention-suggestion";
interface CustomReadOnlyEditorProps {
@ -19,7 +19,14 @@ interface CustomReadOnlyEditorProps {
mentionSuggestions?: IMentionSuggestion[];
}
export const useReadOnlyEditor = ({ value, forwardedRef, extensions = [], editorProps = {}, mentionHighlights, mentionSuggestions}: CustomReadOnlyEditorProps) => {
export const useReadOnlyEditor = ({
value,
forwardedRef,
extensions = [],
editorProps = {},
mentionHighlights,
mentionSuggestions,
}: CustomReadOnlyEditorProps) => {
const editor = useCustomEditor({
editable: false,
content:
@ -28,7 +35,13 @@ export const useReadOnlyEditor = ({ value, forwardedRef, extensions = [], editor
...CoreReadOnlyEditorProps,
...editorProps,
},
extensions: [...CoreReadOnlyEditorExtensions({ mentionSuggestions: mentionSuggestions ?? [], mentionHighlights: mentionHighlights ?? []}), ...extensions],
extensions: [
...CoreReadOnlyEditorExtensions({
mentionSuggestions: mentionSuggestions ?? [],
mentionHighlights: mentionHighlights ?? [],
}),
...extensions,
],
});
const hasIntiliazedContent = useRef(false);

View File

@ -1,11 +1,11 @@
import { Mention, MentionOptions } from '@tiptap/extension-mention'
import { mergeAttributes } from '@tiptap/core'
import { ReactNodeViewRenderer } from '@tiptap/react'
import mentionNodeView from './mentionNodeView'
import { IMentionHighlight } from '../../types/mention-suggestion'
import { Mention, MentionOptions } from "@tiptap/extension-mention";
import { mergeAttributes } from "@tiptap/core";
import { ReactNodeViewRenderer } from "@tiptap/react";
import mentionNodeView from "./mentionNodeView";
import { IMentionHighlight } from "../../types/mention-suggestion";
export interface CustomMentionOptions extends MentionOptions {
mentionHighlights: IMentionHighlight[]
readonly?: boolean
mentionHighlights: IMentionHighlight[];
readonly?: boolean;
}
export const CustomMention = Mention.extend<CustomMentionOptions>({
@ -21,35 +21,37 @@ export const CustomMention = Mention.extend<CustomMentionOptions>({
default: null,
},
self: {
default: false
default: false,
},
redirect_uri: {
default: "/"
}
}
default: "/",
},
};
},
addNodeView() {
return ReactNodeViewRenderer(mentionNodeView)
return ReactNodeViewRenderer(mentionNodeView);
},
parseHTML() {
return [{
tag: 'mention-component',
return [
{
tag: "mention-component",
getAttrs: (node: string | HTMLElement) => {
if (typeof node === 'string') {
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')
}
id: node.getAttribute("data-mention-id") || "",
target: node.getAttribute("data-mention-target") || "",
label: node.innerText.slice(1) || "",
redirect_uri: node.getAttribute("redirect_uri"),
};
},
}]
},
];
},
renderHTML({ HTMLAttributes }) {
return ['mention-component', mergeAttributes(HTMLAttributes)]
return ["mention-component", mergeAttributes(HTMLAttributes)];
},
})
});

View File

@ -2,14 +2,21 @@
import suggestion from "./suggestion";
import { CustomMention } from "./custom";
import { IMentionHighlight, IMentionSuggestion } from "../../types/mention-suggestion";
import {
IMentionHighlight,
IMentionSuggestion,
} from "../../types/mention-suggestion";
export const Mentions = (mentionSuggestions: IMentionSuggestion[], mentionHighlights: IMentionHighlight[], readonly) => CustomMention.configure({
export const Mentions = (
mentionSuggestions: IMentionSuggestion[],
mentionHighlights: IMentionHighlight[],
readonly,
) =>
CustomMention.configure({
HTMLAttributes: {
'class' : "mention",
class: "mention",
},
readonly: readonly,
mentionHighlights: mentionHighlights,
suggestion: suggestion(mentionSuggestions),
})
});

View File

@ -1,12 +1,17 @@
import { ReactRenderer } from '@tiptap/react'
import { ReactRenderer } from "@tiptap/react";
import { Editor } from "@tiptap/core";
import tippy from 'tippy.js'
import tippy from "tippy.js";
import MentionList from './MentionList'
import { IMentionSuggestion } from '../../types/mention-suggestion';
import MentionList from "./MentionList";
import { IMentionSuggestion } from "../../types/mention-suggestion";
const Suggestion = (suggestions: IMentionSuggestion[]) => ({
items: ({ query }: { query: string }) => suggestions.filter(suggestion => suggestion.title.toLowerCase().startsWith(query.toLowerCase())).slice(0, 5),
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;
@ -30,7 +35,7 @@ const Suggestion = (suggestions: IMentionSuggestion[]) => ({
},
onUpdate: (props: { editor: Editor; clientRect: DOMRect }) => {
reactRenderer?.updateProps(props)
reactRenderer?.updateProps(props);
popup &&
popup[0].setProps({
@ -49,11 +54,10 @@ const Suggestion = (suggestions: IMentionSuggestion[]) => ({
},
onExit: () => {
popup?.[0].destroy();
reactRenderer?.destroy()
reactRenderer?.destroy();
},
}
};
},
})
});
export default Suggestion;

View File

@ -1,16 +0,0 @@
const InsertBottomTableIcon = (props: any) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 -960 960 960"
{...props}
>
<path
d="M212.309-152.31q-30.308 0-51.308-21t-21-51.307V-360q0-30.307 21-51.307 21-21 51.308-21h535.382q30.308 0 51.308 21t21 51.307v135.383q0 30.307-21 51.307-21 21-51.308 21H212.309Zm0-375.383q-30.308 0-51.308-21t-21-51.307v-135.383q0-30.307 21-51.307 21-21 51.308-21h535.382q30.308 0 51.308 21t21 51.307V-600q0 30.307-21 51.307-21 21-51.308 21H212.309Zm535.382-219.998H212.309q-4.616 0-8.463 3.846-3.846 3.846-3.846 8.462V-600q0 4.616 3.846 8.462 3.847 3.847 8.463 3.847h535.382q4.616 0 8.463-3.847Q760-595.384 760-600v-135.383q0-4.616-3.846-8.462-3.847-3.846-8.463-3.846ZM200-587.691v-160 160Z"
fill="rgb(var(--color-text-300))"
/>
</svg>
);
export default InsertBottomTableIcon;

View File

@ -1,15 +0,0 @@
const InsertLeftTableIcon = (props: any) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 -960 960 960"
{...props}
>
<path
d="M224.617-140.001q-30.307 0-51.307-21-21-21-21-51.308v-535.382q0-30.308 21-51.308t51.307-21H360q30.307 0 51.307 21 21 21 21 51.308v535.382q0 30.308-21 51.308t-51.307 21H224.617Zm375.383 0q-30.307 0-51.307-21-21-21-21-51.308v-535.382q0-30.308 21-51.308t51.307-21h135.383q30.307 0 51.307 21 21 21 21 51.308v535.382q0 30.308-21 51.308t-51.307 21H600Zm147.691-607.69q0-4.616-3.846-8.463-3.846-3.846-8.462-3.846H600q-4.616 0-8.462 3.846-3.847 3.847-3.847 8.463v535.382q0 4.616 3.847 8.463Q595.384-200 600-200h135.383q4.616 0 8.462-3.846 3.846-3.847 3.846-8.463v-535.382ZM587.691-200h160-160Z"
fill="rgb(var(--color-text-300))"
/>
</svg>
);
export default InsertLeftTableIcon;

View File

@ -1,16 +0,0 @@
const InsertRightTableIcon = (props: any) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 -960 960 960"
{...props}
>
<path
d="M600-140.001q-30.307 0-51.307-21-21-21-21-51.308v-535.382q0-30.308 21-51.308t51.307-21h135.383q30.307 0 51.307 21 21 21 21 51.308v535.382q0 30.308-21 51.308t-51.307 21H600Zm-375.383 0q-30.307 0-51.307-21-21-21-21-51.308v-535.382q0-30.308 21-51.308t51.307-21H360q30.307 0 51.307 21 21 21 21 51.308v535.382q0 30.308-21 51.308t-51.307 21H224.617Zm-12.308-607.69v535.382q0 4.616 3.846 8.463 3.846 3.846 8.462 3.846H360q4.616 0 8.462-3.846 3.847-3.847 3.847-8.463v-535.382q0-4.616-3.847-8.463Q364.616-760 360-760H224.617q-4.616 0-8.462 3.846-3.846 3.847-3.846 8.463Zm160 547.691h-160 160Z"
fill="rgb(var(--color-text-300))"
/>
</svg>
);
export default InsertRightTableIcon;

View File

@ -1,15 +0,0 @@
const InsertTopTableIcon = (props: any) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width={24}
height={24}
viewBox="0 -960 960 960"
{...props}
>
<path
d="M212.309-527.693q-30.308 0-51.308-21t-21-51.307v-135.383q0-30.307 21-51.307 21-21 51.308-21h535.382q30.308 0 51.308 21t21 51.307V-600q0 30.307-21 51.307-21 21-51.308 21H212.309Zm0 375.383q-30.308 0-51.308-21t-21-51.307V-360q0-30.307 21-51.307 21-21 51.308-21h535.382q30.308 0 51.308 21t21 51.307v135.383q0 30.307-21 51.307-21 21-51.308 21H212.309Zm0-59.999h535.382q4.616 0 8.463-3.846 3.846-3.846 3.846-8.462V-360q0-4.616-3.846-8.462-3.847-3.847-8.463-3.847H212.309q-4.616 0-8.463 3.847Q200-364.616 200-360v135.383q0 4.616 3.846 8.462 3.847 3.846 8.463 3.846Zm-12.309-160v160-160Z"
fill="rgb(var(--color-text-300))"
/>
</svg>
);
export default InsertTopTableIcon;

View File

@ -1,77 +0,0 @@
import * as React from 'react';
// next-themes
import { useTheme } from "next-themes";
// tooltip2
import { Tooltip2 } from "@blueprintjs/popover2";
type Props = {
tooltipHeading?: string;
tooltipContent: string | React.ReactNode;
position?:
| "top"
| "right"
| "bottom"
| "left"
| "auto"
| "auto-end"
| "auto-start"
| "bottom-left"
| "bottom-right"
| "left-bottom"
| "left-top"
| "right-bottom"
| "right-top"
| "top-left"
| "top-right";
children: JSX.Element;
disabled?: boolean;
className?: string;
openDelay?: number;
closeDelay?: number;
};
export const Tooltip: React.FC<Props> = ({
tooltipHeading,
tooltipContent,
position = "top",
children,
disabled = false,
className = "",
openDelay = 200,
closeDelay,
}) => {
const { theme } = useTheme();
return (
<Tooltip2
disabled={disabled}
hoverOpenDelay={openDelay}
hoverCloseDelay={closeDelay}
content={
<div
className={`relative z-50 max-w-xs gap-1 rounded-md p-2 text-xs shadow-md ${
theme === "custom"
? "bg-custom-background-100 text-custom-text-200"
: "bg-black text-gray-400"
} break-words overflow-hidden ${className}`}
>
{tooltipHeading && (
<h5
className={`font-medium ${
theme === "custom" ? "text-custom-text-100" : "text-white"
}`}
>
{tooltipHeading}
</h5>
)}
{tooltipContent}
</div>
}
position={position}
renderTarget={({ isOpen: isTooltipOpen, ref: eleReference, ...tooltipProps }) =>
React.cloneElement(children, { ref: eleReference, ...tooltipProps, ...children.props })
}
/>
);
};

View File

@ -15,7 +15,11 @@ interface ImageNode extends ProseMirrorNode {
const TrackImageDeletionPlugin = (deleteImage: DeleteImage): Plugin =>
new Plugin({
key: deleteKey,
appendTransaction: (transactions: readonly Transaction[], oldState: EditorState, newState: EditorState) => {
appendTransaction: (
transactions: readonly Transaction[],
oldState: EditorState,
newState: EditorState,
) => {
const newImageSources = new Set<string>();
newState.doc.descendants((node) => {
if (node.type.name === IMAGE_NODE_TYPE) {
@ -55,7 +59,10 @@ const TrackImageDeletionPlugin = (deleteImage: DeleteImage): Plugin =>
export default TrackImageDeletionPlugin;
async function onNodeDeleted(src: string, deleteImage: DeleteImage): Promise<void> {
async function onNodeDeleted(
src: string,
deleteImage: DeleteImage,
): Promise<void> {
try {
const assetUrlWithWorkspaceId = new URL(src).pathname.substring(1);
const resStatus = await deleteImage(assetUrlWithWorkspaceId);

View File

@ -4,7 +4,7 @@ import { Decoration, DecorationSet, EditorView } from "@tiptap/pm/view";
const uploadKey = new PluginKey("upload-image");
const UploadImagesPlugin = () =>
const UploadImagesPlugin = (cancelUploadImage?: () => any) =>
new Plugin({
key: uploadKey,
state: {
@ -21,15 +21,46 @@ const UploadImagesPlugin = () =>
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-10 rounded-lg border border-custom-border-300",
);
image.src = src;
placeholder.appendChild(image);
// Create cancel button
const cancelButton = document.createElement("button");
cancelButton.style.position = "absolute";
cancelButton.style.right = "3px";
cancelButton.style.top = "3px";
cancelButton.setAttribute("class", "opacity-90 rounded-lg");
cancelButton.onclick = () => {
cancelUploadImage?.();
};
// Create an SVG element from the SVG string
const svgString = `<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-x-circle"><circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/></svg>`;
const parser = new DOMParser();
const svgElement = parser.parseFromString(
svgString,
"image/svg+xml",
).documentElement;
cancelButton.appendChild(svgElement);
placeholder.appendChild(cancelButton);
const deco = Decoration.widget(pos + 1, placeholder, {
id,
});
set = set.add(tr.doc, [deco]);
} else if (action && action.remove) {
set = set.remove(set.find(undefined, undefined, (spec) => spec.id == action.remove.id));
set = set.remove(
set.find(
undefined,
undefined,
(spec) => spec.id == action.remove.id,
),
);
}
return set;
},
@ -48,19 +79,39 @@ function findPlaceholder(state: EditorState, id: {}) {
const found = decos.find(
undefined,
undefined,
(spec: { id: number | undefined }) => spec.id == id
(spec: { id: number | undefined }) => spec.id == id,
);
return found.length ? found[0].from : null;
}
const removePlaceholder = (view: EditorView, id: {}) => {
const removePlaceholderTr = view.state.tr.setMeta(uploadKey, {
remove: { id },
});
view.dispatch(removePlaceholderTr);
};
export async function startImageUpload(
file: File,
view: EditorView,
pos: number,
uploadFile: UploadImage,
setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
setIsSubmitting?: (
isSubmitting: "submitting" | "submitted" | "saved",
) => void,
) {
if (!file) {
alert("No file selected. Please select a file to upload.");
return;
}
if (!file.type.includes("image/")) {
alert("Invalid file type. Please select an image file.");
return;
}
if (file.size > 5 * 1024 * 1024) {
alert("File size too large. Please select a file smaller than 5MB.");
return;
}
@ -82,7 +133,16 @@ export async function startImageUpload(
view.dispatch(tr);
};
// Handle FileReader errors
reader.onerror = (error) => {
console.error("FileReader error: ", error);
removePlaceholder(view, id);
return;
};
setIsSubmitting?.("submitting");
try {
const src = await UploadImageHandler(file, uploadFile);
const { schema } = view.state;
pos = findPlaceholder(view.state, id);
@ -95,15 +155,20 @@ export async function startImageUpload(
.replaceWith(pos, pos, node)
.setMeta(uploadKey, { remove: { id } });
view.dispatch(transaction);
} catch (error) {
console.error("Upload error: ", error);
removePlaceholder(view, id);
}
}
const UploadImageHandler = (file: File,
uploadFile: UploadImage
const UploadImageHandler = (
file: File,
uploadFile: UploadImage,
): Promise<string> => {
try {
return new Promise(async (resolve, reject) => {
try {
const imageUrl = await uploadFile(file)
const imageUrl = await uploadFile(file);
const image = new Image();
image.src = imageUrl;
@ -118,9 +183,6 @@ const UploadImageHandler = (file: File,
}
});
} catch (error) {
if (error instanceof Error) {
console.log(error.message);
}
return Promise.reject(error);
}
};

View File

@ -5,7 +5,9 @@ import { UploadImage } from "../types/upload-image";
export function CoreEditorProps(
uploadFile: UploadImage,
setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
setIsSubmitting?: (
isSubmitting: "submitting" | "submitted" | "saved",
) => void,
): EditorProps {
return {
attributes: {
@ -32,7 +34,11 @@ export function CoreEditorProps(
}
}
}
if (event.clipboardData && event.clipboardData.files && event.clipboardData.files[0]) {
if (
event.clipboardData &&
event.clipboardData.files &&
event.clipboardData.files[0]
) {
event.preventDefault();
const file = event.clipboardData.files[0];
const pos = view.state.selection.from;
@ -51,7 +57,12 @@ export function CoreEditorProps(
}
}
}
if (!moved && event.dataTransfer && event.dataTransfer.files && event.dataTransfer.files[0]) {
if (
!moved &&
event.dataTransfer &&
event.dataTransfer.files &&
event.dataTransfer.files[0]
) {
event.preventDefault();
const file = event.dataTransfer.files[0];
const coordinates = view.posAtCoords({
@ -59,7 +70,13 @@ export function CoreEditorProps(
top: event.clientY,
});
if (coordinates) {
startImageUpload(file, view, coordinates.pos - 1, uploadFile, setIsSubmitting);
startImageUpload(
file,
view,
coordinates.pos - 1,
uploadFile,
setIsSubmitting,
);
}
return true;
}

View File

@ -18,9 +18,10 @@ import { isValidHttpUrl } from "../../lib/utils";
import { Mentions } from "../mentions";
import { IMentionSuggestion } from "../../types/mention-suggestion";
export const CoreReadOnlyEditorExtensions = (
mentionConfig: { mentionSuggestions: IMentionSuggestion[], mentionHighlights: string[] },
) => [
export const CoreReadOnlyEditorExtensions = (mentionConfig: {
mentionSuggestions: IMentionSuggestion[];
mentionHighlights: string[];
}) => [
StarterKit.configure({
bulletList: {
HTMLAttributes: {
@ -93,5 +94,9 @@ export const CoreReadOnlyEditorExtensions = (
TableHeader,
TableCell,
TableRow,
Mentions(mentionConfig.mentionSuggestions, mentionConfig.mentionHighlights, true),
];
Mentions(
mentionConfig.mentionSuggestions,
mentionConfig.mentionHighlights,
true,
),
];

View File

@ -1,7 +1,6 @@
import { EditorProps } from "@tiptap/pm/view";
export const CoreReadOnlyEditorProps: EditorProps =
{
export const CoreReadOnlyEditorProps: EditorProps = {
attributes: {
class: `prose prose-brand max-w-full prose-headings:font-display font-default focus:outline-none`,
},

View File

@ -10,13 +10,13 @@ The `@plane/lite-text-editor` package extends from the `editor-core` package, in
`LiteTextEditor` & `LiteTextEditorWithRef`
- **Read Only Editor Instances**: We have added a really light weight *Read Only* Editor instance for the Lite editor types (with and without Ref)
- **Read Only Editor Instances**: We have added a really light weight _Read Only_ Editor instance for the Lite editor types (with and without Ref)
`LiteReadOnlyEditor` &`LiteReadOnlyEditorWithRef`
## LiteTextEditor
| Prop | Type | Description |
| --- | --- | --- |
| ------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uploadFile` | `(file: File) => Promise<string>` | A function that handles file upload. It takes a file as input and handles the process of uploading that file. |
| `deleteFile` | `(assetUrlWithWorkspaceId: string) => Promise<any>` | A function that handles deleting an image. It takes the asset url from your bucket and handles the process of deleting that image. |
| `value` | `html string` | The initial content of the editor. |
@ -45,21 +45,21 @@ The `@plane/lite-text-editor` package extends from the `editor-core` package, in
onChange={(comment_json: Object, comment_html: string) => {
onChange(comment_html);
}}
/>
/>
```
2. Example of how to use the `LiteTextEditorWithRef` component
```tsx
const editorRef = useRef<any>(null);
const editorRef = useRef<any>(null);
// can use it to set the editor's value
editorRef.current?.setEditorValue(`${watch("description_html")}`);
// can use it to set the editor's value
editorRef.current?.setEditorValue(`${watch("description_html")}`);
// can use it to clear the editor
editorRef?.current?.clearEditor();
// can use it to clear the editor
editorRef?.current?.clearEditor();
return (
return (
<LiteTextEditorWithRef
onEnterKeyPress={handleSubmit(handleCommentUpdate)}
uploadFile={fileService.getUploadFileFunction(workspaceSlug)}
@ -72,13 +72,13 @@ The `@plane/lite-text-editor` package extends from the `editor-core` package, in
onChange(comment_html);
}}
/>
)
);
```
## LiteReadOnlyEditor
| Prop | Type | Description |
| --- | --- | --- |
| ------------------------------- | ------------- | --------------------------------------------------------------------- |
| `value` | `html string` | The initial content of the editor. |
| `noBorder` | `boolean` | If set to true, the editor will not have a border. |
| `borderOnFocus` | `boolean` | If set to true, the editor will show a border when it is focused. |
@ -90,8 +90,8 @@ The `@plane/lite-text-editor` package extends from the `editor-core` package, in
Here is an example of how to use the `RichReadOnlyEditor` component
```tsx
<LiteReadOnlyEditor
<LiteReadOnlyEditor
value={comment.comment_html}
customClassName="text-xs border border-custom-border-200 bg-custom-background-100"
/>
/>
```

View File

@ -29,6 +29,7 @@
},
"dependencies": {
"@plane/editor-core": "*",
"@plane/ui": "*",
"@tiptap/extension-list-item": "^2.1.11",
"class-variance-authority": "^0.7.0",
"clsx": "^1.2.1",

View File

@ -1,3 +1,3 @@
export { LiteTextEditor, LiteTextEditorWithRef } from "./ui";
export { LiteReadOnlyEditor, LiteReadOnlyEditorWithRef } from "./ui/read-only";
export type { IMentionSuggestion, IMentionHighlight } from "./ui"
export type { IMentionSuggestion, IMentionHighlight } from "./ui";

View File

@ -31,7 +31,7 @@ interface ILiteTextEditor {
editorContentCustomClassNames?: string;
onChange?: (json: any, html: string) => void;
setIsSubmitting?: (
isSubmitting: "submitting" | "submitted" | "saved"
isSubmitting: "submitting" | "submitted" | "saved",
) => void;
setShouldShowAlert?: (showAlert: boolean) => void;
forwardedRef?: any;
@ -47,6 +47,7 @@ interface ILiteTextEditor {
}[];
};
onEnterKeyPress?: (e?: any) => void;
cancelUploadImage?: () => any;
mentionHighlights?: string[];
mentionSuggestions?: IMentionSuggestion[];
submitButton?: React.ReactNode;
@ -64,6 +65,7 @@ interface EditorHandle {
const LiteTextEditor = (props: LiteTextEditorProps) => {
const {
onChange,
cancelUploadImage,
debouncedUpdatesEnabled,
setIsSubmitting,
setShouldShowAlert,
@ -84,6 +86,7 @@ const LiteTextEditor = (props: LiteTextEditorProps) => {
const editor = useEditor({
onChange,
cancelUploadImage,
debouncedUpdatesEnabled,
setIsSubmitting,
setShouldShowAlert,
@ -126,7 +129,7 @@ const LiteTextEditor = (props: LiteTextEditorProps) => {
};
const LiteTextEditorWithRef = React.forwardRef<EditorHandle, ILiteTextEditor>(
(props, ref) => <LiteTextEditor {...props} forwardedRef={ref} />
(props, ref) => <LiteTextEditor {...props} forwardedRef={ref} />,
);
LiteTextEditorWithRef.displayName = "LiteTextEditorWithRef";

View File

@ -6,8 +6,9 @@ type Props = {
};
export const Icon: React.FC<Props> = ({ iconName, className = "" }) => (
<span className={`material-symbols-rounded text-sm leading-5 font-light ${className}`}>
<span
className={`material-symbols-rounded text-sm leading-5 font-light ${className}`}
>
{iconName}
</span>
);

View File

@ -14,8 +14,8 @@ import {
TableItem,
UnderLineItem,
} from "@plane/editor-core";
import { Tooltip } from "../../tooltip";
import { UploadImage } from "../..";
import { Tooltip } from "@plane/ui";
import { UploadImage } from "../../";
export interface BubbleMenuItem {
name: string;

View File

@ -10,13 +10,13 @@ The `@plane/rich-text-editor` package extends from the `editor-core` package, in
`RichTextEditor` & `RichTextEditorWithRef`
- **Read Only Editor Instances**: We have added a really light weight *Read Only* Editor instance for the Rich editor types (with and without Ref)
- **Read Only Editor Instances**: We have added a really light weight _Read Only_ Editor instance for the Rich editor types (with and without Ref)
`RichReadOnlyEditor` &`RichReadOnlyEditorWithRef`
## RichTextEditor
| Prop | Type | Description |
| --- | --- | --- |
| ------------------------------- | ---------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `uploadFile` | `(file: File) => Promise<string>` | A function that handles file upload. It takes a file as input and handles the process of uploading that file. |
| `deleteFile` | `(assetUrlWithWorkspaceId: string) => Promise<any>` | A function that handles deleting an image. It takes the asset url from your bucket and handles the process of deleting that image. |
| `value` | `html string` | The initial content of the editor. |
@ -57,15 +57,16 @@ The `@plane/rich-text-editor` package extends from the `editor-core` package, in
2. Example of how to use the `RichTextEditorWithRef` component
```tsx
const editorRef = useRef<any>(null);
const editorRef = useRef<any>(null);
// can use it to set the editor's value
editorRef.current?.setEditorValue(`${watch("description_html")}`);
// can use it to set the editor's value
editorRef.current?.setEditorValue(`${watch("description_html")}`);
// can use it to clear the editor
editorRef?.current?.clearEditor();
// can use it to clear the editor
editorRef?.current?.clearEditor();
return (<RichTextEditorWithRef
return (
<RichTextEditorWithRef
uploadFile={fileService.getUploadFileFunction(workspaceSlug as string)}
deleteFile={fileService.deleteImage}
ref={editorRef}
@ -75,13 +76,15 @@ The `@plane/rich-text-editor` package extends from the `editor-core` package, in
onChange={(description: Object, description_html: string) => {
onChange(description_html);
// custom stuff you want to do
} } />)
}}
/>
);
```
## RichReadOnlyEditor
| Prop | Type | Description |
| --- | --- | --- |
| ------------------------------- | ------------- | --------------------------------------------------------------------- |
| `value` | `html string` | The initial content of the editor. |
| `noBorder` | `boolean` | If set to true, the editor will not have a border. |
| `borderOnFocus` | `boolean` | If set to true, the editor will show a border when it is focused. |
@ -93,7 +96,8 @@ The `@plane/rich-text-editor` package extends from the `editor-core` package, in
Here is an example of how to use the `RichReadOnlyEditor` component
```tsx
<RichReadOnlyEditor
<RichReadOnlyEditor
value={issueDetails.description_html}
customClassName="p-3 min-h-[50px] shadow-sm" />
customClassName="p-3 min-h-[50px] shadow-sm"
/>
```

View File

@ -2,4 +2,4 @@ import "./styles/github-dark.css";
export { RichTextEditor, RichTextEditorWithRef } from "./ui";
export { RichReadOnlyEditor, RichReadOnlyEditorWithRef } from "./ui/read-only";
export type { IMentionSuggestion, IMentionHighlight } from "./ui"
export type { IMentionSuggestion, IMentionHighlight } from "./ui";

View File

@ -1,7 +1,7 @@
import HorizontalRule from "@tiptap/extension-horizontal-rule";
import Placeholder from "@tiptap/extension-placeholder";
import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
import { common, createLowlight } from 'lowlight'
import { common, createLowlight } from "lowlight";
import { InputRule } from "@tiptap/core";
import ts from "highlight.js/lib/languages/typescript";
@ -9,12 +9,14 @@ import ts from "highlight.js/lib/languages/typescript";
import SlashCommand from "./slash-command";
import { UploadImage } from "../";
const lowlight = createLowlight(common)
const lowlight = createLowlight(common);
lowlight.register("ts", ts);
export const RichTextEditorExtensions = (
uploadFile: UploadImage,
setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void
setIsSubmitting?: (
isSubmitting: "submitting" | "submitted" | "saved",
) => void,
) => [
HorizontalRule.extend({
addInputRules() {
@ -56,4 +58,4 @@ export const RichTextEditorExtensions = (
},
includeChildren: true,
}),
];
];

View File

@ -1,8 +1,13 @@
"use client"
import * as React from 'react';
import { EditorContainer, EditorContentWrapper, getEditorClassNames, useEditor } from '@plane/editor-core';
import { EditorBubbleMenu } from './menus/bubble-menu';
import { RichTextEditorExtensions } from './extensions';
"use client";
import * as React from "react";
import {
EditorContainer,
EditorContentWrapper,
getEditorClassNames,
useEditor,
} from "@plane/editor-core";
import { EditorBubbleMenu } from "./menus/bubble-menu";
import { RichTextEditorExtensions } from "./extensions";
export type UploadImage = (file: File) => Promise<string>;
export type DeleteImage = (assetUrlWithWorkspaceId: string) => Promise<any>;
@ -14,9 +19,9 @@ export type IMentionSuggestion = {
title: string;
subtitle: string;
redirect_uri: string;
}
};
export type IMentionHighlight = string
export type IMentionHighlight = string;
interface IRichTextEditor {
value: string;
@ -24,10 +29,13 @@ interface IRichTextEditor {
deleteFile: DeleteImage;
noBorder?: boolean;
borderOnFocus?: boolean;
cancelUploadImage?: () => any;
customClassName?: string;
editorContentCustomClassNames?: string;
onChange?: (json: any, html: string) => void;
setIsSubmitting?: (isSubmitting: "submitting" | "submitted" | "saved") => void;
setIsSubmitting?: (
isSubmitting: "submitting" | "submitted" | "saved",
) => void;
setShouldShowAlert?: (showAlert: boolean) => void;
forwardedRef?: any;
debouncedUpdatesEnabled?: boolean;
@ -54,11 +62,12 @@ const RichTextEditor = ({
uploadFile,
deleteFile,
noBorder,
cancelUploadImage,
borderOnFocus,
customClassName,
forwardedRef,
mentionHighlights,
mentionSuggestions
mentionSuggestions,
}: RichTextEditorProps) => {
const editor = useEditor({
onChange,
@ -67,14 +76,19 @@ const RichTextEditor = ({
setShouldShowAlert,
value,
uploadFile,
cancelUploadImage,
deleteFile,
forwardedRef,
extensions: RichTextEditorExtensions(uploadFile, setIsSubmitting),
mentionHighlights,
mentionSuggestions
mentionSuggestions,
});
const editorClassNames = getEditorClassNames({ noBorder, borderOnFocus, customClassName });
const editorClassNames = getEditorClassNames({
noBorder,
borderOnFocus,
customClassName,
});
if (!editor) return null;
@ -82,16 +96,19 @@ const RichTextEditor = ({
<EditorContainer editor={editor} editorClassNames={editorClassNames}>
{editor && <EditorBubbleMenu editor={editor} />}
<div className="flex flex-col">
<EditorContentWrapper editor={editor} editorContentCustomClassNames={editorContentCustomClassNames} />
<EditorContentWrapper
editor={editor}
editorContentCustomClassNames={editorContentCustomClassNames}
/>
</div>
</EditorContainer >
</EditorContainer>
);
};
const RichTextEditorWithRef = React.forwardRef<EditorHandle, IRichTextEditor>((props, ref) => (
<RichTextEditor {...props} forwardedRef={ref} />
));
const RichTextEditorWithRef = React.forwardRef<EditorHandle, IRichTextEditor>(
(props, ref) => <RichTextEditor {...props} forwardedRef={ref} />,
);
RichTextEditorWithRef.displayName = "RichTextEditorWithRef";
export { RichTextEditor, RichTextEditorWithRef};
export { RichTextEditor, RichTextEditorWithRef };

View File

@ -1,7 +1,19 @@
import { Editor } from "@tiptap/core";
import { Check, Trash } from "lucide-react";
import { Dispatch, FC, SetStateAction, useCallback, useEffect, useRef } from "react";
import { cn, isValidHttpUrl, setLinkEditor, unsetLinkEditor, } from "@plane/editor-core";
import {
Dispatch,
FC,
SetStateAction,
useCallback,
useEffect,
useRef,
} from "react";
import {
cn,
isValidHttpUrl,
setLinkEditor,
unsetLinkEditor,
} from "@plane/editor-core";
interface LinkSelectorProps {
editor: Editor;
@ -9,7 +21,11 @@ interface LinkSelectorProps {
setIsOpen: Dispatch<SetStateAction<boolean>>;
}
export const LinkSelector: FC<LinkSelectorProps> = ({ editor, isOpen, setIsOpen }) => {
export const LinkSelector: FC<LinkSelectorProps> = ({
editor,
isOpen,
setIsOpen,
}) => {
const inputRef = useRef<HTMLInputElement>(null);
const onLinkSubmit = useCallback(() => {
@ -31,7 +47,7 @@ export const LinkSelector: FC<LinkSelectorProps> = ({ editor, isOpen, setIsOpen
type="button"
className={cn(
"flex h-full items-center space-x-2 px-3 py-1.5 text-sm font-medium text-custom-text-300 hover:bg-custom-background-100 active:bg-custom-background-100",
{ "bg-custom-background-100": isOpen }
{ "bg-custom-background-100": isOpen },
)}
onClick={() => {
setIsOpen(!isOpen);

View File

@ -1,10 +1,16 @@
import { BulletListItem, cn, CodeItem, HeadingOneItem, HeadingThreeItem, HeadingTwoItem, NumberedListItem, QuoteItem, TodoListItem } from "@plane/editor-core";
import { Editor } from "@tiptap/react";
import {
Check,
ChevronDown,
TextIcon,
} from "lucide-react";
BulletListItem,
cn,
CodeItem,
HeadingOneItem,
HeadingThreeItem,
HeadingTwoItem,
NumberedListItem,
QuoteItem,
TodoListItem,
} from "@plane/editor-core";
import { Editor } from "@tiptap/react";
import { Check, ChevronDown, TextIcon } from "lucide-react";
import { Dispatch, FC, SetStateAction } from "react";
import { BubbleMenuItem } from ".";
@ -15,12 +21,17 @@ interface NodeSelectorProps {
setIsOpen: Dispatch<SetStateAction<boolean>>;
}
export const NodeSelector: FC<NodeSelectorProps> = ({ editor, isOpen, setIsOpen }) => {
export const NodeSelector: FC<NodeSelectorProps> = ({
editor,
isOpen,
setIsOpen,
}) => {
const items: BubbleMenuItem[] = [
{
name: "Text",
icon: TextIcon,
command: () => editor.chain().focus().toggleNode("paragraph", "paragraph").run(),
command: () =>
editor.chain().focus().toggleNode("paragraph", "paragraph").run(),
isActive: () =>
editor.isActive("paragraph") &&
!editor.isActive("bulletList") &&
@ -63,7 +74,10 @@ export const NodeSelector: FC<NodeSelectorProps> = ({ editor, isOpen, setIsOpen
}}
className={cn(
"flex items-center justify-between rounded-sm px-2 py-1 text-sm text-custom-text-200 hover:bg-custom-primary-100/5 hover:text-custom-text-100",
{ "bg-custom-primary-100/5 text-custom-text-100": activeItem.name === item.name }
{
"bg-custom-primary-100/5 text-custom-text-100":
activeItem.name === item.name,
},
)}
>
<div className="flex items-center space-x-2">

View File

@ -1,6 +1,11 @@
"use client"
import { EditorContainer, EditorContentWrapper, getEditorClassNames, useReadOnlyEditor } from '@plane/editor-core';
import * as React from 'react';
"use client";
import {
EditorContainer,
EditorContentWrapper,
getEditorClassNames,
useReadOnlyEditor,
} from "@plane/editor-core";
import * as React from "react";
interface IRichTextReadOnlyEditor {
value: string;
@ -35,23 +40,31 @@ const RichReadOnlyEditor = ({
mentionHighlights,
});
const editorClassNames = getEditorClassNames({ noBorder, borderOnFocus, customClassName });
const editorClassNames = getEditorClassNames({
noBorder,
borderOnFocus,
customClassName,
});
if (!editor) return null;
return (
<EditorContainer editor={editor} editorClassNames={editorClassNames}>
<div className="flex flex-col">
<EditorContentWrapper editor={editor} editorContentCustomClassNames={editorContentCustomClassNames} />
<EditorContentWrapper
editor={editor}
editorContentCustomClassNames={editorContentCustomClassNames}
/>
</div>
</EditorContainer >
</EditorContainer>
);
};
const RichReadOnlyEditorWithRef = React.forwardRef<EditorHandle, IRichTextReadOnlyEditor>((props, ref) => (
<RichReadOnlyEditor {...props} forwardedRef={ref} />
));
const RichReadOnlyEditorWithRef = React.forwardRef<
EditorHandle,
IRichTextReadOnlyEditor
>((props, ref) => <RichReadOnlyEditor {...props} forwardedRef={ref} />);
RichReadOnlyEditorWithRef.displayName = "RichReadOnlyEditorWithRef";
export { RichReadOnlyEditor , RichReadOnlyEditorWithRef };
export { RichReadOnlyEditor, RichReadOnlyEditorWithRef };

View File

@ -123,7 +123,7 @@ export const Avatar: React.FC<Props> = (props) => {
size = "md",
shape = "circle",
src,
className = ""
className = "",
} = props;
// get size details based on the size prop
@ -157,7 +157,9 @@ export const Avatar: React.FC<Props> = (props) => {
<div
className={`${
sizeInfo.fontSize
} grid place-items-center h-full w-full ${getBorderRadius(shape)} ${className}`}
} grid place-items-center h-full w-full ${getBorderRadius(
shape,
)} ${className}`}
style={{
backgroundColor:
fallbackBackgroundColor ?? "rgba(var(--color-primary-500))",

View File

@ -58,7 +58,7 @@ const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
)}
</button>
);
}
},
);
Button.displayName = "plane-ui-button";

View File

@ -102,7 +102,7 @@ export const buttonStyling: IButtonStyling = {
export const getButtonStyling = (
variant: TButtonVariant,
size: TButtonSizes,
disabled: boolean = false
disabled: boolean = false,
): string => {
let _variant: string = ``;
const currentVariant = buttonStyling[variant];

View File

@ -35,7 +35,7 @@ export const CustomSearchSelect = (props: ICustomSearchSelectProps) => {
const [referenceElement, setReferenceElement] =
useState<HTMLButtonElement | null>(null);
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(
null
null,
);
const { styles, attributes } = usePopper(referenceElement, popperElement, {
@ -46,7 +46,7 @@ export const CustomSearchSelect = (props: ICustomSearchSelectProps) => {
query === ""
? options
: options?.filter((option) =>
option.query.toLowerCase().includes(query.toLowerCase())
option.query.toLowerCase().includes(query.toLowerCase()),
);
const comboboxProps: any = {
@ -87,8 +87,8 @@ export const CustomSearchSelect = (props: ICustomSearchSelectProps) => {
<button
ref={setReferenceElement}
type="button"
className={`flex items-center justify-between gap-1 w-full rounded-md border border-custom-border-300 shadow-sm duration-300 focus:outline-none ${
input ? "px-3 py-2 text-sm" : "px-2.5 py-1 text-xs"
className={`flex items-center justify-between gap-1 w-full rounded border-[0.5px] border-custom-border-300 ${
input ? "px-3 py-2 text-sm" : "px-2 py-1 text-xs"
} ${
disabled
? "cursor-not-allowed text-custom-text-200"

View File

@ -30,7 +30,7 @@ const CustomSelect = (props: ICustomSelectProps) => {
const [referenceElement, setReferenceElement] =
useState<HTMLButtonElement | null>(null);
const [popperElement, setPopperElement] = useState<HTMLDivElement | null>(
null
null,
);
const { styles, attributes } = usePopper(referenceElement, popperElement, {
@ -65,8 +65,8 @@ const CustomSelect = (props: ICustomSelectProps) => {
<button
ref={setReferenceElement}
type="button"
className={`flex items-center justify-between gap-1 w-full rounded-md border border-custom-border-300 shadow-sm duration-300 focus:outline-none ${
input ? "px-3 py-2 text-sm" : "px-2.5 py-1 text-xs"
className={`flex items-center justify-between gap-1 w-full rounded border-[0.5px] border-custom-border-300 ${
input ? "px-3 py-2 text-sm" : "px-2 py-1 text-xs"
} ${
disabled
? "cursor-not-allowed text-custom-text-200"

View File

@ -1,3 +1,3 @@
export * from "./input";
export * from "./textarea";
export * from "./input-color-picker"
export * from "./input-color-picker";

View File

@ -10,7 +10,7 @@ export interface TextAreaProps
// Updates the height of a <textarea> when the value changes.
const useAutoSizeTextArea = (
textAreaRef: HTMLTextAreaElement | null,
value: any
value: any,
) => {
React.useEffect(() => {
if (textAreaRef) {
@ -63,7 +63,7 @@ const TextArea = React.forwardRef<HTMLTextAreaElement, TextAreaProps>(
{...rest}
/>
);
}
},
);
export { TextArea };

View File

@ -9,7 +9,7 @@ interface ICircularProgressIndicator {
}
export const CircularProgressIndicator: React.FC<ICircularProgressIndicator> = (
props
props,
) => {
const { size = 40, percentage = 25, strokeWidth = 6, children } = props;

View File

@ -76,6 +76,7 @@ export const AddComment: React.FC<Props> = observer((props) => {
handleSubmit(onSubmit)(e);
});
}}
cancelUploadImage={fileService.cancelUpload}
uploadFile={fileService.getUploadFileFunction(workspace_slug as string)}
deleteFile={fileService.deleteImage}
ref={editorRef}

View File

@ -103,6 +103,7 @@ export const CommentCard: React.FC<Props> = observer((props) => {
render={({ field: { onChange, value } }) => (
<LiteTextEditorWithRef
onEnterKeyPress={handleSubmit(handleCommentUpdate)}
cancelUploadImage={fileService.cancelUpload}
uploadFile={fileService.getUploadFileFunction(workspaceSlug)}
deleteFile={fileService.deleteImage}
ref={editorRef}

View File

@ -9,7 +9,6 @@ type Props = {
};
export const PeekOverviewIssueDetails: React.FC<Props> = ({ issueDetails }) => {
const mentionConfig = useEditorSuggestions();
return (
@ -20,15 +19,19 @@ export const PeekOverviewIssueDetails: React.FC<Props> = ({ issueDetails }) => {
<h4 className="break-words text-2xl font-semibold">{issueDetails.name}</h4>
{issueDetails.description_html !== "" && issueDetails.description_html !== "<p></p>" && (
<RichReadOnlyEditor
value={!issueDetails.description_html ||
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} />
: issueDetails.description_html
}
customClassName="p-3 min-h-[50px] shadow-sm"
mentionHighlights={mentionConfig.mentionHighlights}
/>
)}
<IssueReactions />
</div>
)
);
};

View File

@ -1,5 +1,6 @@
import APIService from "services/api.service";
import { API_BASE_URL } from "helpers/common.helper";
import axios from "axios";
interface UnSplashImage {
id: string;
@ -26,25 +27,37 @@ interface UnSplashImageUrls {
}
class FileService extends APIService {
private cancelSource: any;
constructor() {
super(API_BASE_URL);
this.uploadFile = this.uploadFile.bind(this);
this.deleteImage = this.deleteImage.bind(this);
this.cancelUpload = this.cancelUpload.bind(this);
}
async uploadFile(workspaceSlug: string, file: FormData): Promise<any> {
this.cancelSource = axios.CancelToken.source();
return this.post(`/api/workspaces/${workspaceSlug}/file-assets/`, file, {
headers: {
...this.getHeaders(),
"Content-Type": "multipart/form-data",
},
cancelToken: this.cancelSource.token,
})
.then((response) => response?.data)
.catch((error) => {
if (axios.isCancel(error)) {
console.log(error.message);
} else {
throw error?.response?.data;
}
});
}
cancelUpload() {
this.cancelSource.cancel("Upload cancelled");
}
getUploadFileFunction(workspaceSlug: string): (file: File) => Promise<string> {
return async (file: File) => {
const formData = new FormData();

View File

@ -7,20 +7,18 @@ export interface IMentionsStore {
mentionHighlights: IMentionHighlight[];
}
export class MentionsStore implements IMentionsStore{
export class MentionsStore implements IMentionsStore {
// root store
rootStore;
constructor(_rootStore: RootStore ){
constructor(_rootStore: RootStore) {
// rootStore
this.rootStore = _rootStore;
makeObservable(this, {
mentionHighlights: computed,
// mentionSuggestions: computed
})
});
}
// get mentionSuggestions() {
@ -40,6 +38,6 @@ export class MentionsStore implements IMentionsStore{
get mentionHighlights() {
const user = this.rootStore.user.currentUser;
return user ? [user.id] : []
return user ? [user.id] : [];
}
}

View File

@ -92,7 +92,7 @@
transform: translateY(-50%);
}
.tableWrapper .tableControls .columnsControl > button {
.tableWrapper .tableControls .columnsControl .columnsControlDiv {
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;
@ -104,26 +104,42 @@
transform: translateX(-50%);
}
.tableWrapper .tableControls .rowsControl > button {
.tableWrapper .tableControls .rowsControl .rowsControlDiv {
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 button {
.tableWrapper .tableControls .rowsControlDiv {
background-color: rgba(var(--color-primary-100));
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;
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: rgba(var(--color-primary-100));
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 .tableToolbox,
.tableWrapper .tableControls .tableColorPickerToolbox {
border: 1px solid rgba(var(--color-border-300));

View File

@ -32,8 +32,7 @@ export const GithubLoginButton: FC<GithubLoginButtonProps> = (props) => {
}, [code, gitCode, handleSignIn]);
useEffect(() => {
const origin =
typeof window !== "undefined" && window.location.origin ? window.location.origin : "";
const origin = typeof window !== "undefined" && window.location.origin ? window.location.origin : "";
setLoginCallBackURL(`${origin}/` as any);
}, []);

View File

@ -49,10 +49,7 @@ export const CustomTooltip: React.FC<Props> = ({ datum, analytics, params }) =>
: ""
}`}
>
{params.segment === "assignees__id"
? renderAssigneeName(tooltipValue.toString())
: tooltipValue}
:
{params.segment === "assignees__id" ? renderAssigneeName(tooltipValue.toString()) : tooltipValue}:
</span>
<span>{datum.value}</span>
</div>

View File

@ -112,8 +112,9 @@ export const AnalyticsGraph: React.FC<Props> = ({ analytics, barGraphData, param
<text
x={0}
y={datum.y}
textAnchor="end"
textAnchor={`${barGraphData.data.length > 7 ? "end" : "middle"}`}
fontSize={10}
fill="rgb(var(--color-text-200))"
className={`${barGraphData.data.length > 7 ? "-rotate-45" : ""}`}
>
{generateDisplayName(datum.value, analytics, params, "x_axis")}

View File

@ -22,9 +22,7 @@ export const AnalyticsScope: React.FC<Props> = ({ defaultAnalytics }) => (
keys={["count"]}
height="250px"
colors={() => `#f97316`}
customYAxisTickValues={defaultAnalytics.pending_issue_user.map((d) =>
d.count > 0 ? d.count : 50
)}
customYAxisTickValues={defaultAnalytics.pending_issue_user.map((d) => (d.count > 0 ? d.count : 50))}
tooltip={(datum) => {
const assignee = defaultAnalytics.pending_issue_user.find(
(a) => a.assignees__id === `${datum.indexValue}`

View File

@ -31,9 +31,7 @@ export const NotAuthorizedView: React.FC<Props> = ({ actionButton, type }) => {
alt="ProjectSettingImg"
/>
</div>
<h1 className="text-xl font-medium text-custom-text-100">
Oops! You are not authorized to view this page
</h1>
<h1 className="text-xl font-medium text-custom-text-100">Oops! You are not authorized to view this page</h1>
<div className="w-full max-w-md text-base text-custom-text-200">
{user ? (

View File

@ -1,7 +1,9 @@
import React, { useState } from "react";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// component
import { CustomSelect, ToggleSwitch } from "@plane/ui";
import { CustomSelect, Loader, ToggleSwitch } from "@plane/ui";
import { SelectMonthModal } from "components/automation";
// icon
import { ArchiveRestore } from "lucide-react";
@ -11,15 +13,21 @@ import { PROJECT_AUTOMATION_MONTHS } from "constants/project";
import { IProject } from "types";
type Props = {
projectDetails: IProject | undefined;
handleChange: (formData: Partial<IProject>) => Promise<void>;
disabled?: boolean;
};
export const AutoArchiveAutomation: React.FC<Props> = ({ projectDetails, handleChange, disabled = false }) => {
const initialValues: Partial<IProject> = { archive_in: 1 };
export const AutoArchiveAutomation: React.FC<Props> = observer((props) => {
const { handleChange } = props;
// states
const [monthModal, setmonthModal] = useState(false);
const initialValues: Partial<IProject> = { archive_in: 1 };
const { user: userStore, project: projectStore } = useMobxStore();
const projectDetails = projectStore.currentProjectDetails;
const userRole = userStore.currentProjectRole;
return (
<>
<SelectMonthModal
@ -48,13 +56,14 @@ export const AutoArchiveAutomation: React.FC<Props> = ({ projectDetails, handleC
projectDetails?.archive_in === 0 ? handleChange({ archive_in: 1 }) : handleChange({ archive_in: 0 })
}
size="sm"
disabled={disabled}
disabled={userRole !== 20}
/>
</div>
{projectDetails?.archive_in !== 0 && (
{projectDetails ? (
projectDetails.archive_in !== 0 && (
<div className="ml-12">
<div className="flex items-center justify-between rounded px-5 py-4 bg-custom-background-90 border-[0.5px] border-custom-border-200 gap-2 w-full">
<div className="flex items-center justify-between rounded px-5 py-4 bg-custom-background-90 border border-custom-border-200 gap-2 w-full">
<div className="w-1/2 text-sm font-medium">Auto-archive issues that are closed for</div>
<div className="w-1/2">
<CustomSelect
@ -65,7 +74,7 @@ export const AutoArchiveAutomation: React.FC<Props> = ({ projectDetails, handleC
}}
input
width="w-full"
disabled={disabled}
disabled={userRole !== 20}
>
<>
{PROJECT_AUTOMATION_MONTHS.map((month) => (
@ -86,8 +95,13 @@ export const AutoArchiveAutomation: React.FC<Props> = ({ projectDetails, handleC
</div>
</div>
</div>
)
) : (
<Loader className="ml-12">
<Loader.Item height="50px" />
</Loader>
)}
</div>
</>
);
};
});

View File

@ -1,42 +1,32 @@
import React, { useState } from "react";
import useSWR from "swr";
import { useRouter } from "next/router";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// component
import { SelectMonthModal } from "components/automation";
import { CustomSelect, CustomSearchSelect, ToggleSwitch, StateGroupIcon, DoubleCircleIcon } from "@plane/ui";
import { CustomSelect, CustomSearchSelect, ToggleSwitch, StateGroupIcon, DoubleCircleIcon, Loader } from "@plane/ui";
// icons
import { ArchiveX } from "lucide-react";
// services
import { ProjectStateService } from "services/project";
// constants
import { PROJECT_AUTOMATION_MONTHS } from "constants/project";
import { STATES_LIST } from "constants/fetch-keys";
// types
import { IProject } from "types";
// helper
import { getStatesList } from "helpers/state.helper";
// fetch keys
import { PROJECT_AUTOMATION_MONTHS } from "constants/project";
type Props = {
projectDetails: IProject | undefined;
handleChange: (formData: Partial<IProject>) => Promise<void>;
disabled?: boolean;
};
const projectStateService = new ProjectStateService();
export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleChange, disabled = false }) => {
export const AutoCloseAutomation: React.FC<Props> = observer((props) => {
const { handleChange } = props;
// states
const [monthModal, setmonthModal] = useState(false);
const router = useRouter();
const { workspaceSlug, projectId } = router.query;
const { user: userStore, project: projectStore, projectState: projectStateStore } = useMobxStore();
const { data: stateGroups } = useSWR(
workspaceSlug && projectId ? STATES_LIST(projectId as string) : null,
workspaceSlug && projectId
? () => projectStateService.getStates(workspaceSlug as string, projectId as string)
: null
);
const states = getStatesList(stateGroups);
const userRole = userStore.currentProjectRole;
const projectDetails = projectStore.currentProjectDetails;
// const stateGroups = projectStateStore.groupedProjectStates ?? undefined;
const states = projectStateStore.projectStates;
const options = states
?.filter((state) => state.group === "cancelled")
@ -53,7 +43,7 @@ export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleCha
const multipleOptions = (options ?? []).length > 1;
const defaultState = stateGroups && stateGroups.cancelled ? stateGroups.cancelled[0].id : null;
const defaultState = states?.find((s) => s.group === "cancelled")?.id || null;
const selectedOption = states?.find((s) => s.id === projectDetails?.default_state ?? defaultState);
const currentDefaultState = states?.find((s) => s.id === defaultState);
@ -72,8 +62,7 @@ export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleCha
handleClose={() => setmonthModal(false)}
handleChange={handleChange}
/>
<div className="flex flex-col gap-4 border-b border-custom-border-100 px-4 py-6">
<div className="flex flex-col gap-4 border-b border-custom-border-200 px-4 py-6">
<div className="flex items-center justify-between">
<div className="flex items-start gap-3">
<div className="flex items-center justify-center p-3 rounded bg-custom-background-90">
@ -82,7 +71,7 @@ export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleCha
<div className="">
<h4 className="text-sm font-medium">Auto-close issues</h4>
<p className="text-sm text-custom-text-200 tracking-tight">
Plane will automatically close issue that havent been completed or cancelled.
Plane will automatically close issue that haven{"'"}t been completed or cancelled.
</p>
</div>
</div>
@ -94,13 +83,14 @@ export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleCha
: handleChange({ close_in: 0, default_state: null })
}
size="sm"
disabled={disabled}
disabled={userRole !== 20}
/>
</div>
{projectDetails?.close_in !== 0 && (
{projectDetails ? (
projectDetails.close_in !== 0 && (
<div className="ml-12">
<div className="flex flex-col rounded bg-custom-background-90 border-[0.5px] border-custom-border-200 p-2">
<div className="flex flex-col rounded bg-custom-background-90 border border-custom-border-200">
<div className="flex items-center justify-between px-5 py-4 gap-2 w-full">
<div className="w-1/2 text-sm font-medium">Auto-close issues that are inactive for</div>
<div className="w-1/2">
@ -112,7 +102,7 @@ export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleCha
}}
input
width="w-full"
disabled={disabled}
disabled={userRole !== 20}
>
<>
{PROJECT_AUTOMATION_MONTHS.map((month) => (
@ -136,7 +126,7 @@ export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleCha
<div className="w-1/2 text-sm font-medium">Auto-close Status</div>
<div className="w-1/2 ">
<CustomSearchSelect
value={projectDetails?.default_state ? projectDetails?.default_state : defaultState}
value={projectDetails?.default_state ?? defaultState}
label={
<div className="flex items-center gap-2">
{selectedOption ? (
@ -173,8 +163,13 @@ export const AutoCloseAutomation: React.FC<Props> = ({ projectDetails, handleCha
</div>
</div>
</div>
)
) : (
<Loader className="ml-12">
<Loader.Item height="50px" />
</Loader>
)}
</div>
</>
);
};
});

View File

@ -3,6 +3,7 @@ import { useRouter } from "next/router";
import useSWR, { mutate } from "swr";
import { Command } from "cmdk";
import { Dialog, Transition } from "@headlessui/react";
import { observer } from "mobx-react-lite";
import {
FileText,
FolderPlus,
@ -16,12 +17,13 @@ import {
UserMinus2,
UserPlus2,
} from "lucide-react";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// services
import { WorkspaceService } from "services/workspace.service";
import { IssueService } from "services/issue";
// hooks
import useDebounce from "hooks/use-debounce";
import useUser from "hooks/use-user";
import useToast from "hooks/use-toast";
// components
import {
@ -61,11 +63,8 @@ type Props = {
const workspaceService = new WorkspaceService();
const issueService = new IssueService();
export const CommandModal: React.FC<Props> = (props) => {
export const CommandModal: React.FC<Props> = observer((props) => {
const { deleteIssue, isPaletteOpen, closePalette } = props;
// router
const router = useRouter();
const { workspaceSlug, projectId, issueId } = router.query;
// states
const [placeholder, setPlaceholder] = useState("Type a command or search...");
const [resultsCount, setResultsCount] = useState(0);
@ -86,14 +85,19 @@ export const CommandModal: React.FC<Props> = (props) => {
const [isWorkspaceLevel, setIsWorkspaceLevel] = useState(false);
const [pages, setPages] = useState<string[]>([]);
const { user: userStore, commandPalette: commandPaletteStore } = useMobxStore();
const user = userStore.currentUser ?? undefined;
// router
const router = useRouter();
const { workspaceSlug, projectId, issueId } = router.query;
const page = pages[pages.length - 1];
const debouncedSearchTerm = useDebounce(searchTerm, 500);
const { setToastAlert } = useToast();
const { user } = useUser();
const { data: issueDetails } = useSWR(
workspaceSlug && projectId && issueId ? ISSUE_DETAILS(issueId as string) : null,
workspaceSlug && projectId && issueId
@ -468,10 +472,7 @@ export const CommandModal: React.FC<Props> = (props) => {
<Command.Item
onSelect={() => {
closePalette();
const e = new KeyboardEvent("keydown", {
key: "c",
});
document.dispatchEvent(e);
commandPaletteStore.toggleCreateIssueModal(true);
}}
className="focus:bg-custom-background-80"
>
@ -488,10 +489,7 @@ export const CommandModal: React.FC<Props> = (props) => {
<Command.Item
onSelect={() => {
closePalette();
const e = new KeyboardEvent("keydown", {
key: "p",
});
document.dispatchEvent(e);
commandPaletteStore.toggleCreateProjectModal(true);
}}
className="focus:outline-none"
>
@ -510,10 +508,7 @@ export const CommandModal: React.FC<Props> = (props) => {
<Command.Item
onSelect={() => {
closePalette();
const e = new KeyboardEvent("keydown", {
key: "q",
});
document.dispatchEvent(e);
commandPaletteStore.toggleCreateCycleModal(true);
}}
className="focus:outline-none"
>
@ -528,10 +523,7 @@ export const CommandModal: React.FC<Props> = (props) => {
<Command.Item
onSelect={() => {
closePalette();
const e = new KeyboardEvent("keydown", {
key: "m",
});
document.dispatchEvent(e);
commandPaletteStore.toggleCreateModuleModal(true);
}}
className="focus:outline-none"
>
@ -546,10 +538,7 @@ export const CommandModal: React.FC<Props> = (props) => {
<Command.Item
onSelect={() => {
closePalette();
const e = new KeyboardEvent("keydown", {
key: "v",
});
document.dispatchEvent(e);
commandPaletteStore.toggleCreateViewModal(true);
}}
className="focus:outline-none"
>
@ -564,10 +553,7 @@ export const CommandModal: React.FC<Props> = (props) => {
<Command.Item
onSelect={() => {
closePalette();
const e = new KeyboardEvent("keydown", {
key: "d",
});
document.dispatchEvent(e);
commandPaletteStore.toggleCreatePageModal(true);
}}
className="focus:outline-none"
>
@ -621,10 +607,7 @@ export const CommandModal: React.FC<Props> = (props) => {
<Command.Item
onSelect={() => {
closePalette();
const e = new KeyboardEvent("keydown", {
key: "h",
});
document.dispatchEvent(e);
commandPaletteStore.toggleShortcutModal(true);
}}
className="focus:outline-none"
>
@ -762,4 +745,4 @@ export const CommandModal: React.FC<Props> = (props) => {
</Dialog>
</Transition.Root>
);
};
});

View File

@ -1,9 +1,6 @@
import React, { Dispatch, SetStateAction, useCallback } from "react";
import { useRouter } from "next/router";
import useSWR, { mutate } from "swr";
// cmdk
import { Command } from "cmdk";
// services
@ -13,8 +10,6 @@ import { ProjectStateService } from "services/project";
import { Spinner, StateGroupIcon } from "@plane/ui";
// icons
import { Check } from "lucide-react";
// helpers
import { getStatesList } from "helpers/state.helper";
// types
import { IUser, IIssue } from "types";
// fetch keys
@ -34,11 +29,10 @@ export const ChangeIssueState: React.FC<Props> = ({ setIsPaletteOpen, issue, use
const router = useRouter();
const { workspaceSlug, projectId, issueId } = router.query;
const { data: stateGroups, mutate: mutateIssueDetails } = useSWR(
const { data: states, mutate: mutateStates } = useSWR(
workspaceSlug && projectId ? STATES_LIST(projectId as string) : null,
workspaceSlug && projectId ? () => stateService.getStates(workspaceSlug as string, projectId as string) : null
);
const states = getStatesList(stateGroups);
const submitChanges = useCallback(
async (formData: Partial<IIssue>) => {
@ -60,14 +54,14 @@ export const ChangeIssueState: React.FC<Props> = ({ setIsPaletteOpen, issue, use
await issueService
.patchIssue(workspaceSlug as string, projectId as string, issueId as string, payload, user)
.then(() => {
mutateIssueDetails();
mutateStates();
mutate(PROJECT_ISSUES_ACTIVITY(issueId as string));
})
.catch((e) => {
console.error(e);
});
},
[workspaceSlug, issueId, projectId, mutateIssueDetails, user]
[workspaceSlug, issueId, projectId, mutateStates, user]
);
const handleIssueState = (stateId: string) => {

View File

@ -57,8 +57,7 @@ const ProgressChart: React.FC<Props> = ({ distribution, startDate, endDate, tota
const interval = Math.ceil(totalDates / maxDates);
const limitedDates = [];
for (let i = 0; i < totalDates; i += interval)
limitedDates.push(renderShortNumericDateFormat(dates[i]));
for (let i = 0; i < totalDates; i += interval) limitedDates.push(renderShortNumericDateFormat(dates[i]));
if (!limitedDates.includes(renderShortNumericDateFormat(dates[totalDates - 1])))
limitedDates.push(renderShortNumericDateFormat(dates[totalDates - 1]));

View File

@ -1,10 +1,12 @@
import { MouseEvent } from "react";
import Link from "next/link";
import { useRouter } from "next/router";
import { observer } from "mobx-react-lite";
import useSWR from "swr";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// hooks
import useToast from "hooks/use-toast";
import { useMobxStore } from "lib/mobx/store-provider";
// ui
import { SingleProgressStats } from "components/core";
import {
@ -25,7 +27,6 @@ import { ActiveCycleProgressStats } from "components/cycles";
import { ViewIssueLabel } from "components/issues";
// icons
import { AlarmClock, AlertTriangle, ArrowRight, CalendarDays, Star, Target } from "lucide-react";
// helpers
import { getDateRangeStatus, renderShortDateWithYearFormat, findHowManyDaysLeft } from "helpers/date-time.helper";
import { truncateText } from "helpers/string.helper";
@ -65,12 +66,12 @@ interface IActiveCycleDetails {
projectId: string;
}
export const ActiveCycleDetails: React.FC<IActiveCycleDetails> = (props) => {
export const ActiveCycleDetails: React.FC<IActiveCycleDetails> = observer((props) => {
const router = useRouter();
const { workspaceSlug, projectId } = props;
const { cycle: cycleStore } = useMobxStore();
const { cycle: cycleStore, commandPalette: commandPaletteStore } = useMobxStore();
const { setToastAlert } = useToast();
@ -117,12 +118,7 @@ export const ActiveCycleDetails: React.FC<IActiveCycleDetails> = (props) => {
<button
type="button"
className="text-custom-primary-100 text-sm outline-none"
onClick={() => {
const e = new KeyboardEvent("keydown", {
key: "q",
});
document.dispatchEvent(e);
}}
onClick={() => commandPaletteStore.toggleCreateCycleModal(true)}
>
Create a new cycle
</button>
@ -485,4 +481,4 @@ export const ActiveCycleDetails: React.FC<IActiveCycleDetails> = (props) => {
</div>
</div>
);
};
});

View File

@ -41,7 +41,7 @@ export const CyclePeekOverview: React.FC<Props> = observer(({ projectId, workspa
{peekCycle && (
<div
ref={ref}
className="flex flex-col gap-3.5 h-full w-[24rem] z-10 overflow-y-auto border-l border-custom-border-100 bg-custom-sidebar-background-100 px-6 py-3.5 duration-300 flex-shrink-0"
className="flex flex-col gap-3.5 h-full w-[24rem] overflow-y-auto border-l border-custom-border-100 bg-custom-sidebar-background-100 px-6 py-3.5 duration-300 flex-shrink-0"
style={{
boxShadow:
"0px 1px 4px 0px rgba(0, 0, 0, 0.06), 0px 2px 4px 0px rgba(16, 24, 40, 0.06), 0px 1px 8px -1px rgba(16, 24, 40, 0.06)",

View File

@ -1,8 +1,11 @@
import { FC } from "react";
// types
import { ICycle } from "types";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// components
import { CyclePeekOverview, CyclesBoardCard } from "components/cycles";
// types
import { ICycle } from "types";
export interface ICyclesBoard {
cycles: ICycle[];
@ -12,9 +15,11 @@ export interface ICyclesBoard {
peekCycle: string;
}
export const CyclesBoard: FC<ICyclesBoard> = (props) => {
export const CyclesBoard: FC<ICyclesBoard> = observer((props) => {
const { cycles, filter, workspaceSlug, projectId, peekCycle } = props;
const { commandPalette: commandPaletteStore } = useMobxStore();
return (
<>
{cycles.length > 0 ? (
@ -53,12 +58,7 @@ export const CyclesBoard: FC<ICyclesBoard> = (props) => {
<button
type="button"
className="text-custom-primary-100 text-sm outline-none"
onClick={() => {
const e = new KeyboardEvent("keydown", {
key: "q",
});
document.dispatchEvent(e);
}}
onClick={() => commandPaletteStore.toggleCreateCycleModal(true)}
>
Create a new cycle
</button>
@ -67,4 +67,4 @@ export const CyclesBoard: FC<ICyclesBoard> = (props) => {
)}
</>
);
};
});

View File

@ -231,7 +231,7 @@ export const CyclesListItem: FC<TCyclesListItem> = (props) => {
</button>
)}
<CustomMenu width="auto" ellipsis className="z-10">
<CustomMenu width="auto" ellipsis>
{!isCompleted && (
<>
<CustomMenu.MenuItem onClick={handleEditCycle}>

View File

@ -1,7 +1,9 @@
import { FC } from "react";
import { observer } from "mobx-react-lite";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// components
import { CyclePeekOverview, CyclesListItem } from "components/cycles";
// ui
import { Loader } from "@plane/ui";
// types
@ -14,9 +16,11 @@ export interface ICyclesList {
projectId: string;
}
export const CyclesList: FC<ICyclesList> = (props) => {
export const CyclesList: FC<ICyclesList> = observer((props) => {
const { cycles, filter, workspaceSlug, projectId } = props;
const { commandPalette: commandPaletteStore } = useMobxStore();
return (
<>
{cycles ? (
@ -53,12 +57,7 @@ export const CyclesList: FC<ICyclesList> = (props) => {
<button
type="button"
className="text-custom-primary-100 text-sm outline-none"
onClick={() => {
const e = new KeyboardEvent("keydown", {
key: "q",
});
document.dispatchEvent(e);
}}
onClick={() => commandPaletteStore.toggleCreateCycleModal(true)}
>
Create a new cycle
</button>
@ -75,4 +74,4 @@ export const CyclesList: FC<ICyclesList> = (props) => {
)}
</>
);
};
});

View File

@ -135,7 +135,7 @@ export const CycleForm: React.FC<Props> = (props) => {
</div>
</div>
</div>
<div className="flex items-center justify-end gap-2 pt-5 mt-5 border-t-[0.5px] border-custom-border-200 ">
<div className="flex items-center justify-end gap-2 pt-5 mt-5 border-t-[0.5px] border-custom-border-100 ">
<Button variant="neutral-primary" onClick={handleClose}>
Cancel
</Button>

View File

@ -317,11 +317,11 @@ export const CycleDetailsSidebar: React.FC<Props> = observer((props) => {
<LinkIcon className="h-3 w-3 text-custom-text-300" />
</button>
{!isCompleted && (
<CustomMenu width="lg" ellipsis>
<CustomMenu width="lg" placement="bottom-end" ellipsis>
<CustomMenu.MenuItem onClick={() => setCycleDeleteModal(true)}>
<span className="flex items-center justify-start gap-2">
<Trash2 className="h-4 w-4" />
<span>Delete</span>
<Trash2 className="h-3 w-3" />
<span>Delete cycle</span>
</span>
</CustomMenu.MenuItem>
</CustomMenu>

View File

@ -34,16 +34,8 @@ export const MonthChartView: FC<any> = () => {
style={{ width: `${currentViewData?.data.width}px` }}
>
<div className="text-xs space-x-1">
<span className="text-custom-text-200">
{monthDay.dayData.shortTitle[0]}
</span>{" "}
<span
className={
monthDay.today
? "bg-custom-primary-100 text-white px-1 rounded-full"
: ""
}
>
<span className="text-custom-text-200">{monthDay.dayData.shortTitle[0]}</span>{" "}
<span className={monthDay.today ? "bg-custom-primary-100 text-white px-1 rounded-full" : ""}>
{monthDay.day}
</span>
</div>
@ -63,9 +55,7 @@ export const MonthChartView: FC<any> = () => {
>
<div
className={`relative h-full w-full flex-1 flex justify-center ${
["sat", "sun"].includes(monthDay?.dayData?.shortTitle || "")
? `bg-custom-background-90`
: ``
["sat", "sun"].includes(monthDay?.dayData?.shortTitle || "") ? `bg-custom-background-90` : ``
}`}
>
{/* {monthDay?.today && (

View File

@ -27,8 +27,7 @@ export const months: WeekMonthDataType[] = [
{ key: 11, shortTitle: "dec", title: "december" },
];
export const charCapitalize = (word: string) =>
`${word.charAt(0).toUpperCase()}${word.substring(1)}`;
export const charCapitalize = (word: string) => `${word.charAt(0).toUpperCase()}${word.substring(1)}`;
export const bindZero = (value: number) => (value > 9 ? `${value}` : `0${value}`);
@ -50,9 +49,7 @@ export const datePreview = (date: Date, includeTime: boolean = false) => {
month = months[month as number] as WeekMonthDataType;
const year = date.getFullYear();
return `${charCapitalize(month?.shortTitle)} ${day}, ${year}${
includeTime ? `, ${timePreview(date)}` : ``
}`;
return `${charCapitalize(month?.shortTitle)} ${day}, ${year}${includeTime ? `, ${timePreview(date)}` : ``}`;
};
// context data
@ -137,8 +134,6 @@ export const allViewsWithData: ChartDataType[] = [
];
export const currentViewDataWithView = (view: string = "month") => {
const currentView: ChartDataType | undefined = allViewsWithData.find(
(_viewData) => _viewData.key === view
);
const currentView: ChartDataType | undefined = allViewsWithData.find((_viewData) => _viewData.key === view);
return currentView;
};

View File

@ -3,12 +3,7 @@ import { ChartDataType } from "../types";
// data
import { weeks, months } from "../data";
// helpers
import {
generateDate,
getWeekNumberByDate,
getNumberOfDaysInMonth,
getDatesBetweenTwoDates,
} from "./helpers";
import { generateDate, getWeekNumberByDate, getNumberOfDaysInMonth, getDatesBetweenTwoDates } from "./helpers";
type GetAllDaysInMonthInMonthViewType = {
date: any;
@ -34,9 +29,7 @@ const getAllDaysInMonthInMonthView = (month: number, year: number) => {
title: `${weeks[date.getDay()].shortTitle} ${_day + 1}`,
active: false,
today:
currentDate.getFullYear() === year &&
currentDate.getMonth() === month &&
currentDate.getDate() === _day + 1
currentDate.getFullYear() === year && currentDate.getMonth() === month && currentDate.getDate() === _day + 1
? true
: false,
});
@ -72,16 +65,8 @@ export const generateBiWeekChart = (monthPayload: ChartDataType, side: null | "l
if (side === null) {
const currentDate = renderState.data.currentDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -96,16 +81,8 @@ export const generateBiWeekChart = (monthPayload: ChartDataType, side: null | "l
} else if (side === "left") {
const currentDate = renderState.data.startDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - 1,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -116,16 +93,8 @@ export const generateBiWeekChart = (monthPayload: ChartDataType, side: null | "l
} else if (side === "right") {
const currentDate = renderState.data.endDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + 1,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);

View File

@ -10,8 +10,7 @@ export const getWeekNumberByDate = (date: Date) => {
const firstWeekStart = firstDayOfYear.getTime() - daysOffset * 24 * 60 * 60 * 1000;
const weekStart = new Date(firstWeekStart);
const weekNumber =
Math.floor((date.getTime() - weekStart.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1;
const weekNumber = Math.floor((date.getTime() - weekStart.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1;
return weekNumber;
};
@ -25,8 +24,7 @@ export const getNumberOfDaysInMonth = (month: number, year: number) => {
return date.getDate();
};
export const generateDate = (day: number, month: number, year: number) =>
new Date(year, month, day);
export const generateDate = (day: number, month: number, year: number) => new Date(year, month, day);
export const getDatesBetweenTwoDates = (startDate: Date, endDate: Date) => {
const months = [];
@ -45,8 +43,7 @@ export const getDatesBetweenTwoDates = (startDate: Date, endDate: Date) => {
months.push(new Date(currentYear, currentMonth));
currentDate.setMonth(currentDate.getMonth() + 1);
}
if (endYear === currentDate.getFullYear() && endMonth === currentDate.getMonth())
months.push(endDate);
if (endYear === currentDate.getFullYear() && endMonth === currentDate.getMonth()) months.push(endDate);
return months;
};
@ -73,9 +70,7 @@ export const getAllDaysInMonth = (month: number, year: number) => {
weekNumber: getWeekNumberByDate(date),
title: `${weeks[date.getDay()].shortTitle} ${_day + 1}`,
today:
currentDate.getFullYear() === year &&
currentDate.getMonth() === month &&
currentDate.getDate() === _day + 1
currentDate.getFullYear() === year && currentDate.getMonth() === month && currentDate.getDate() === _day + 1
? true
: false,
});
@ -99,10 +94,7 @@ export const generateMonthDataByMonth = (month: number, year: number) => {
return monthPayload;
};
export const generateMonthDataByYear = (
monthPayload: ChartDataType,
side: null | "left" | "right"
) => {
export const generateMonthDataByYear = (monthPayload: ChartDataType, side: null | "left" | "right") => {
let renderState = monthPayload;
const renderPayload: any = [];
@ -114,16 +106,8 @@ export const generateMonthDataByYear = (
if (side === null) {
const currentDate = renderState.data.currentDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -138,16 +122,8 @@ export const generateMonthDataByYear = (
} else if (side === "left") {
const currentDate = renderState.data.startDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - 1,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -158,16 +134,8 @@ export const generateMonthDataByYear = (
} else if (side === "right") {
const currentDate = renderState.data.endDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + 1,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);

View File

@ -1,6 +1,5 @@
// Generating the date by using the year, month, and day
export const generateDate = (day: number, month: number, year: number) =>
new Date(year, month, day);
export const generateDate = (day: number, month: number, year: number) => new Date(year, month, day);
// Getting the number of days in a month
export const getNumberOfDaysInMonth = (month: number, year: number) => {
@ -20,8 +19,7 @@ export const getWeekNumberByDate = (date: Date) => {
const firstWeekStart = firstDayOfYear.getTime() - daysOffset * 24 * 60 * 60 * 1000;
const weekStart = new Date(firstWeekStart);
const weekNumber =
Math.floor((date.getTime() - weekStart.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1;
const weekNumber = Math.floor((date.getTime() - weekStart.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1;
return weekNumber;
};
@ -86,8 +84,7 @@ export const getDatesBetweenTwoDates = (startDate: Date, endDate: Date) => {
dates.push(new Date(currentYear, currentMonth));
currentDate.setMonth(currentDate.getMonth() + 1);
}
if (endYear === currentDate.getFullYear() && endMonth === currentDate.getMonth())
dates.push(endDate);
if (endYear === currentDate.getFullYear() && endMonth === currentDate.getMonth()) dates.push(endDate);
return dates;
};

View File

@ -10,8 +10,7 @@ export const getWeekNumberByDate = (date: Date) => {
const firstWeekStart = firstDayOfYear.getTime() - daysOffset * 24 * 60 * 60 * 1000;
const weekStart = new Date(firstWeekStart);
const weekNumber =
Math.floor((date.getTime() - weekStart.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1;
const weekNumber = Math.floor((date.getTime() - weekStart.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1;
return weekNumber;
};
@ -25,8 +24,7 @@ export const getNumberOfDaysInMonth = (month: number, year: number) => {
return date.getDate();
};
export const generateDate = (day: number, month: number, year: number) =>
new Date(year, month, day);
export const generateDate = (day: number, month: number, year: number) => new Date(year, month, day);
export const getDatesBetweenTwoDates = (startDate: Date, endDate: Date) => {
const months = [];
@ -45,8 +43,7 @@ export const getDatesBetweenTwoDates = (startDate: Date, endDate: Date) => {
months.push(new Date(currentYear, currentMonth));
currentDate.setMonth(currentDate.getMonth() + 1);
}
if (endYear === currentDate.getFullYear() && endMonth === currentDate.getMonth())
months.push(endDate);
if (endYear === currentDate.getFullYear() && endMonth === currentDate.getMonth()) months.push(endDate);
return months;
};
@ -73,9 +70,7 @@ export const getAllDaysInMonth = (month: number, year: number) => {
weekNumber: getWeekNumberByDate(date),
title: `${weeks[date.getDay()].shortTitle} ${_day + 1}`,
today:
currentDate.getFullYear() === year &&
currentDate.getMonth() === month &&
currentDate.getDate() === _day + 1
currentDate.getFullYear() === year && currentDate.getMonth() === month && currentDate.getDate() === _day + 1
? true
: false,
});
@ -99,10 +94,7 @@ export const generateMonthDataByMonth = (month: number, year: number) => {
return monthPayload;
};
export const generateMonthDataByYear = (
monthPayload: ChartDataType,
side: null | "left" | "right"
) => {
export const generateMonthDataByYear = (monthPayload: ChartDataType, side: null | "left" | "right") => {
let renderState = monthPayload;
const renderPayload: any = [];
@ -114,16 +106,8 @@ export const generateMonthDataByYear = (
if (side === null) {
const currentDate = renderState.data.currentDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -138,16 +122,8 @@ export const generateMonthDataByYear = (
} else if (side === "left") {
const currentDate = renderState.data.startDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - 1,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -158,16 +134,8 @@ export const generateMonthDataByYear = (
} else if (side === "right") {
const currentDate = renderState.data.endDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + 1,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);

View File

@ -3,12 +3,7 @@ import { ChartDataType, IGanttBlock } from "../types";
// data
import { weeks, months } from "../data";
// helpers
import {
generateDate,
getWeekNumberByDate,
getNumberOfDaysInMonth,
getDatesBetweenTwoDates,
} from "./helpers";
import { generateDate, getWeekNumberByDate, getNumberOfDaysInMonth, getDatesBetweenTwoDates } from "./helpers";
type GetAllDaysInMonthInMonthViewType = {
date: any;
@ -62,9 +57,7 @@ const getAllDaysInMonthInMonthView = (month: number, year: number): IMonthChild[
title: `${weeks[date.getDay()].shortTitle} ${_day + 1}`,
active: false,
today:
currentDate.getFullYear() === year &&
currentDate.getMonth() === month &&
currentDate.getDate() === _day + 1
currentDate.getFullYear() === year && currentDate.getMonth() === month && currentDate.getDate() === _day + 1
? true
: false,
});
@ -100,16 +93,8 @@ export const generateMonthChart = (monthPayload: ChartDataType, side: null | "le
if (side === null) {
const currentDate = renderState.data.currentDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -124,16 +109,8 @@ export const generateMonthChart = (monthPayload: ChartDataType, side: null | "le
} else if (side === "left") {
const currentDate = renderState.data.startDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - 1,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -144,16 +121,8 @@ export const generateMonthChart = (monthPayload: ChartDataType, side: null | "le
} else if (side === "right") {
const currentDate = renderState.data.endDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + 1,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -191,10 +160,7 @@ export const getNumberOfDaysBetweenTwoDatesInMonth = (startDate: Date, endDate:
};
// calc item scroll position and width
export const getMonthChartItemPositionWidthInMonth = (
chartData: ChartDataType,
itemData: IGanttBlock
) => {
export const getMonthChartItemPositionWidthInMonth = (chartData: ChartDataType, itemData: IGanttBlock) => {
let scrollPosition: number = 0;
let scrollWidth: number = 0;
@ -207,9 +173,7 @@ export const getMonthChartItemPositionWidthInMonth = (
// position code starts
const positionTimeDifference: number = startDate.getTime() - itemStartDate.getTime();
const positionDaysDifference: number = Math.abs(
Math.floor(positionTimeDifference / (1000 * 60 * 60 * 24))
);
const positionDaysDifference: number = Math.abs(Math.floor(positionTimeDifference / (1000 * 60 * 60 * 24)));
scrollPosition = positionDaysDifference * chartData.data.width;
var diffMonths = (itemStartDate.getFullYear() - startDate.getFullYear()) * 12;
@ -221,9 +185,7 @@ export const getMonthChartItemPositionWidthInMonth = (
// width code starts
const widthTimeDifference: number = itemStartDate.getTime() - itemTargetDate.getTime();
const widthDaysDifference: number = Math.abs(
Math.floor(widthTimeDifference / (1000 * 60 * 60 * 24))
);
const widthDaysDifference: number = Math.abs(Math.floor(widthTimeDifference / (1000 * 60 * 60 * 24)));
scrollWidth = (widthDaysDifference + 1) * chartData.data.width + 1;
// width code ends

View File

@ -36,10 +36,7 @@ const generateMonthDataByMonthAndYearInMonthView = (month: number, year: number)
return weekPayload;
};
export const generateQuarterChart = (
quarterPayload: ChartDataType,
side: null | "left" | "right"
) => {
export const generateQuarterChart = (quarterPayload: ChartDataType, side: null | "left" | "right") => {
let renderState = quarterPayload;
const renderPayload: any = [];

View File

@ -3,12 +3,7 @@ import { ChartDataType } from "../types";
// data
import { weeks, months } from "../data";
// helpers
import {
generateDate,
getWeekNumberByDate,
getNumberOfDaysInMonth,
getDatesBetweenTwoDates,
} from "./helpers";
import { generateDate, getWeekNumberByDate, getNumberOfDaysInMonth, getDatesBetweenTwoDates } from "./helpers";
type GetAllDaysInMonthInMonthViewType = {
date: any;
@ -34,9 +29,7 @@ const getAllDaysInMonthInMonthView = (month: number, year: number) => {
title: `${weeks[date.getDay()].shortTitle} ${_day + 1}`,
active: false,
today:
currentDate.getFullYear() === year &&
currentDate.getMonth() === month &&
currentDate.getDate() === _day + 1
currentDate.getFullYear() === year && currentDate.getMonth() === month && currentDate.getDate() === _day + 1
? true
: false,
});
@ -72,16 +65,8 @@ export const generateWeekChart = (monthPayload: ChartDataType, side: null | "lef
if (side === null) {
const currentDate = renderState.data.currentDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -96,16 +81,8 @@ export const generateWeekChart = (monthPayload: ChartDataType, side: null | "lef
} else if (side === "left") {
const currentDate = renderState.data.startDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - range,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() - 1,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - range, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);
@ -116,16 +93,8 @@ export const generateWeekChart = (monthPayload: ChartDataType, side: null | "lef
} else if (side === "right") {
const currentDate = renderState.data.endDate;
minusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + 1,
currentDate.getDate()
);
plusDate = new Date(
currentDate.getFullYear(),
currentDate.getMonth() + range,
currentDate.getDate()
);
minusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, currentDate.getDate());
plusDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + range, currentDate.getDate());
if (minusDate && plusDate) filteredDates = getDatesBetweenTwoDates(minusDate, plusDate);

View File

@ -31,6 +31,8 @@ export const CycleIssuesHeader: React.FC = observer(() => {
cycle: cycleStore,
cycleIssueFilter: cycleIssueFilterStore,
project: projectStore,
projectState: projectStateStore,
commandPalette: commandPaletteStore,
} = useMobxStore();
const { currentProjectDetails } = projectStore;
@ -139,7 +141,6 @@ export const CycleIssuesHeader: React.FC = observer(() => {
type="component"
component={
<CustomMenu
placement="bottom-start"
label={
<>
<ContrastIcon className="h-3 w-3" />
@ -148,6 +149,7 @@ export const CycleIssuesHeader: React.FC = observer(() => {
}
className="ml-1.5 flex-shrink-0"
width="auto"
placement="bottom-start"
>
{cyclesList?.map((cycle) => (
<CustomMenu.MenuItem
@ -177,7 +179,7 @@ export const CycleIssuesHeader: React.FC = observer(() => {
}
labels={projectStore.labels?.[projectId?.toString() ?? ""] ?? undefined}
members={projectStore.members?.[projectId?.toString() ?? ""]?.map((m) => m.member)}
states={projectStore.states?.[projectId?.toString() ?? ""] ?? undefined}
states={projectStateStore.states?.[projectId?.toString() ?? ""] ?? undefined}
/>
</FiltersDropdown>
<FiltersDropdown title="Display" placement="bottom-end">
@ -194,17 +196,8 @@ export const CycleIssuesHeader: React.FC = observer(() => {
<Button onClick={() => setAnalyticsModal(true)} variant="neutral-primary" size="sm">
Analytics
</Button>
<Button
onClick={() => {
const e = new KeyboardEvent("keydown", {
key: "c",
});
document.dispatchEvent(e);
}}
size="sm"
prependIcon={<Plus />}
>
Add issue
<Button onClick={() => commandPaletteStore.toggleCreateIssueModal(true)} size="sm" prependIcon={<Plus />}>
Add Issue
</Button>
<button
type="button"

View File

@ -1,22 +1,20 @@
import { FC } from "react";
import { useRouter } from "next/router";
import { observer } from "mobx-react-lite";
import { Plus } from "lucide-react";
// mobx store
import { useMobxStore } from "lib/mobx/store-provider";
// ui
import { Breadcrumbs, Button, ContrastIcon } from "@plane/ui";
// helpers
import { renderEmoji } from "helpers/emoji.helper";
// hooks
import { useMobxStore } from "lib/mobx/store-provider";
export interface ICyclesHeader {}
export const CyclesHeader: FC<ICyclesHeader> = (props) => {
const {} = props;
export const CyclesHeader: FC = observer(() => {
// router
const router = useRouter();
const { workspaceSlug } = router.query;
// store
const { project: projectStore } = useMobxStore();
const { project: projectStore, commandPalette: commandPaletteStore } = useMobxStore();
const { currentProjectDetails } = projectStore;
return (
@ -54,14 +52,11 @@ export const CyclesHeader: FC<ICyclesHeader> = (props) => {
<Button
variant="primary"
prependIcon={<Plus />}
onClick={() => {
const e = new KeyboardEvent("keydown", { key: "q" });
document.dispatchEvent(e);
}}
onClick={() => commandPaletteStore.toggleCreateCycleModal(true)}
>
Build cycle
</Button>
</div>
</div>
);
};
});

View File

@ -41,6 +41,7 @@ export const GlobalIssuesHeader: React.FC<Props> = observer((props) => {
globalViewFilters: globalViewFiltersStore,
workspaceFilter: workspaceFilterStore,
workspace: workspaceStore,
workspaceMember: { workspaceMembers },
project: projectStore,
} = useMobxStore();
@ -145,7 +146,7 @@ export const GlobalIssuesHeader: React.FC<Props> = observer((props) => {
handleFiltersUpdate={handleFiltersUpdate}
layoutDisplayFiltersOptions={ISSUE_DISPLAY_FILTERS_BY_LAYOUT.my_issues.spreadsheet}
labels={workspaceStore.workspaceLabels ?? undefined}
members={workspaceStore.workspaceMembers?.map((m) => m.member) ?? undefined}
members={workspaceMembers?.map((m) => m.member) ?? undefined}
projects={workspaceSlug ? projectStore.projects[workspaceSlug.toString()] : undefined}
/>
</FiltersDropdown>

View File

@ -31,6 +31,8 @@ export const ModuleIssuesHeader: React.FC = observer(() => {
module: moduleStore,
moduleFilter: moduleFilterStore,
project: projectStore,
projectState: projectStateStore,
commandPalette: commandPaletteStore,
} = useMobxStore();
const activeLayout = issueFilterStore.userDisplayFilters.layout;
const { currentProjectDetails } = projectStore;
@ -146,6 +148,7 @@ export const ModuleIssuesHeader: React.FC = observer(() => {
}
className="ml-1.5 flex-shrink-0"
width="auto"
placement="bottom-start"
>
{modulesList?.map((module) => (
<CustomMenu.MenuItem
@ -175,7 +178,7 @@ export const ModuleIssuesHeader: React.FC = observer(() => {
}
labels={projectStore.labels?.[projectId?.toString() ?? ""] ?? undefined}
members={projectStore.members?.[projectId?.toString() ?? ""]?.map((m) => m.member)}
states={projectStore.states?.[projectId?.toString() ?? ""] ?? undefined}
states={projectStateStore.states?.[projectId?.toString() ?? ""] ?? undefined}
/>
</FiltersDropdown>
<FiltersDropdown title="Display" placement="bottom-end">
@ -192,17 +195,8 @@ export const ModuleIssuesHeader: React.FC = observer(() => {
<Button onClick={() => setAnalyticsModal(true)} variant="neutral-primary" size="sm">
Analytics
</Button>
<Button
onClick={() => {
const e = new KeyboardEvent("keydown", {
key: "c",
});
document.dispatchEvent(e);
}}
size="sm"
prependIcon={<Plus />}
>
Add issue
<Button onClick={() => commandPaletteStore.toggleCreateIssueModal(true)} size="sm" prependIcon={<Plus />}>
Add job
</Button>
<button
type="button"

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