Skip to content

Commit

Permalink
refactor: optimize heat map tracking logic for improved performance
Browse files Browse the repository at this point in the history
  • Loading branch information
rockbenben committed Apr 20, 2023
1 parent e4c7e33 commit 826e393
Show file tree
Hide file tree
Showing 4 changed files with 110 additions and 58 deletions.
29 changes: 29 additions & 0 deletions src/api.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import axios from "axios";

export async function fetchAllCopyCounts() {
try {
const response = await axios.get(
"https://api-count.newzone.top/api/cards/allcounts"
);
const counts = response.data.reduce((acc, item) => {
acc[item.card_id] = item.count;
return acc;
}, {});
return counts;
} catch (error) {
console.error("Error fetching all copy counts:", error);
return {};
}
}
export async function updateCopyCount(cardId) {
try {
const response = await axios.post(
`https://api-count.newzone.top/api/cards/${cardId}/copy`
);
const updatedCount = response.data.copyCount;
return updatedCount;
} catch (error) {
console.error("Error updating copy count:", error);
return null;
}
}
41 changes: 11 additions & 30 deletions src/pages/_components/ShowcaseCard/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useState, useEffect, useCallback } from "react";
import clsx from "clsx";
import axios from "axios";
import Link from "@docusaurus/Link";
import Translate from "@docusaurus/Translate";
import copy from "copy-text-to-clipboard";
Expand All @@ -17,6 +16,7 @@ import { sortBy } from "@site/src/utils/jsUtils";
import Heading from "@theme/Heading";
import Tooltip from "../ShowcaseTooltip";
import styles from "./styles.module.css";
import { updateCopyCount } from "@site/src/api";

import useDocusaurusContext from "@docusaurus/useDocusaurusContext";

Expand Down Expand Up @@ -57,7 +57,7 @@ function ShowcaseCardTag({ tags }: { tags: TagType[] }) {
);
}

