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

feat: anchor comment #89

Merged
merged 2 commits into from
Sep 9, 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
4 changes: 2 additions & 2 deletions cloudflare-workers/src/administration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ export async function modifyComments(env: Env, path: string, diff: ModifiedComme
await updateCommentOffsets(env, path, calcOffsetModification(offsets, diff));
}

export async function sendCommentUpdateToTelegram(env: Env, req: PostComment, username: string) {
export async function sendCommentUpdateToTelegram(env: Env, req: PostComment, username: string, commentId: number) {
let title = req.path;
let offset = `${req.offset.start}-${req.offset.end}`;

Expand All @@ -82,7 +82,7 @@ export async function sendCommentUpdateToTelegram(env: Env, req: PostComment, us

let message =
`💬 New paragraph comment on ` +
`[${escapeTelegramMarkdown(`${title}`)}](${escapeTelegramMarkdown(`https://oi-wiki.org${req.path}`)})\n` +
`[${escapeTelegramMarkdown(`${title}`)}](${escapeTelegramMarkdown(`https://oi-wiki.org${req.path}#comment-${commentId}`)})\n` +
`> ${escapeTelegramMarkdown(offset)}\n` +
`by ${escapeTelegramMarkdown(username)}\n\n`;

Expand Down
9 changes: 6 additions & 3 deletions cloudflare-workers/src/db.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Commenter, GetComment, GetCommentRespBody, Offset, PostComment } from './types';

export async function postComment(env: Env, req: PostComment) {
export async function postComment(env: Env, req: PostComment): Promise<number> {
const db = env.DB;

// 插入页面(如果不存在)并返回 ID
Expand Down Expand Up @@ -33,7 +33,7 @@ export async function postComment(env: Env, req: PostComment) {
const offsetId = offsetResult.id;

// 插入评论
await db
const commentResult = (await db
.prepare(
`
INSERT INTO comments (offset_id, commenter_id, comment, created_time)
Expand All @@ -43,10 +43,13 @@ export async function postComment(env: Env, req: PostComment) {
?,
?
)
RETURNING id
`,
)
.bind(offsetId, req.commenter.oauth_provider, req.commenter.oauth_user_id, req.comment, new Date().toISOString())
.run();
.first())!;

return commentResult.id as number;
}

export async function deleteComment(env: Env, id: number) {
Expand Down
4 changes: 2 additions & 2 deletions cloudflare-workers/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,9 @@ router.post('/comment/:path', async (req, env, ctx) => {
comment: body.comment,
};

await postComment(env, data);
const commentId = await postComment(env, data);

ctx.waitUntil(sendCommentUpdateToTelegram(env, data, token.name));
ctx.waitUntil(sendCommentUpdateToTelegram(env, data, token.name, commentId));

const cache = caches.default;
ctx.waitUntil(purgeCommentCache(env, cache, new URL(req.url).origin, params.path));
Expand Down
70 changes: 63 additions & 7 deletions frontend/lib/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ import iconAddComment from "iconify/add-comment-outline-rounded";
import iconComment from "iconify/comment-outline-rounded";
import iconClose from "iconify/close";
import iconDefaultAvatar from "iconify/account-circle";
import iconShare from "iconify/share";
import iconEdit from "iconify/edit";
import iconDelete from "iconify/delete";

const groupBy = function <K extends string, T>(arr: T[], func: (el: T) => K) {
return arr.reduce(
Expand Down Expand Up @@ -99,6 +102,41 @@ const _decodeJWT = () => {
return JSON.parse(payload) as JWTPayload;
};

const _handleAnchor = async () => {
const url = new URL(window.location.href);
const anchor = url.hash;
if (!anchor) return;

const rawCommentId = /#comment-(\d+)/.exec(anchor)?.[1];
if (!rawCommentId) return;
const commentId = parseInt(rawCommentId);

await _fetchComments();
const comment = commentsCache?.find((it) => it.id === commentId);
if (!comment) return;

const offsets = [comment.offset.start, comment.offset.end];
const paragraph = document.querySelector<HTMLDivElement>(
`[data-review-enabled][data-original-document-start="${offsets[0]}"][data-original-document-end="${offsets[1]}"]`,
);
if (!paragraph) return;

await _selectOffsetParagraph({
el: paragraph,
focusReply: true,
});

const commentEl = document.querySelector<HTMLDivElement>(
`.comment[data-id="${commentId}"]`,
);

commentEl?.classList.add("comment_highlighting");
commentEl?.scrollIntoView({
behavior: "smooth",
block: "center",
});
};

const _logout = () => {
document.cookie =
"oauth_token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT; secure";
Expand Down Expand Up @@ -153,7 +191,7 @@ const _registerDialog = ({
return dialog;
};

const _selectOffsetParagraph = ({
const _selectOffsetParagraph = async ({
el,
focusReply = false,
}: {
Expand All @@ -168,7 +206,7 @@ const _selectOffsetParagraph = ({
if (selectedOffset?.dataset.reviewHasComments || focusReply) {
delete selectedOffset.dataset.reviewFocused;
selectedOffset.dataset.reviewSelected = "true";
_openCommentsPanel();
await _openCommentsPanel();
}
};

Expand Down Expand Up @@ -611,8 +649,9 @@ const _renderComments = (comments: Comment[]) => {
<span class="comment_time comment_created_time">发布于 ${dateTimeFormatter.format(new Date(comment.created_time))}</span>
<span class="comment_time comment_edited_time">最后编辑于 ${comment.last_edited_time ? dateTimeFormatter.format(new Date(comment.last_edited_time)) : ""}</span>
<div class="comment_actions">
<button class="comment_actions_item" data-action="modify">修改</button>
<button class="comment_actions_item" data-action="delete">删除</button>
<button class="comment_actions_item" data-action="copy_permalink" title="分享">${iconShare}</button>
<button class="comment_actions_item" data-action="modify" title="编辑">${iconEdit}</button>
<button class="comment_actions_item" data-action="delete" title="删除">${iconDelete}</button>
</div>
</div>
<div class="comment_main">
Expand Down Expand Up @@ -692,9 +731,8 @@ const _renderComments = (comments: Comment[]) => {
}

for (const actions of container.querySelectorAll(".comment_actions_item")) {
actions.addEventListener("click", (e) => {
if (!(e.target instanceof HTMLButtonElement)) return;
const target = e.target as HTMLButtonElement;
actions.addEventListener("click", () => {
const target = actions as HTMLButtonElement;

const textarea = container.querySelector(
".comment_actions_panel textarea",
Expand Down Expand Up @@ -733,6 +771,22 @@ const _renderComments = (comments: Comment[]) => {
};

switch (target?.dataset.action) {
case "copy_permalink": {
target.dataset.tag = "using";
const commentEl = container.querySelector(
`.comment:has([data-tag="using"][data-action="${target?.dataset.action}"])`,
) as HTMLDivElement;
delete target.dataset.tag;
const id = commentEl?.dataset?.id;
if (id == undefined) return;

const permalink = new URL(window.location.href);
permalink.hash = `#comment-${id}`;
navigator.clipboard.writeText(permalink.toString()).then(() => {
notification.textContent = "已复制评论链接地址";
});
break;
}
case "login": {
if (!githubMeta) {
console.log("githubMeta not ready");
Expand Down Expand Up @@ -1086,6 +1140,8 @@ export function setupReview(
// initialize comments panel position
_closeCommentsPanel();

_handleAnchor();

console.log(
`oiwiki-feedback-sys-frontend version ${__VERSION__} has been successfully installed.`,
);
Expand Down
22 changes: 21 additions & 1 deletion frontend/lib/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,18 @@
[data-review-enabled][data-original-document-start][data-original-document-end];
@custom-media --mobile (width <= 768px);

@keyframes HighlightBackground {
0% {
background-color: rgba(255, 255, 255, 0);
}
50% {
background-color: var(--review-variant-color);
}
100% {
background-color: rgba(255, 255, 255, 0);
}
}

:root {
--review-primary-color: #ffc60a;
--review-secondary-color: #fcdf7e;
Expand Down Expand Up @@ -320,7 +332,7 @@

& .comment_header {
display: flex;
align-items: baseline;
align-items: center;

flex-wrap: wrap;

Expand All @@ -343,6 +355,14 @@
opacity: 0.5;
}

& .comment {
transition: background-color 0.3s;

&.comment_highlighting {
animation: HighlightBackground ease-in-out 1s;
}
}

& .comment_main {
position: relative;

Expand Down