Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add lexical rich component in mr comment #620

Merged
merged 4 commits into from
Sep 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion ceres/src/api_service/mono_api_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,6 @@ impl ApiHandler for MonoApiService {
Ok(())
}


fn strip_relative(&self, path: &Path) -> Result<PathBuf, GitError> {
Ok(path.to_path_buf())
}
Expand Down Expand Up @@ -326,6 +325,23 @@ impl MonoApiService {
Ok(())
}

pub async fn comment(&self, mr_link: &str, comment: String) -> Result<(), MegaError> {
let storage = self.context.services.mono_storage.clone();
if let Some(model) = storage.get_mr(mr_link).await.unwrap() {
storage
.add_mr_conversation(&model.mr_link, 0, ConvType::Comment, Some(comment))
.await
.unwrap();
}
Ok(())
}

pub async fn delete_comment(&self, id: i64) -> Result<(), MegaError> {
let storage = self.context.services.mono_storage.clone();
storage.remove_mr_conversation(id).await.unwrap();
Ok(())
}

async fn update_parent_tree(
&self,
mut path: PathBuf,
Expand Down
2 changes: 2 additions & 0 deletions ceres/src/model/mr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ pub struct MRDetail {

#[derive(Serialize, Deserialize)]
pub struct MRConversion {
pub id: i64,
pub user_id: i64,
pub conv_type: String,
pub comment: Option<String>,
Expand All @@ -62,6 +63,7 @@ impl From<mega_mr::Model> for MRDetail {
impl From<mega_mr_conv::Model> for MRConversion {
fn from(value: mega_mr_conv::Model) -> Self {
Self {
id: value.id,
user_id: value.user_id,
conv_type: value.conv_type.to_string(),
comment: value.comment,
Expand Down
2 changes: 1 addition & 1 deletion docker/mono-pg-dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,6 @@ EXPOSE 5432

# Add the database initialization script to the container
# When the container starts, PostgreSQL will automatically execute all .sql files in the docker-entrypoint-initdb.d/ directory
COPY ./sql/postgres/pg_20240912__init.sql /docker-entrypoint-initdb.d/
COPY ./sql/postgres/pg_20240923__init.sql /docker-entrypoint-initdb.d/

CMD ["postgres"]
16 changes: 13 additions & 3 deletions jupiter/src/storage/mono_storage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@ use sea_orm::{

use callisto::db_enums::{ConvType, MergeStatus};
use callisto::{
mega_blob, mega_commit, mega_mr, mega_mr_conv, mega_refs, mega_tag, mega_tree,
raw_blob,
mega_blob, mega_commit, mega_mr, mega_mr_conv, mega_refs, mega_tag, mega_tree, raw_blob,
};
use common::errors::MegaError;
use common::utils::generate_id;
Expand Down Expand Up @@ -103,7 +102,10 @@ impl MonoStorage {
Ok(())
}

pub async fn get_open_mr_by_path(&self, path: &str) -> Result<Option<mega_mr::Model>, MegaError> {
pub async fn get_open_mr_by_path(
&self,
path: &str,
) -> Result<Option<mega_mr::Model>, MegaError> {
let model = mega_mr::Entity::find()
.filter(mega_mr::Column::Path.eq(path))
.filter(mega_mr::Column::Status.eq(MergeStatus::Open))
Expand Down Expand Up @@ -173,6 +175,14 @@ impl MonoStorage {
Ok(model?)
}

pub async fn remove_mr_conversation(&self, id: i64) -> Result<(), MegaError> {
mega_mr_conv::Entity::delete_by_id(id)
.exec(self.get_connection())
.await
.unwrap();
Ok(())
}

pub async fn add_mr_conversation(
&self,
mr_link: &str,
Expand Down
31 changes: 31 additions & 0 deletions mono/src/api/mr_router.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ use axum::{
Json, Router,
};

use bytes::Bytes;

use ceres::model::mr::{MRDetail, MrInfoItem};
use common::model::CommonResult;
use taurus::event::api_request::{ApiRequestEvent, ApiType};
Expand All @@ -19,6 +21,8 @@ pub fn routers() -> Router<MonoApiServiceState> {
.route("/mr/:mr_link/detail", get(mr_detail))
.route("/mr/:mr_link/merge", post(merge))
.route("/mr/:mr_link/files", get(get_mr_files))
.route("/mr/:mr_link/comment", post(save_comment))
.route("/mr/comment/:conv_id/delete", post(delete_comment))
}

async fn merge(
Expand Down Expand Up @@ -75,3 +79,30 @@ async fn get_mr_files(
};
Ok(Json(res))
}

async fn save_comment(
Path(mr_link): Path<String>,
state: State<MonoApiServiceState>,
body: Bytes,
) -> Result<Json<CommonResult<String>>, ApiError> {
let json_string =
String::from_utf8(body.to_vec()).unwrap_or_else(|_| "Invalid UTF-8".to_string());
let res = state.monorepo().comment(&mr_link, json_string).await;
let res = match res {
Ok(_) => CommonResult::success(None),
Err(err) => CommonResult::failed(&err.to_string()),
};
Ok(Json(res))
}

async fn delete_comment(
Path(conv_id): Path<i64>,
state: State<MonoApiServiceState>,
) -> Result<Json<CommonResult<String>>, ApiError> {
let res = state.monorepo().delete_comment(conv_id).await;
let res = match res {
Ok(_) => CommonResult::success(None),
Err(err) => CommonResult::failed(&err.to_string()),
};
Ok(Json(res))
}
14 changes: 7 additions & 7 deletions moon/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,21 +9,21 @@
"lint": "next lint"
},
"dependencies": {
"@ant-design/icons": "^5.4.0",
"@ant-design/icons": "^5.5.1",
"@ant-design/nextjs-registry": "^1.0.1",
"@headlessui/react": "^2.1.6",
"@headlessui/react": "^2.1.8",
"@headlessui/tailwindcss": "^0.2.1",
"@heroicons/react": "^2.1.5",
"@lexical/react": "^0.17.1",
"lexical": "^0.17.1",
"@tailwindcss/forms": "^0.5.9",
"clsx": "^2.1.1",
"copy-to-clipboard": "^3.3.3",
"date-fns": "^3.6.0",
"framer-motion": "^11.5.3",
"github-markdown-css": "^5.6.1",
"date-fns": "^4.1.0",
"framer-motion": "^11.7.0",
"github-markdown-css": "^5.7.0",
"highlight.js": "^11.10.0",
"lexical": "^0.17.1",
"next": "^14.2.9",
"next": "^14.2.13",
"prism-react-renderer": "^2.4.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
Expand Down
82 changes: 53 additions & 29 deletions moon/src/app/(dashboard)/mr/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,48 +1,55 @@
'use client'
import { useEffect, useState } from "react";
import { Card, Button, List, Tabs, TabsProps, Space, Timeline } from 'antd/lib';
import { useRouter } from 'next/navigation';
import { Card, Button, List, Tabs, TabsProps, Space, Timeline, Flex } from 'antd/lib';
import { CommentOutlined, MergeOutlined } from '@ant-design/icons';
import { formatDistance, fromUnixTime } from 'date-fns';
import RichEditor from "@/components/rich-editor/RichEditor";
import MRComment from "@/components/MRComment";

interface MRDetail {
status: string,
conversions: Conversation[],
title: string,
}
interface Conversation {
id: number,
user_id: number,
conv_type: String,
comment: String,
conv_type: string,
comment: string,
created_at: number,
}

export default function MRDetailPage({ params }: { params: { id: string } }) {
const [editorState, setEditorState] = useState("");
const [mrDetail, setMrDetail] = useState<MRDetail>(
{
status: "",
conversions: [],
status: "",
conversions: [],
title: "",
}
}
);
const router = useRouter();
const [filedata, setFileData] = useState([]);
const [loadings, setLoadings] = useState<boolean[]>([]);

const fetchDetail = async () => {
const detail = await fetch(`/api/mr/${params.id}/detail`);
const detail_json = await detail.json();
setMrDetail(detail_json.data.data);
};

const fetchFileList = async () => {
set_to_loading(2)
try {
const res = await fetch(`/api/mr/${params.id}/files`);
const result = await res.json();
setFileData(result.data.data);
} finally {
cancel_loading(2)
}
};

useEffect(() => {
const fetchFileList = async () => {
set_to_loading(2)
try {
const detail = await fetch(`/api/mr/${params.id}/detail`);
const detail_json = await detail.json();
setMrDetail(detail_json.data.data);
const res = await fetch(`/api/mr/${params.id}/files`);
const result = await res.json();
setFileData(result.data.data);
} finally {
cancel_loading(2)
}
};
fetchDetail()
fetchFileList();
}, [params.id]);

Expand All @@ -62,21 +69,34 @@ export default function MRDetailPage({ params }: { params: { id: string } }) {
});
}

const approve_mr = async (index: number, mr_link: string) => {
set_to_loading(index);
const res = await fetch(`/api/mr/${mr_link}/merge`, {
async function approve_mr() {
set_to_loading(1);
const res = await fetch(`/api/mr/${params.id}/merge`, {
method: 'POST',
});
if (res) {
cancel_loading(index);
cancel_loading(1);
}
};

async function save_comment(comment) {
set_to_loading(3);
const res = await fetch(`/api/mr/${params.id}/comment`, {
method: 'POST',
body: comment,
});
if (res) {
setEditorState("");
fetchDetail();
cancel_loading(3);
}
}

let conv_items = mrDetail?.conversions.map(conv => {
let icon;
let children;
switch (conv.conv_type) {
case "Comment": icon = <CommentOutlined />; children = conv.comment; break;
case "Comment": icon = <CommentOutlined />; children = <MRComment conv={conv} fetchDetail={fetchDetail} />; break
case "Merged": icon = <MergeOutlined />; children = "Merged via the queue into main " + formatDistance(fromUnixTime(conv.created_at), new Date(), { addSuffix: true }); break;
// default: icon = <CommentOutlined />; children = conv.comment;
};
Expand All @@ -94,8 +114,13 @@ export default function MRDetailPage({ params }: { params: { id: string } }) {
key: '1',
label: 'Conversation',
children:
<Space style={{ width: '100%' }}>
<Space direction="vertical" style={{ width: '100%' }}>
<Timeline items={conv_items} />
<h1>Add a comment</h1>
<RichEditor setEditorState={setEditorState} />
<Flex justify={"flex-end"}>
<Button loading={loadings[3]} onClick={() => save_comment(editorState)}>Comment</Button>
</Flex>
</Space>
},
{
Expand All @@ -122,9 +147,8 @@ export default function MRDetailPage({ params }: { params: { id: string } }) {
<Card title={mrDetail.title + " #" + params.id}>
{mrDetail && mrDetail.status === "open" &&
<Button
type="primary"
loading={loadings[1]}
onClick={() => approve_mr(1, params.id)}
onClick={() => approve_mr()}
>
Merge MR
</Button>
Expand Down
24 changes: 24 additions & 0 deletions moon/src/app/api/mr/[id]/comment/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { verifySession } from "@/app/lib/dal";

export async function POST(request: Request, { params }: { params: { id: string } }) {
const session = await verifySession()
const jsonData = await request.json();

// Check if the user is authenticated
if (!session) {
// User is not authenticated
return new Response(null, { status: 401 })
}

const endpoint = process.env.MEGA_INTERNAL_HOST;
const res = await fetch(`${endpoint}/api/v1/mr/${params.id}/comment`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(jsonData),
})
const data = await res.json()

return Response.json({ data })
}
19 changes: 19 additions & 0 deletions moon/src/app/api/mr/comment/[id]/delete/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { verifySession } from "@/app/lib/dal";

export async function POST(request: Request, { params }: { params: { id: string } }) {
const session = await verifySession()

// Check if the user is authenticated
if (!session) {
// User is not authenticated
return new Response(null, { status: 401 })
}

const endpoint = process.env.MEGA_INTERNAL_HOST;
const res = await fetch(`${endpoint}/api/v1/mr/comment/${params.id}/delete`, {
method: 'POST',
})
const data = await res.json()

return Response.json({ data })
}
1 change: 1 addition & 0 deletions moon/src/app/host/route.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export const revalidate = 0

export async function GET() {
const endpoint = process.env.MEGA_HOST;
Expand Down
Loading
Loading