function ShowcaseCard({ user, isDescription }) {
function ShowcaseCard({ user, isDescription, copyCount, onCopy }) {
const [paragraphText, setParagraphText] = useState(
isDescription ? user.description : user.desc_cn
);
Expand Down Expand Up @@ -86,40 +86,21 @@ function ShowcaseCard({ user, isDescription }) {

const handleCopyClick = useCallback(async () => {
try {
// Update the copy count on the server
const response = await axios.post(
`https://api-count.newzone.top/api/cards/${user.id}/copy`
);
const updatedCount = response.data.copyCount;
if (user.description) {
copy(user.description);
const updatedCount = await updateCopyCount(user.id);
if (updatedCount !== null) {
if (user.description) {
copy(user.description);
}
setShowCopied(true);
setTimeout(() => setShowCopied(false), 2000);
// Notify parent component to update the copy count
onCopy(user.id, updatedCount);
}
setShowCopied(true);
setTimeout(() => setShowCopied(false), 2000);
// Update the copy count in the local state
setCopyCount(updatedCount);
} catch (error) {
console.error("Error updating copy count:", error);
}
}, [user.id]);

const [copyCount, setCopyCount] = useState(0);

useEffect(() => {
const fetchCopyCount = async () => {
try {
const response = await axios.get(
`https://api-count.newzone.top/api/cards/${user.id}/count`
);
setCopyCount(response.data.count);
} catch (error) {
console.error("Error fetching copy count:", error);
}
};

fetchCopyCount();
}, [user.id]);

return (
<li key={userTitle} className="card shadow--md">
{/* <div className={clsx('card__image', styles.showcaseCardImage)}>
Expand Down
83 changes: 55 additions & 28 deletions src/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import React, { useState, useMemo, useEffect, useCallback } from "react";
import React, {
useState,
useMemo,
useEffect,
useCallback,
} from "react";
import clsx from "clsx";
import ExecutionEnvironment from "@docusaurus/ExecutionEnvironment";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
Expand Down Expand Up @@ -26,8 +31,9 @@ import ShowcaseFilterToggle, {
type Operator,
readOperator,
} from "./_components/ShowcaseFilterToggle";
import ShowcaseCard from "./_components/ShowcaseCard";
import ShowcaseTooltip from "./_components/ShowcaseTooltip";
import ShowcaseCard from "./_components/ShowcaseCard";
import { fetchAllCopyCounts } from "../api";

import styles from "./styles.module.css";

Expand Down Expand Up @@ -161,7 +167,7 @@ function useSiteCountPlural() {

function ShowcaseFilters({ onToggleDescription }) {
const filteredUsers = useFilteredUsers();
const siteCountPlural = useSiteCountPlural();
const siteCountPlural = useCallback(useSiteCountPlural(), []);
const { i18n } = useDocusaurusContext();
const currentLanguage = i18n.currentLocale;
return (
Expand All @@ -176,20 +182,7 @@ function ShowcaseFilters({ onToggleDescription }) {
{currentLanguage === "zh-Hans" && (
<button
onClick={onToggleDescription}
style={{
display: "inline-block",
backgroundColor: "#18816a",
color: "var(--site-color-favorite-background)",
padding: "5px 10px",
borderRadius: "5px",
textDecoration: "none",
fontSize: "8px",
fontWeight: "bold",
marginRight: "8px",
border: "none",
boxShadow: "none",
cursor: "pointer",
}}
className={styles.onToggleButton}
title="更改提示词的显示语言,支持中英文的切换"
>
切换 Prompt 语言
Expand Down Expand Up @@ -238,17 +231,25 @@ function ShowcaseFilters({ onToggleDescription }) {
);
}

const favoriteUsers = sortedUsers.filter((user) =>
user.tags.includes("favorite")
).sort((a, b) => b.weight - a.weight);
const otherUsers = sortedUsers.filter(
(user) => !user.tags.includes("favorite")
).sort((a, b) => b.weight - a.weight);
const [favoriteUsers, otherUsers] = sortedUsers.reduce(
([favorites, others], user) => {
if (user.tags.includes("favorite")) {
favorites.push(user);
} else {
others.push(user);
}
return [favorites, others];
},
[[], []]
);

favoriteUsers.sort((a, b) => b.weight - a.weight);
otherUsers.sort((a, b) => b.weight - a.weight);

function SearchBar() {
const history = useHistory();
const location = useLocation();

const { i18n } = useDocusaurusContext();
const currentLanguage = i18n.currentLocale;
const [value, setValue] = useState<string | null>(null);
Expand Down Expand Up @@ -281,7 +282,9 @@ function SearchBar() {

const handleInput = (e: React.FormEvent<HTMLInputElement>) => {
if (
currentLanguage === "zh-Hans" && (window.innerWidth >= 768 || (typeof chrome !== "undefined" && chrome.extension))
currentLanguage === "zh-Hans" &&
(window.innerWidth >= 768 ||
(typeof chrome !== "undefined" && chrome.extension))
) {
// PC 端或插件版
setValue(e.currentTarget.value);
Expand Down Expand Up @@ -318,6 +321,24 @@ function SearchBar() {
}

function ShowcaseCards({ isDescription }) {
const [copyCounts, setCopyCounts] = useState({});

useEffect(() => {
const fetchData = async () => {
const counts = await fetchAllCopyCounts();
setCopyCounts(counts);
};

fetchData();
}, []);

const handleCardCopy = useCallback((cardId, updatedCount) => {
setCopyCounts((prevCopyCounts) => ({
...prevCopyCounts,
[cardId]: updatedCount,
}));
}, []);

const filteredUsers = useFilteredUsers();

if (filteredUsers.length === 0) {
Expand Down Expand Up @@ -361,6 +382,8 @@ function ShowcaseCards({ isDescription }) {
key={user.title}
user={user}
isDescription={isDescription}
copyCount={copyCounts[user.id] || 0}
onCopy={handleCardCopy}
/>
))}
</ul>
Expand All @@ -378,6 +401,8 @@ function ShowcaseCards({ isDescription }) {
key={user.title}
user={user}
isDescription={isDescription}
copyCount={copyCounts[user.id] || 0}
onCopy={handleCardCopy}
/>
))}
</ul>
Expand All @@ -396,6 +421,8 @@ function ShowcaseCards({ isDescription }) {
key={user.title}
user={user}
isDescription={isDescription}
copyCount={copyCounts[user.id] || 0}
onCopy={handleCardCopy}
/>
))}
</ul>
Expand All @@ -407,9 +434,9 @@ function ShowcaseCards({ isDescription }) {

export default function Showcase(): JSX.Element {
const [isDescription, setIsDescription] = useState(true);
const toggleDescription = () => {
setIsDescription(!isDescription);
};
const toggleDescription = useCallback(() => {
setIsDescription((prevIsDescription) => !prevIsDescription);
}, []);
return (
<Layout title={TITLE} description={DESCRIPTION}>
<main className="margin-vert--lg">
Expand Down
15 changes: 15 additions & 0 deletions src/pages/styles.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -93,3 +93,18 @@
.svgIconFavorite {
margin-left: 1rem;
}

.onToggleButton {
display: inline-block;
background-color: #18816a;
color: var(--site-color-favorite-background);
padding: 5px 10px;
border-radius: 5px;
text-decoration: none;
font-size: 8px;
font-weight: bold;
margin-right: 8px;
border: none;
box-shadow: none;
cursor: pointer;
}

0 comments on commit 826e393

Please sign in to comment.