Skip to content

Commit c6c42eb

Browse files
committed
refactor(hooks): update usePresetViewsData to include refresh dependency
The usePresetViewsData hook now includes the refresh parameter to trigger data fetching when the refresh state changes. Additionally, single quotes were standardized across the file for consistency.
1 parent 9c22f64 commit c6c42eb

2 files changed

Lines changed: 31 additions & 28 deletions

File tree

src/hooks/use-square-presets.ts

Lines changed: 29 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import { sha1 } from "@/lib/utils";
2-
import { CharacterPresetTemplate, RawPreset } from "@/types/preset";
3-
import { SquarePresetData, SquarePresetDataView } from "@/types/square";
4-
import { load } from "js-yaml";
5-
import { useState, useEffect, useMemo } from "react";
1+
import { sha1 } from '@/lib/utils';
2+
import { CharacterPresetTemplate, RawPreset } from '@/types/preset';
3+
import { SquarePresetData, SquarePresetDataView } from '@/types/square';
4+
import { load } from 'js-yaml';
5+
import { useState, useEffect, useMemo } from 'react';
66

77
// 缓存管理对象
88
const cacheManager = {
@@ -15,7 +15,7 @@ const cacheManager = {
1515
presetContent: new Map<string, string>(),
1616
};
1717

18-
const API_URL = "https://api-chatluna-preset-market.dingyi222666.top";
18+
const API_URL = 'https://api-chatluna-preset-market.dingyi222666.top';
1919

2020
// 通用请求处理器
2121
const fetchWithCache = async <T>({
@@ -29,7 +29,7 @@ const fetchWithCache = async <T>({
2929
parser: (response: Response) => Promise<T>;
3030
ttl: number;
3131
}): Promise<T> => {
32-
if (cacheKey !== "presets") {
32+
if (cacheKey !== 'presets') {
3333
return;
3434
}
3535

@@ -55,7 +55,7 @@ const fetchPresets = async (): Promise<SquarePresetData[]> => {
5555
try {
5656
return await fetchWithCache({
5757
url: `https://gcore.jsdelivr.net/gh/chatlunalab/awesome-chatluna-presets@preset/presets.json?t=${Date.now()}`,
58-
cacheKey: "presets",
58+
cacheKey: 'presets',
5959
parser: async (response) => {
6060
const data = (await response.json()) as SquarePresetData[];
6161
await Promise.all(
@@ -68,7 +68,7 @@ const fetchPresets = async (): Promise<SquarePresetData[]> => {
6868
ttl: cacheManager.presets.ttl,
6969
});
7070
} catch (error) {
71-
console.error("Error fetching presets:", error);
71+
console.error('Error fetching presets:', error);
7272
return [];
7373
}
7474
};
@@ -88,19 +88,19 @@ export const fetchPresetData = async (
8888

8989
try {
9090
const response = await fetch(`${API_URL}/query_preset_views`, {
91-
method: "POST",
92-
headers: { "Content-Type": "application/json" },
91+
method: 'POST',
92+
headers: { 'Content-Type': 'application/json' },
9393
body: JSON.stringify(presetPaths),
9494
});
9595

96-
if (!response.ok) throw new Error("Failed to fetch preset data");
96+
if (!response.ok) throw new Error('Failed to fetch preset data');
9797

9898
const newData = (await response.json()) as SquarePresetDataView[];
9999
newData.forEach((data) => cacheManager.presetData.set(data.path, data));
100100

101101
return newData.sort((a, b) => b.path.localeCompare(a.path));
102102
} catch (error) {
103-
console.error("Error fetching preset data:", error);
103+
console.error('Error fetching preset data:', error);
104104
return [];
105105
}
106106
};
@@ -118,8 +118,8 @@ const sortStrategies = {
118118

119119
// 关键词过滤
120120
const filterByKeywords = (preset: SquarePresetData, keywords: string[]) => {
121-
const lowerKeywords = keywords?.map((k) => k?.toLowerCase() ?? "") ?? [];
122-
const presetType = preset.type === "main" ? "主插件" : "伪装";
121+
const lowerKeywords = keywords?.map((k) => k?.toLowerCase() ?? '') ?? [];
122+
const presetType = preset.type === 'main' ? '主插件' : '伪装';
123123

124124
return lowerKeywords.some(
125125
(keyword) =>
@@ -160,22 +160,25 @@ export function useSquarePresets(
160160
return sortedPresets;
161161
}
162162

163-
export function usePresetViewsData(presets: SquarePresetData[]) {
163+
export function usePresetViewsData(
164+
presets: SquarePresetData[],
165+
refresh: boolean
166+
) {
164167
const [presetData, setPresetData] = useState<SquarePresetDataView[]>([]);
165168

166169
useEffect(() => {
167170
fetchPresetData(presets).then(setPresetData);
168-
}, [presets]);
171+
}, [presets, refresh]);
169172

170173
return presetData;
171174
}
172175

173176
// 通用统计递增方法
174-
const incrementStat = async (id: string, type: "views" | "downloads") => {
177+
const incrementStat = async (id: string, type: 'views' | 'downloads') => {
175178
try {
176179
const response = await fetch(
177180
`${API_URL}/increment_preset_${type}?path=${id}`,
178-
{ headers: { "Content-Type": "application/json" } }
181+
{ headers: { 'Content-Type': 'application/json' } }
179182
);
180183
if (!response.ok) throw new Error(`Failed to increment ${type}`);
181184
return response;
@@ -189,9 +192,9 @@ export function clearPresetViewCache() {
189192
cacheManager.presetData.clear();
190193
}
191194

192-
export const incrementViews = (id: string) => incrementStat(id, "views");
195+
export const incrementViews = (id: string) => incrementStat(id, 'views');
193196
export const incrementDownloads = (id: string) =>
194-
incrementStat(id, "downloads");
197+
incrementStat(id, 'downloads');
195198

196199
export function useSquarePreset(id: string) {
197200
const [preset, setPreset] = useState<SquarePresetData>();
@@ -232,8 +235,8 @@ export function useSquarePresetForNetwork(squarePreset: SquarePresetData) {
232235
const cdnUrl = useMemo(
233236
() =>
234237
squarePreset.rawPath.replace(
235-
"https://raw.githubusercontent.com/ChatLunaLab/awesome-chatluna-presets/main/presets",
236-
"https://gcore.jsdelivr.net/gh/chatlunalab/awesome-chatluna-presets@main/presets"
238+
'https://raw.githubusercontent.com/ChatLunaLab/awesome-chatluna-presets/main/presets',
239+
'https://gcore.jsdelivr.net/gh/chatlunalab/awesome-chatluna-presets@main/presets'
237240
),
238241
[squarePreset.rawPath]
239242
);
@@ -247,14 +250,14 @@ export function useSquarePresetForNetwork(squarePreset: SquarePresetData) {
247250

248251
export async function downloadPreset(preset: SquarePresetData) {
249252
const url = preset.rawPath.replace(
250-
"https://raw.githubusercontent.com/ChatLunaLab/awesome-chatluna-presets/main/presets",
251-
"https://gcore.jsdelivr.net/gh/chatlunalab/awesome-chatluna-presets@main/presets"
253+
'https://raw.githubusercontent.com/ChatLunaLab/awesome-chatluna-presets/main/presets',
254+
'https://gcore.jsdelivr.net/gh/chatlunalab/awesome-chatluna-presets@main/presets'
252255
);
253256

254257
const blob = await fetch(url).then((r) => r.blob());
255258
const objectUrl = URL.createObjectURL(blob);
256259

257-
const anchor = document.createElement("a");
260+
const anchor = document.createElement('a');
258261
anchor.href = objectUrl;
259262
anchor.download = `${preset.name}.yml`;
260263
document.body.appendChild(anchor);

src/pages/square/page.tsx

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ export default function SquarePage() {
6060
[presets, currentPage]
6161
);
6262

63-
const presetDataList = usePresetViewsData(presets);
63+
const presetDataList = usePresetViewsData(presets,refresh);
6464

6565
const getPaginationRange = () => {
6666
const start = Math.max(1, currentPage - 1);
@@ -93,7 +93,7 @@ export default function SquarePage() {
9393
setTimeout(() => {
9494
setRefresh(false);
9595
}, 10);
96-
}, [search, sortOption]);
96+
}, [currentData]);
9797

9898
return (
9999
<MainLayout>

0 commit comments

Comments
 (0)