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 1 commit
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
58 changes: 56 additions & 2 deletions frontend/lib/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,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 +188,7 @@ const _registerDialog = ({
return dialog;
};

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

Expand Down Expand Up @@ -611,6 +646,7 @@ 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="copy_permalink">复制链接地址</button>
Enter-tainer marked this conversation as resolved.
Show resolved Hide resolved
<button class="comment_actions_item" data-action="modify">修改</button>
<button class="comment_actions_item" data-action="delete">删除</button>
</div>
Expand Down Expand Up @@ -733,6 +769,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 +1138,8 @@ export function setupReview(
// initialize comments panel position
_closeCommentsPanel();

_handleAnchor();

console.log(
`oiwiki-feedback-sys-frontend version ${__VERSION__} has been successfully installed.`,
);
Expand Down
20 changes: 20 additions & 0 deletions 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 @@ -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