Skip to content

Commit

Permalink
refactor: code and cache, bump version to 0.0.5
Browse files Browse the repository at this point in the history
  • Loading branch information
shaokeyibb committed Aug 6, 2024
1 parent 64132c2 commit deaedbe
Show file tree
Hide file tree
Showing 7 changed files with 71 additions and 75 deletions.
2 changes: 1 addition & 1 deletion frontend/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test environment for Review</title>
<title>offsets-injection-review playground</title>
</head>
<body>
<div id="app"></div>
Expand Down
120 changes: 48 additions & 72 deletions frontend/lib/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,14 @@ const dateTimeFormatter = new Intl.DateTimeFormat(undefined, {
});

let globalInitialized = false;
let apiEndpoint = "/api";

let selectedOffset: HTMLElement | null = null;

let commentsCache: Comment[] | undefined;

let commentsButton = document.querySelector(
"#review-comments-button",
)! as HTMLDivElement;
let commentsPanel = document.querySelector(
"#review-comments-panel",
)! as HTMLDivElement;
let commentsButton: HTMLElement;
let commentsPanel: HTMLElement;

const _registerDialog = ({
id,
Expand All @@ -60,8 +57,10 @@ const _registerDialog = ({
actions?: Map<string, (el: HTMLElement) => void>;
tag?: keyof HTMLElementTagNameMap;
initialize?: (el: HTMLElement) => void;
}) => {
if (parent.querySelector(`#${id}`)) return;
}): HTMLElement => {
let dialog = document.querySelector<HTMLElement>(`#${id}`);
if (dialog) return dialog;

parent.insertAdjacentHTML(
insertPosition,
`
Expand All @@ -70,8 +69,10 @@ const _registerDialog = ({
</${tag}>
`.trim(),
);
const dialog = document.querySelector(`#${id}`)! as HTMLElement;
dialog = document.querySelector(`#${id}`)! as HTMLElement;

initialize(dialog);

const actionElements = dialog.querySelectorAll(`[data-action]`);
for (const actionEl of actionElements) {
actionEl.addEventListener("click", (e) => {
Expand All @@ -81,16 +82,16 @@ const _registerDialog = ({
actions.get(action)?.(el);
});
}

return dialog;
};

const _selectOffsetParagraph = ({
el,
focusReply = false,
apiEndpoint,
}: {
el: HTMLElement;
focusReply?: boolean;
apiEndpoint: string;
}) => {
if (selectedOffset !== el) {
selectedOffset?.classList.remove("review_selected");
Expand All @@ -103,9 +104,7 @@ const _selectOffsetParagraph = ({
) {
selectedOffset.classList.remove("review_focused");
selectedOffset.classList.add("review_selected");
_openCommentsPanel({
apiEndpoint,
});
_openCommentsPanel();
}
};

Expand All @@ -114,13 +113,7 @@ const _unselectOffsetParagraph = () => {
selectedOffset = null;
};

const _openContextMenu = ({
el,
apiEndpoint,
}: {
el: HTMLElement;
apiEndpoint: string;
}) => {
const _openContextMenu = ({ el }: { el: HTMLElement }) => {
_registerDialog({
id: "review-context-menu",
content: `
Expand All @@ -138,7 +131,6 @@ const _openContextMenu = ({
_selectOffsetParagraph({
el,
focusReply: true,
apiEndpoint,
});
},
],
Expand All @@ -159,13 +151,8 @@ const _closeContextMenu = () => {
contextMenu.remove();
};

const _openCommentsPanel = async ({
apiEndpoint,
}: {
focusReply?: boolean;
apiEndpoint: string;
}) => {
const comments = [...(await _fetchComments({ apiEndpoint }))];
const _openCommentsPanel = async () => {
const comments = [...(await _fetchComments())];

const selected = selectedOffset;

Expand All @@ -191,7 +178,7 @@ const _openCommentsPanel = async ({
});
}

_renderComments(comments, apiEndpoint);
_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}"]`,
);
Expand All @@ -212,12 +199,10 @@ const _closeCommentsPanel = () => {
};

const _submitComment = async ({
apiEndpoint,
offsets,
username,
content,
}: {
apiEndpoint: string;
offsets: [number, number];
username: string;
content: string;
Expand All @@ -227,8 +212,6 @@ const _submitComment = async ({
throw new Error("Commit hash not found");
}

apiEndpoint = apiEndpoint.endsWith("/") ? apiEndpoint : apiEndpoint + "/";

const comment = {
offset: {
start: offsets[0],
Expand Down Expand Up @@ -265,15 +248,14 @@ const _submitComment = async ({
});
}

_updateAvailableComments({ apiEndpoint });
_updateAvailableComments();
};

const _fetchComments = async ({ apiEndpoint }: { apiEndpoint: string }) => {
const _fetchComments = async () => {
if (commentsCache) {
return commentsCache;
}

apiEndpoint = apiEndpoint.endsWith("/") ? apiEndpoint : apiEndpoint + "/";
const res = await fetch(
`${apiEndpoint}comment/${encodeURIComponent(new URL(window.location.href).pathname)}`,
);
Expand All @@ -287,7 +269,7 @@ const _fetchComments = async ({ apiEndpoint }: { apiEndpoint: string }) => {
return comments;
};

const _renderComments = (comments: Comment[], apiEndpoint: string) => {
const _renderComments = (comments: Comment[]) => {
const commentsEl = commentsPanel.querySelector(
".panel_main",
)! as HTMLDivElement;
Expand Down Expand Up @@ -383,7 +365,6 @@ const _renderComments = (comments: Comment[], apiEndpoint: string) => {
notification.textContent = "";

_submitComment({
apiEndpoint,
offsets: [
parseInt(selectedOffset!.dataset.originalDocumentStart!),
parseInt(selectedOffset!.dataset.originalDocumentEnd!),
Expand All @@ -397,9 +378,7 @@ const _renderComments = (comments: Comment[], apiEndpoint: string) => {
notification.textContent = "";
submitButton.disabled = false;

_openCommentsPanel({
apiEndpoint,
});
_openCommentsPanel();
})
.catch((e) => {
console.error(e);
Expand Down Expand Up @@ -465,18 +444,14 @@ const _renderComments = (comments: Comment[], apiEndpoint: string) => {
commentsEl.appendChild(fragment);
};

const _updateAvailableComments = async ({
apiEndpoint,
}: {
apiEndpoint: string;
}) => {
const _updateAvailableComments = async () => {
const offsets = Array.from(
document.querySelectorAll<HTMLElement>(
".review_enabled[data-original-document-start][data-original-document-end]",
),
);

await _fetchComments({ apiEndpoint });
await _fetchComments();

for (let offset of offsets) {
offset.classList.remove("review_has_comments");
Expand All @@ -493,65 +468,71 @@ const _updateAvailableComments = async ({
}
};

export const __VERSION__: string = __LIB_VERSION__;

export function setupReview(
el: Element,
{ apiEndpoint = "/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]",
),
);

if (!offsets) return;
if (!offsets) {
console.warn(
"offsets-injection-review not found any offsets to inject, quitting...",
);
return;
}

for (let offset of offsets) {
offset.classList.add("review_enabled");
offset.addEventListener("click", (e) => {
e.stopPropagation(); // Prevent bubble so that the document click event won't be triggered
_selectOffsetParagraph({
el: e.currentTarget as HTMLElement,
apiEndpoint,
});
});
offset.addEventListener("mouseenter", (e) => {
_openContextMenu({
el: e.currentTarget as HTMLElement,
apiEndpoint,
});
});
offset.addEventListener("mouseleave", () => {
_closeContextMenu();
});
}

_updateAvailableComments({ apiEndpoint });
// clear cache
commentsCache = undefined;

if (globalInitialized) return;
_updateAvailableComments();

if (globalInitialized) {
_closeCommentsPanel();
console.log("offsets-injection-review has been successfully reset.");
return;
}

document.addEventListener("click", () => {
_unselectOffsetParagraph();
});

_registerDialog({
commentsButton = _registerDialog({
id: "review-comments-button",
content: `
<button data-action="open">
<iconify-icon class="iconify-inline" icon="material-symbols:comment-outline-rounded"></iconify-icon>
</button>
`,
actions: new Map([
[
"open",
() =>
_openCommentsPanel({
apiEndpoint,
}),
],
]),
actions: new Map([["open", () => _openCommentsPanel()]]),
});

_registerDialog({
commentsPanel = _registerDialog({
id: "review-comments-panel",
content: `
<div class="panel_header">
Expand All @@ -566,15 +547,10 @@ export function setupReview(
actions: new Map([["close", () => _closeCommentsPanel()]]),
});

commentsButton = document.querySelector(
"#review-comments-button",
)! as HTMLDivElement;
commentsPanel = document.querySelector(
"#review-comments-panel",
)! as HTMLDivElement;

// initialize comments panel position
_closeCommentsPanel();

console.log("offsets-injection-review has been successfully installed.");

globalInitialized = true;
}
2 changes: 2 additions & 0 deletions frontend/lib/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ iconify-icon.iconify-inline {

transition: transform 0.3s;

z-index: 100;

&:hover {
transform: translateX(-20%);
}
Expand Down
6 changes: 4 additions & 2 deletions 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.1",
"version": "0.0.5",
"license": "Apache-2.0",
"type": "module",
"files": [
Expand All @@ -19,9 +19,11 @@
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"fmt": "prettier --write ."
"fmt": "prettier --write .",
"prepublishOnly": "yarn build"
},
"devDependencies": {
"@types/node": "^22.1.0",
"autoprefixer": "^10.4.19",
"postcss": "^8.4.40",
"postcss-preset-env": "^10.0.0",
Expand Down
1 change: 1 addition & 0 deletions frontend/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/// <reference types="vite/client" />
declare const __LIB_VERSION__: string;
3 changes: 3 additions & 0 deletions frontend/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,7 @@ export default defineConfig({
},
},
},
define: {
__LIB_VERSION__: JSON.stringify(process.env.npm_package_version),
},
});
12 changes: 12 additions & 0 deletions frontend/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -511,6 +511,13 @@
resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.5.tgz#a6ce3e556e00fd9895dd872dd172ad0d4bd687f4"
integrity sha512-/kYRxGDLWzHOB7q+wtSUQlFrtcdUccpfy+X+9iMBpHK8QLLhx2wIPYuS5DYtR9Wa/YlZAbIovy7qVdB1Aq6Lyw==

"@types/node@^22.1.0":
version "22.1.0"
resolved "https://registry.yarnpkg.com/@types/node/-/node-22.1.0.tgz#6d6adc648b5e03f0e83c78dc788c2b037d0ad94b"
integrity sha512-AOmuRF0R2/5j1knA3c6G3HOk523Ga+l+ZXltX8SF1+5oqcXijjfTd8fY3XRZqSihEu9XhtQnKYLmkFaoxgsJHw==
dependencies:
undici-types "~6.13.0"

autoprefixer@^10.4.19:
version "10.4.19"
resolved "https://registry.yarnpkg.com/autoprefixer/-/autoprefixer-10.4.19.tgz#ad25a856e82ee9d7898c59583c1afeb3fa65f89f"
Expand Down Expand Up @@ -964,6 +971,11 @@ typescript@^5.4.5:
resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.5.4.tgz#d9852d6c82bad2d2eda4fd74a5762a8f5909e9ba"
integrity sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==

undici-types@~6.13.0:
version "6.13.0"
resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-6.13.0.tgz#e3e79220ab8c81ed1496b5812471afd7cf075ea5"
integrity sha512-xtFJHudx8S2DSoujjMd1WeWvn7KKWFRESZTMeL1RptAYERu29D6jphMjjY+vn96jvN3kVPDNxU/E13VTaXj6jg==

update-browserslist-db@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.1.0.tgz#7ca61c0d8650766090728046e416a8cde682859e"
Expand Down

0 comments on commit deaedbe

Please sign in to comment.