Skip to content

Commit

Permalink
feat: pretty error message, bump version to 0.0.7
Browse files Browse the repository at this point in the history
  • Loading branch information
shaokeyibb committed Aug 7, 2024
1 parent e115e98 commit bae4755
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 28 deletions.
69 changes: 42 additions & 27 deletions frontend/lib/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ const groupBy = function <K extends string, T>(arr: T[], func: (el: T) => K) {
},
{} as {
[key: string]: T[];
},
}
);
};

Expand Down Expand Up @@ -67,7 +67,7 @@ const _registerDialog = ({
<${tag} id="${id}">
${content.trim()}
</${tag}>
`.trim(),
`.trim()
);
dialog = document.querySelector(`#${id}`)! as HTMLElement;

Expand Down Expand Up @@ -161,7 +161,7 @@ const _openCommentsPanel = async () => {
comments.find(
(it) =>
it.offset.start === parseInt(selected.dataset.originalDocumentStart!) &&
it.offset.end === parseInt(selected.dataset.originalDocumentEnd!),
it.offset.end === parseInt(selected.dataset.originalDocumentEnd!)
) === undefined
) {
comments.push({
Expand All @@ -180,7 +180,7 @@ const _openCommentsPanel = async () => {

_renderComments(comments);
let selectedCommentsGroup = document.querySelector(
`#review-comments-panel .comments_group[data-original-document-start="${selectedOffset?.dataset.originalDocumentStart}"][data-original-document-end="${selectedOffset?.dataset.originalDocumentEnd}"]`,
`#review-comments-panel .comments_group[data-original-document-start="${selectedOffset?.dataset.originalDocumentStart}"][data-original-document-end="${selectedOffset?.dataset.originalDocumentEnd}"]`
);

selectedCommentsGroup?.classList.add("review_selected");
Expand All @@ -207,9 +207,9 @@ const _submitComment = async ({
username: string;
content: string;
}) => {
const commitHash = globalThis.sessionStorage.getItem("commitHash");
const commitHash = sessionStorage.getItem("commitHash");
if (!commitHash) {
throw new Error("Commit hash not found");
throw new Error("找不到 Commit hash,请联系站点管理员");
}

const comment = {
Expand All @@ -234,7 +234,7 @@ const _submitComment = async ({
...comment,
commit_hash: commitHash,
}),
},
}
);
if (!res.ok) {
throw res;
Expand All @@ -257,7 +257,7 @@ const _fetchComments = async () => {
}

const res = await fetch(
`${apiEndpoint}comment/${encodeURIComponent(new URL(window.location.href).pathname)}`,
`${apiEndpoint}comment/${encodeURIComponent(new URL(window.location.href).pathname)}`
);
if (!res.ok) {
throw res;
Expand All @@ -271,17 +271,17 @@ const _fetchComments = async () => {

const _renderComments = (comments: Comment[]) => {
const commentsEl = commentsPanel.querySelector(
".panel_main",
".panel_main"
)! as HTMLDivElement;

const fragment = document.createDocumentFragment();

const group = groupBy(
comments,
(it) => `${it.offset.start}-${it.offset.end}`,
(it) => `${it.offset.start}-${it.offset.end}`
);
for (const key of Object.keys(group).sort(
(a, b) => parseInt(a.split("-")[0]) - parseInt(b.split("-")[0]),
(a, b) => parseInt(a.split("-")[0]) - parseInt(b.split("-")[0])
)) {
const container = document.createElement("div");
container.classList.add("comments_group");
Expand All @@ -291,7 +291,7 @@ const _renderComments = (comments: Comment[]) => {
container.dataset.originalDocumentEnd = offsets[1];

const paragraph = document.querySelector<HTMLDivElement>(
`.review_enabled[data-original-document-start="${container.dataset.originalDocumentStart}"][data-original-document-end="${container.dataset.originalDocumentEnd}"]`,
`.review_enabled[data-original-document-start="${container.dataset.originalDocumentStart}"][data-original-document-end="${container.dataset.originalDocumentEnd}"]`
);
const content = paragraph?.textContent ?? "";

Expand Down Expand Up @@ -327,18 +327,18 @@ const _renderComments = (comments: Comment[]) => {
const target = e.target as HTMLButtonElement;

const input = container.querySelector(
".comment_reply_panel input",
".comment_reply_panel input"
) as HTMLInputElement;
const textarea = container.querySelector(
".comment_reply_panel textarea",
".comment_reply_panel textarea"
) as HTMLTextAreaElement;

const notification = container.querySelector(
".comment_reply_notification",
".comment_reply_notification"
) as HTMLSpanElement;

const submitButton = container.querySelector(
".comment_reply_item[data-action='submit']",
".comment_reply_item[data-action='submit']"
) as HTMLButtonElement;

switch (target?.dataset.action) {
Expand Down Expand Up @@ -380,9 +380,24 @@ const _renderComments = (comments: Comment[]) => {

_openCommentsPanel();
})
.catch((e) => {
.catch(async (e) => {
console.error(e);
notification.textContent = "提交失败,请稍后再试";

if (e instanceof Error) {
notification.textContent = e.message;
} else if (e instanceof Response) {
if (e.headers.get("content-type")?.includes("application/json") === true) {
const json = (await e.json()) as {
status: number;
error: string;
};
notification.textContent = json.error;
} else {
notification.textContent = `未知接口错误:${e.status}(${e.statusText})`;
}
} else {
notification.textContent = "提交失败,请稍后再试";
}

textarea.disabled = false;
submitButton.disabled = false;
Expand Down Expand Up @@ -415,7 +430,7 @@ const _renderComments = (comments: Comment[]) => {

const commentsGroup = group[key].sort(
(a, b) =>
new Date(a.created_time).getTime() - new Date(b.created_time).getTime(),
new Date(a.created_time).getTime() - new Date(b.created_time).getTime()
);
const main = container.querySelector(".comments_group_main")!;

Expand Down Expand Up @@ -447,8 +462,8 @@ const _renderComments = (comments: Comment[]) => {
const _updateAvailableComments = async () => {
const offsets = Array.from(
document.querySelectorAll<HTMLElement>(
".review_enabled[data-original-document-start][data-original-document-end]",
),
".review_enabled[data-original-document-start][data-original-document-end]"
)
);

await _fetchComments();
Expand All @@ -460,7 +475,7 @@ const _updateAvailableComments = async () => {
(it) =>
it.offset.start ===
parseInt(offset!.dataset.originalDocumentStart!) &&
it.offset.end === parseInt(offset!.dataset.originalDocumentEnd!),
it.offset.end === parseInt(offset!.dataset.originalDocumentEnd!)
)
) {
offset.classList.add("review_has_comments");
Expand All @@ -472,19 +487,19 @@ export const __VERSION__: string = __LIB_VERSION__;

export function setupReview(
el: Element,
{ apiEndpoint: endpoint = "/api" }: { apiEndpoint?: string } = {},
{ apiEndpoint: endpoint = "/api" }: { apiEndpoint?: string } = {}
) {
apiEndpoint = endpoint.endsWith("/") ? endpoint : endpoint + "/";

const offsets = Array.from(
el.querySelectorAll<HTMLElement>(
"[data-original-document-start][data-original-document-end]",
),
"[data-original-document-start][data-original-document-end]"
)
);

if (!offsets) {
console.warn(
"offsets-injection-review not found any offsets to inject, quitting...",
"offsets-injection-review not found any offsets to inject, quitting..."
);
return;
}
Expand Down Expand Up @@ -551,7 +566,7 @@ export function setupReview(
_closeCommentsPanel();

console.log(
`offsets-injection-review version ${__VERSION__} has been successfully installed.`,
`offsets-injection-review version ${__VERSION__} has been successfully installed.`
);

globalInitialized = true;
Expand Down
2 changes: 1 addition & 1 deletion frontend/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "offsets-injection-review",
"private": false,
"version": "0.0.6",
"version": "0.0.7",
"license": "Apache-2.0",
"type": "module",
"files": [
Expand Down

0 comments on commit bae4755

Please sign in to comment.