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 e115e98
Show file tree
Hide file tree
Showing 7 changed files with 75 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
122 changes: 50 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;

_updateAvailableComments();

if (globalInitialized) return;
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,12 @@ 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 version ${__VERSION__} has been successfully installed.`,
);

globalInitialized = true;
}
4 changes: 4 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 Expand Up @@ -101,6 +103,8 @@ iconify-icon.iconify-inline {

transition: transform 0.3s;

z-index: 100;

@media (--mobile) {
width: 100vw;
height: 100%;
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.6",
"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),
},
});
Loading

0 comments on commit e115e98

Please sign in to comment.