feat: 更新包管理器为 bun,优化项目配置和资源管理

- 将包管理器从 pnpm 更改为 bun,提升依赖管理效率。
- 在 index.html 中引入 jQuery 和 videoajax.js,增强页面功能。
- 删除 pnpm-lock.yaml 文件,清理不必要的锁定文件。
- 在多个组件中优化状态管理和访问逻辑,提升用户体验。
- 更新多个页面和组件以支持新的状态管理方式,确保数据一致性。
This commit is contained in:
zhongyidian committed 2026-02-06 09:28:25 +08:00
1 parent ac5a2159a1
commit 7bbeb10e57
33 files changed
+2291 -4531

No files matched your search

+16 -1
View File
@@ -1,8 +1,9 @@
import { RouterProvider } from "react-router-dom";
import { Suspense } from "react";
import { Suspense, useEffect } from "react";
import router from "./router";
import { ScaleProvider, useScale } from "./contexts/ScaleContext";
import { RotateHint } from "./components/RotateHint";
import { useUserStore } from "./store";
/**
* 应用内容组件
@@ -10,6 +11,20 @@ import { RotateHint } from "./components/RotateHint";
*/
function AppContent() {
const { scaleStyle } = useScale();
const setCourseInfo = useUserStore((state) => state.setCourseInfo);
useEffect(() => {
const params = new URLSearchParams(window.location.search);
const courseId = params.get("courseid");
const uid = params.get("uid");
if (courseId || uid) {
setCourseInfo({
courseId: courseId ?? null,
uid: uid ?? null,
});
}
}, [setCourseInfo]);
return (
<>
Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

+353
View File
@@ -0,0 +1,353 @@
import { useMemo, useState } from "react";
import { getBackgroundImage, getStaticImage } from "@/lib/utils";
import { usePuzzleStore } from "@/store/puzzleStore";
import { Image } from "@/components";
/**
* 六边形进度条组件
* 根据进度值显示不同颜色:100%绿色,50%-99%橙色,0%-49%灰色
*/
interface HexagonProgressBarProps {
progress: number; // 0-100
}
const HexagonProgressBar = ({ progress }: HexagonProgressBarProps) => {
const progressPercent = Math.min(100, Math.max(0, progress));
const progressText = progressPercent.toFixed(2) === "100.00"
? "进度100%"
: `进度${Math.round(progressPercent)}%`;
// 根据进度值确定填充颜色
const getProgressColor = () => {
if (progressPercent >= 100) {
return "#90B86B"; // 浅橄榄绿色(100%完成)
} else if (progressPercent >= 50) {
return "#EEB362"; // 橙色(50%-99%)
} else {
return "#E0E0E0"; // 浅灰色(0%-49%)
}
};
const fillColor = getProgressColor();
// 六边形路径,细长的水平六边形,左右两端是尖角
// 正确的六边形路径:从左顶点开始,顺时针绘制
// 左顶点(0%, 50%) -> 左上角(3%, 0%) -> 右上角(97%, 0%) -> 右顶点(100%, 50%) -> 右下角(97%, 100%) -> 左下角(3%, 100%)
// 外层路径(包含边框)
const outerHexagonPath = "polygon(0% 50%, 3% 0%, 97% 0%, 100% 50%, 97% 100%, 3% 100%)";
// 内层路径(边框内部)
const innerHexagonPath = "polygon(0% 50%, 3% 0%, 97% 0%, 100% 50%, 97% 100%, 3% 100%)";
const borderWidth = 4; // 增加边框宽度从2px到3px
return (
<div className="relative" style={{ width: "260px", height: "50px" }}>
{/* 外层:白色边框(使用 clip-path 裁剪形状) */}
<div
className="absolute inset-0"
style={{
clipPath: outerHexagonPath,
backgroundColor: "white",
}}
/>
{/* 内容容器(边框内部区域) */}
<div
className="absolute"
style={{
left: `${borderWidth}px`,
top: `${borderWidth}px`,
right: `${borderWidth}px`,
bottom: `${borderWidth}px`,
clipPath: innerHexagonPath,
}}
>
{/* 背景层:深灰色背景(未填充部分) */}
<div
className="absolute inset-0"
style={{
backgroundColor: "#757575",
}}
/>
{/* 填充层(根据进度百分比从左侧填充) */}
{progressPercent > 0 && (
<div
className="absolute left-0 top-0 bottom-0 overflow-hidden"
style={{
width: `${progressPercent}%`,
}}
>
<div
className="absolute inset-0"
style={{
backgroundColor: fillColor,
transition: "width 0.3s ease, background-color 0.3s ease",
}}
/>
</div>
)}
</div>
{/* 文字(白色,居中,始终显示在最上层,带阴影效果) */}
<div
className="absolute inset-0 flex items-center justify-center text-white text-2xl font-bold pointer-events-none"
style={{
textShadow: "0 2px 4px rgba(0,0,0,0.6), 0 1px 2px rgba(0,0,0,0.8)",
zIndex: 10,
}}
>
{progressText}
</div>
</div>
);
};
export interface MenuPuzzleCenterProps {
/** 是否可见 */
visible: boolean;
/** 关闭回调 */
onClose: () => void;
/** 选择某个故居后的回调(进入对应的碎片系统) */
onSelectResidence: (residence: string) => void;
}
interface ResidenceConfig {
/** 拼图存储用的英文 key(如 chenyun) */
residence: string;
/** 显示名称 */
displayName: string;
/** 在大地图上的水平位置(百分比字符串,如 "20%") */
left: string;
/** 在大地图上的垂直位置(百分比字符串,如 "40%") */
top: string;
/** 显示用图片路径(相对于 puzzle/home/ 目录) */
image: string;
/** 是否已经开放拼图(未开放时只展示,不可点击) */
hasPuzzle: boolean;
/** 是否有导图资源 */
hasMap?: boolean;
/** 导图资源文件名(位于 puzzle/home/map 下) */
mapImage?: string;
}
/**
* 顶层碎片管理中心中展示的故居列表(8 个故居)
* left / top 为大致位置,后续可以根据视觉效果微调
* image 资源都位于 puzzle/home 目录下,命名可按实际资源调整
*/
const RESIDENCE_LIST: ResidenceConfig[] = [
{
residence: "maozedong",
displayName: "毛泽东旧居",
left: "30%",
top: "35%",
image: "毛泽东",
hasPuzzle: true,
hasMap: true,
mapImage: "毛泽东导图",
},
{
residence: "sunzhongshan",
displayName: "孙中山故居",
left: "12%",
top: "51%",
image: "孙中山",
hasPuzzle: true,
hasMap: true,
mapImage: "孙中山导图",
},
{
residence: "luxun",
displayName: "鲁迅故居",
left: "26.3%",
top: "74%",
image: "鲁迅",
hasPuzzle: true,
hasMap: true,
mapImage: "鲁迅导图",
},
{
residence: "huangyanpei",
displayName: "黄炎培故居",
left: "44%",
top: "67%",
image: "黄炎培",
hasPuzzle: true,
hasMap: true,
mapImage: "黄炎培导图",
},
{
residence: "nieer",
displayName: "聂耳旧居",
left: "62%",
top: "60%",
image: "聂耳",
hasPuzzle: true,
hasMap: false,
},
{
residence: "zhangleping",
displayName: "张乐平故居",
left: "73%",
top: "33%",
image: "张乐平",
hasPuzzle: true,
hasMap: false,
},
{
residence: "rongdesheng",
displayName: "荣德生旧居",
left: "90%",
top: "45%",
image: "荣德生",
hasPuzzle: true,
hasMap: false,
},
{
residence: "chenyun",
displayName: "陈云故居",
left: "80%",
top: "76%",
image: "陈云",
hasPuzzle: true,
hasMap: true,
mapImage: "陈云导图",
},
];
const MenuPuzzleCenter = ({
visible,
onClose,
onSelectResidence,
}: MenuPuzzleCenterProps) => {
const { getPuzzleCollectProgress } = usePuzzleStore();
const [activeMapImage, setActiveMapImage] = useState<string | null>(null);
const residenceProgress = useMemo(
() =>
RESIDENCE_LIST.map((item) => ({
...item,
// 只有已开放拼图的故居才计算收集进度
progress: item.hasPuzzle ? getPuzzleCollectProgress(item.residence) : 0,
})),
[getPuzzleCollectProgress]
);
if (!visible) return null;
return (
<div
className="fixed inset-0 z-90 flex items-center justify-center"
style={{ background: "rgba(0,0,0,0.8)" }}
onClick={(e) => {
if (e.target === e.currentTarget) {
onClose();
}
}}
>
<div
className="relative w-full h-full bg-cover bg-center bg-no-repeat"
style={{ backgroundImage: getBackgroundImage("puzzle/home/底图") }}
>
{/* 箭头指示底图 */}
<img className="absolute top-84 left-55" src={getStaticImage("puzzle/home/箭头指引")} alt="" />
{/* 关闭按钮 */}
<Image
className="absolute right-8 top-8 z-10"
src={getStaticImage("components/关闭")}
alt="关闭"
button
onClick={onClose}
/>
{/* 故居列表:按照设计图进行绝对定位 */}
<div className="absolute inset-0">
{residenceProgress.map(
({
residence,
displayName,
left,
top,
image,
hasPuzzle,
progress,
hasMap,
mapImage,
}) => (
<div
key={residence}
className={`absolute -translate-x-1/2 -translate-y-1/2`}
style={{ left, top }}
>
{/* 故居图片(资源在 puzzle/home 下,可根据实际名称调整) */}
<Image
src={getStaticImage(`puzzle/home/${image}`)}
alt={displayName}
/>
{/* 进度展示,仅对已开放拼图的故居显示 */}
{hasPuzzle && (
<div className="mb-4 flex justify-center">
<HexagonProgressBar progress={progress} />
</div>
)}
{/* 图标 */}
<div className="flex justify-center gap-6">
<Image src={getStaticImage(`puzzle/home/拼图`)} alt="拼图" button
onClick={(e) => {
if (!hasPuzzle) return;
e.stopPropagation();
onSelectResidence(residence);
}} />
<Image
src={getStaticImage(`puzzle/home/导图`)}
alt="导图"
button
onClick={(e) => {
e.stopPropagation();
if (!hasMap || !mapImage) return;
setActiveMapImage(mapImage);
}}
/>
</div>
</div>
)
)}
</div>
{/* 导图弹窗 */}
{activeMapImage && (
<div
className="fixed inset-0 z-110 flex items-center justify-center"
style={{ background: "rgba(0,0,0,0.75)" }}
onClick={(e) => {
if (e.target === e.currentTarget) {
setActiveMapImage(null);
}
}}
>
<div className="relative w-full h-full">
<div className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
<Image
className="absolute -right-4 -top-8 z-10"
src={getStaticImage("components/close")}
alt="关闭"
button
onClick={() => setActiveMapImage(null)}
/>
<img
src={getStaticImage(`puzzle/home/map/${activeMapImage}`)}
alt="导图"
/>
</div>
</div>
</div>
)}
</div>
</div>
);
};
export default MenuPuzzleCenter;
+17 -1
View File
@@ -86,6 +86,22 @@ const PuzzlePieceSvg = ({
className={cn(isUnlocked ? "puzzle-piece" : "")}
>
<defs>
{/* Safari/iOS 对 SVG image 的 CSS filter 支持有限,使用滤镜定义保证生效 */}
<filter
id={`${patternId}-dim`}
colorInterpolationFilters="sRGB"
x="0%"
y="0%"
width="100%"
height="100%"
>
{/* 将亮度压低到约 20% */}
<feColorMatrix
type="matrix"
values="0.2 0 0 0 0 0 0.2 0 0 0 0 0 0.2 0 0 0 0 0 1 0"
/>
</filter>
<pattern
id={patternId}
patternUnits="objectBoundingBox"
@@ -98,8 +114,8 @@ const PuzzlePieceSvg = ({
width={1}
height={1}
preserveAspectRatio="none"
filter={isUnlocked ? undefined : `url(#${patternId}-dim)`}
style={{
filter: isUnlocked ? "none" : "brightness(0.2)",
transition: "filter 220ms ease",
}}
/>
+79 -26
View File
@@ -90,12 +90,12 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
[allowDuplicate, currentValue]
);
// 处理鼠标移动
const handleMouseMove = useCallback(
(e: MouseEvent) => {
// 通用的坐标更新逻辑(鼠标/触摸)
const updateDragPosition = useCallback(
(clientX: number, clientY: number) => {
if (!draggingOption) return;
setDragPosition({ x: e.clientX, y: e.clientY });
setDragPosition({ x: clientX, y: clientY });
// 检测是否悬停在空白区域上
let foundBlank: string | null = null;
@@ -104,10 +104,10 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
blankRefsMap.current.forEach((element, blankId) => {
const rect = element.getBoundingClientRect();
if (
e.clientX >= rect.left &&
e.clientX <= rect.right &&
e.clientY >= rect.top &&
e.clientY <= rect.bottom
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= rect.bottom
) {
foundBlank = blankId;
}
@@ -122,10 +122,10 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
if (element) {
const rect = element.getBoundingClientRect();
if (
e.clientX >= rect.left &&
e.clientX <= rect.right &&
e.clientY >= rect.top &&
e.clientY <= rect.bottom
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= rect.bottom
) {
foundBlank = blank.id;
}
@@ -138,8 +138,28 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
[draggingOption, normalizedBlanks]
);
// 处理鼠标释放
const handleMouseUp = useCallback(() => {
// 处理鼠标移动
const handleMouseMove = useCallback(
(e: MouseEvent) => {
updateDragPosition(e.clientX, e.clientY);
},
[updateDragPosition]
);
// 处理触摸移动
const handleTouchMove = useCallback(
(e: TouchEvent) => {
const touch = e.touches[0];
if (!touch) return;
// 阻止页面滚动,确保拖拽顺滑
e.preventDefault();
updateDragPosition(touch.clientX, touch.clientY);
},
[updateDragPosition]
);
// 处理释放(鼠标/触摸)
const handleRelease = useCallback(() => {
if (!draggingOption) return;
// 如果悬停在空白区域上,执行放置
@@ -212,16 +232,29 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
useEffect(() => {
if (draggingOption) {
document.addEventListener("mousemove", handleMouseMove);
document.addEventListener("mouseup", handleMouseUp);
document.addEventListener("mouseup", handleRelease);
document.addEventListener("touchmove", handleTouchMove, {
passive: false,
});
document.addEventListener("touchend", handleRelease);
document.addEventListener("touchcancel", handleRelease);
return () => {
document.removeEventListener("mousemove", handleMouseMove);
document.removeEventListener("mouseup", handleMouseUp);
document.removeEventListener("mouseup", handleRelease);
document.removeEventListener("touchmove", handleTouchMove);
document.removeEventListener("touchend", handleRelease);
document.removeEventListener("touchcancel", handleRelease);
};
}
}, [draggingOption, handleMouseMove, handleMouseUp]);
}, [draggingOption, handleMouseMove, handleTouchMove, handleRelease]);
// 处理鼠标按下开始拖拽
const handleMouseDown = (e: React.MouseEvent, optionValue: string) => {
// 开始拖拽(通用)
const startDragging = (
optionValue: string,
clientX: number,
clientY: number,
currentTarget: HTMLElement
) => {
if (disabled) return;
const option = normalizedOptions.find((opt) => opt.value === optionValue);
if (option?.disabled) return;
@@ -230,10 +263,10 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
if (!allowDuplicate && isOptionUsed(optionValue)) return;
// 获取实际的元素(如果有自定义渲染,使用第一个子元素)
const wrapperElement = e.currentTarget as HTMLElement;
const actualElement = (
renderOption ? wrapperElement.firstElementChild : wrapperElement
) as HTMLElement;
const wrapperElement = currentTarget;
const actualElement = renderOption
? (wrapperElement.firstElementChild as HTMLElement)
: wrapperElement;
if (!actualElement) return;
@@ -241,12 +274,26 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
// 记录偏移量和元素尺寸
dragOffsetRef.current = {
x: e.clientX - rect.left,
y: e.clientY - rect.top,
x: clientX - rect.left,
y: clientY - rect.top,
};
setDraggingOption(optionValue);
setDragPosition({ x: e.clientX, y: e.clientY });
setDragPosition({ x: clientX, y: clientY });
};
// 处理鼠标按下开始拖拽
const handleMouseDown = (e: React.MouseEvent, optionValue: string) => {
startDragging(optionValue, e.clientX, e.clientY, e.currentTarget);
};
// 处理触摸开始拖拽
const handleTouchStart = (e: React.TouchEvent, optionValue: string) => {
const touch = e.touches[0];
if (!touch) return;
// 防止滚动干扰
e.preventDefault();
startDragging(optionValue, touch.clientX, touch.clientY, e.currentTarget);
};
// 移除填充
@@ -288,6 +335,7 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
return (
<div
onMouseDown={(e) => handleMouseDown(e, option.value)}
onTouchStart={(e) => handleTouchStart(e, option.value)}
className={cn(
"px-6 py-4 border-2 rounded-lg transition-all select-none",
!disabled &&
@@ -439,6 +487,11 @@ const DragFill = forwardRef<HTMLDivElement, DragFillProps>(
handleMouseDown(e, option.value);
}
}}
onTouchStart={(e) => {
if (!disabled && !option.disabled && !isUsed) {
handleTouchStart(e, option.value);
}
}}
className={cn(
renderOption && "select-none",
!optionClassName && renderOption && "flex-1",
+127
View File
@@ -0,0 +1,127 @@
$.extend({
getUrlVars: function(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
},
getUrlVar: function(name){
return $.getUrlVars()[name];
}
});
var lesson="yuxiang"
var videoajax = videoAjax();
videoajax.setHost("/");
//设置我的自定义数据(所有的自定义数据都设置在第一个课时ID上,以key来区分不同的类型)
function setLtDefine(key,value){
if(iscallyb){
setUserDefine(1,key,value);
}else{
sessionStorage.setItem(lesson+"_"+key,value);
}
}
var mycstr9 = "";
//获取定义数据
function getLtDefine(key){
if(iscallyb){
let cstr = "";
if(mycstr9 == ""){
let cstr = getUsersDefine(1, emykey);
if(cstr == undefined || cstr == null || cstr == "null" || cstr == ""){
mycstr9 = getFutureDa(10);
setLtDefine(emykey, mycstr9);
}else{
mycstr9 = cstr;
}
}
cstr = mycstr9;
let str = (cstr == undefined || cstr==null || cstr=="null")?"":cstr;
getCurrentDa(str);
var objitem = getUserDefine(1,key);
return (objitem == undefined || objitem==null || objitem=="null")?"":objitem;
}else{
// let cstr = sessionStorage.getItem(lesson+"_"+emykey);
// let str = (cstr == undefined || cstr==null || cstr=="null")?"":cstr;
// getCurrentDa(str);
var itemvalue = sessionStorage.getItem(lesson+"_"+key);
return (itemvalue == undefined || itemvalue==null || itemvalue=="null")?"":itemvalue;
}
}
//设置课程笔记10002
function setCourseNotepad(collect){
setLtDefine(10002,$.toJSON(collect));
}
//获取课程笔记10002
function getCourseNotepad(){
return (getLtDefine(10002) == undefined || getLtDefine(10002) == null || getLtDefine(10002) == "") ? ["","","","","","","","",""] : $.parseJSON(getLtDefine(10002));
}
//lessonId(课时唯一ID)
export function setUserDefine(lessonId,key,value) {
var param = { "lessonId": lesson+"_"+lessonId, "key": key, "content": value };
videoajax.addUserDefine(param);
}
//获取用户自定义数据
export function getUserDefine(lessonId,key) {
var param = { "lessonId": lesson+"_"+lessonId, "order": key };
var content = "";
videoajax.getUserDefineInfoByUser(param, function (data) {
console.log(data)
if (data && data.code == 200) {
var json = data.data.value || {};
var contents = json[0].content || "";
content = contents;
}else{
content = "";
}
});
return content;
}
//获取【所有】用户自定义数据
export function getUsersDefine(lessonId,key) {
var param = { "lessonId": lesson+"_"+lessonId, "order": key };
var content = "";
videoajax.getUserDefineInfo(param, function (data) {
if (data && data.code == 200) {
//console.info(data);
var json = data.data.value || {};
if(json.length > 1){
if(key == emykey){
let mdate = new Date(Math.max.apply(null, json.map(item => new Date(item.content))));
content = formatDateFromMilliseconds(mdate);
}else{
content = json;
}
}else{
content = json[0].content || "";
}
}else{
content = "";
}
});
return content;
}
//根据课时顺序号(所处课程的第几课时)更新对应易班平台上的每个环节进度
export function setCourseTimeProgress(order){
//var courseid = getCookie(lesson+"_course_id");//获取url链接的课程ID
var courseid = getLtDefine("10000");
console.info("courseid:" + courseid + " order:" + order);
if (iscallyb && courseid != undefined && courseid != null && courseid != "") {
if (order > 0) {
var param2 = { "order": order, "co": courseid, "process": 100 };
videoajax.finishCourse(param2);
}
}
}
+40 -3
View File
@@ -1,14 +1,17 @@
import { useState } from "react";
import { getBackgroundImage, getStaticImage } from "@/lib/utils";
import { Image } from "@/components";
import { Image, PuzzleSystem } from "@/components";
import { useNavigate } from "react-router-dom";
import MenuPuzzleCenter from "@/components/puzzle/MenuPuzzleCenter";
const Menu = () => {
const navigate = useNavigate();
const [isPuzzleCenterVisible, setIsPuzzleCenterVisible] = useState(false);
const [activeResidence, setActiveResidence] = useState<string | null>(null);
/**
*类型:1:革命先驱、文化民人、艺术名家、经济巨擘
* 类型:1:革命先驱、文化民人、艺术名家、经济巨擘
*/
const Category = [
{
id: 1,
@@ -48,6 +51,15 @@ const Menu = () => {
onClick={() => navigate("/")}
/>
{/* 左下角碎片盒按钮 - 进入碎片管理中心 */}
<div className="absolute left-4 bottom-4 z-10 cursor-pointer">
<Image
src={getStaticImage("components/拼图盒")}
button
onClick={() => setIsPuzzleCenterVisible(true)}
/>
</div>
<div className="absolute left-40 top-70 inline-grid grid-cols-2 gap-x-20 gap-y-10">
{Category.map((item) => (
<div
@@ -72,8 +84,33 @@ const Menu = () => {
</div>
))}
</div>
{/* 顶层碎片管理中心:选择要查看的故居拼图 */}
<MenuPuzzleCenter
visible={isPuzzleCenterVisible}
onClose={() => setIsPuzzleCenterVisible(false)}
onSelectResidence={(residence) => {
setActiveResidence(residence);
setIsPuzzleCenterVisible(false);
}}
/>
{/* 进入具体故居的拼图系统(与故居页面一致的 PuzzleSystem) */}
{activeResidence && (
<PuzzleSystem
visible={!!activeResidence}
onClose={() => {
setActiveResidence(null);
// 关闭 PuzzleSystem 后,重新打开碎片管理中心
setIsPuzzleCenterVisible(true);
}}
residence={activeResidence}
/>
)}
</div>
);
};
export default Menu;
+46
View File
@@ -1,6 +1,23 @@
import { useEffect } from "react";
import { getBackgroundImage, getStaticImage } from "@/lib/utils";
import { useNavigate, useParams } from "react-router-dom";
import { Image } from "@/components";
import { getUserDefine } from "@/lib/utils/api-common";
import { useChenyunStore } from "@/store/chenyunStore";
const CHENYUN_LESSON_ID = "chenyunStore";
const CHENYUN_KEY = 1;
const deserializeVisitedExhibits = (
data: Record<string, number[]> | undefined
): Record<string, Set<number>> => {
if (!data || typeof data !== "object") return {};
const visitedExhibits: Record<string, Set<number>> = {};
for (const [place, exhibits] of Object.entries(data)) {
visitedExhibits[place] = new Set(Array.isArray(exhibits) ? exhibits : []);
}
return visitedExhibits;
};
const Chenyun = () => {
const navigate = useNavigate();
@@ -11,6 +28,35 @@ const Chenyun = () => {
// starName 固定为 chenyun
const starName = "chenyun";
useEffect(() => {
try {
const raw = getUserDefine(CHENYUN_LESSON_ID, CHENYUN_KEY);
console.log(raw)
if (!raw) return;
const data = JSON.parse(raw) as {
visitedExhibits?: Record<string, number[]>;
isYinyuanSolved?: boolean;
isMimianSolved?: boolean;
};
useChenyunStore.setState((prev) => ({
...prev,
visitedExhibits: deserializeVisitedExhibits(data.visitedExhibits),
isYinyuanSolved:
data.isYinyuanSolved !== undefined
? data.isYinyuanSolved
: prev.isYinyuanSolved,
isMimianSolved:
data.isMimianSolved !== undefined
? data.isMimianSolved
: prev.isMimianSolved,
}));
} catch (error) {
console.error("Failed to load Chenyun store", error);
}
}, []);
if (!moduleName) {
return null;
}
+27 -2
View File
@@ -12,11 +12,36 @@ import { getBackgroundImage, getStaticImage, getPublicPath } from "@/lib/utils";
import { useNavigate, useParams } from "react-router-dom";
import type { VideoRef } from "@/components/video";
import { useChenyunStore } from "@/store/chenyunStore";
import { setUserDefine } from "@/lib/utils/api-common";
import { usePuzzleAnimation } from "@/contexts/PuzzleAnimationContext";
// starName 固定为 chenyun
const starName = "chenyun";
const CHENYUN_LESSON_ID = "chenyunStore";
const CHENYUN_KEY = 1;
const saveChenyunStore = () => {
const state = useChenyunStore.getState();
const visitedExhibits: Record<string, number[]> = {};
for (const [place, exhibits] of Object.entries(state.visitedExhibits)) {
visitedExhibits[place] = Array.from(exhibits);
}
const payload = {
visitedExhibits,
isYinyuanSolved: state.isYinyuanSolved,
isMimianSolved: state.isMimianSolved,
};
try {
setUserDefine(CHENYUN_LESSON_ID, CHENYUN_KEY, JSON.stringify(payload));
} catch (error) {
console.error("Failed to save Chenyun store", error);
}
};
// 展品 ID 与资源路径映射
const exhibitSrcMap: Record<1, string> = {
1: "chenyun/place9/场景9展品1",
@@ -34,8 +59,7 @@ const ChenyunPlace9 = () => {
// 使用持久化的访问状态
const place = "place9";
const { isExhibitVisited, markExhibitVisited, getVisitedExhibits } =
useChenyunStore();
const { markExhibitVisited, getVisitedExhibits } = useChenyunStore();
// 从 store 获取已访问的展品,转换为 Set 用于兼容现有代码
const visitedExhibits = getVisitedExhibits(place);
@@ -117,6 +141,7 @@ const ChenyunPlace9 = () => {
src={getStaticImage("chenyun/place9/离开场景")}
button
onClick={() => {
saveChenyunStore();
navigate(`/${moduleName}/${starName}/home`);
}}
/>
+2 -1
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { STORE_NAMES } from "./storeNames";
interface ChenyunStore {
// 存储每个场景(place)的已访问展品ID集合
@@ -116,7 +117,7 @@ export const useChenyunStore = create<ChenyunStore>()(
},
}),
{
name: "chenyun-storage", // localStorage key
name: STORE_NAMES.CHENYUN, // localStorage key
partialize: (state) => ({
visitedExhibits: serializeVisitedExhibits(state.visitedExhibits),
isYinyuanSolved: state.isYinyuanSolved,
+2 -1
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { STORE_NAMES } from "./storeNames";
export interface Clue {
id: string; // 格式: "sunzhongshan/reflection/scene1/clue1"
@@ -76,7 +77,7 @@ export const useClueStore = create<ClueStore>()(
},
}),
{
name: "clue-storage", // localStorage key
name: STORE_NAMES.CLUE, // localStorage key
}
)
);
+2 -1
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { STORE_NAMES } from "./storeNames";
interface HuangyanpeiStore {
// 存储每个场景(place)的已访问展品ID集合
@@ -154,7 +155,7 @@ export const useHuangyanpeiStore = create<HuangyanpeiStore>()(
},
}),
{
name: "huangyanpei-storage", // localStorage key
name: STORE_NAMES.HUANGYANPEI, // localStorage key
partialize: (state) => ({
visitedExhibits: serializeVisitedExhibits(state.visitedExhibits),
visitedReflectionCursors: serializeVisitedExhibits(
+2
View File
@@ -4,3 +4,5 @@ export { useLuxunStore } from "./luxunStore";
export { useSunzhongshanStore } from "./sunzhongshanStore";
export { useClueStore } from "./clueStore";
export { usePuzzleStore } from "./puzzleStore";
export { useUserStore } from "./userStore";
export { STORE_NAMES } from "./storeNames";
+2 -1
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { STORE_NAMES } from "./storeNames";
interface LuxunStore {
// 存储每个场景(place)的已访问展品ID集合
@@ -94,7 +95,7 @@ export const useLuxunStore = create<LuxunStore>()(
},
}),
{
name: "luxun-storage",
name: STORE_NAMES.LUXUN,
partialize: (state) => ({
visitedExhibits: serializeVisitedExhibits(state.visitedExhibits),
}),
+2 -1
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { STORE_NAMES } from "./storeNames";
interface PuzzleStore {
// 每个故居的已解锁碎片集合,格式:{ residence: Set<pieceId> }
@@ -135,7 +136,7 @@ export const usePuzzleStore = create<PuzzleStore>()(
},
}),
{
name: "puzzle-storage", // localStorage key
name: STORE_NAMES.PUZZLE, // localStorage key
partialize: (state) => ({
puzzles: serializePuzzles(state.puzzles),
}),
+25
View File
@@ -0,0 +1,25 @@
//lessonId 课时唯一id
export const STORE_NAMES = {
USER: "user-storage",
SUNZHONGSHAN: "sunzhongshan-storage",
LUXUN: "luxun-storage",
HUANGYANPEI: "huangyanpei-storage",
CHENYUN: "chenyun-storage",
PUZZLE: "puzzle-storage",
CLUE: "clue-storage",
} as const;
//课程的第几课时
export const COURSE_ORDER = {
COURSE_ORDER_1: 1,
COURSE_ORDER_2: 2,
COURSE_ORDER_3: 3,
COURSE_ORDER_4: 4,
COURSE_ORDER_5: 5,
COURSE_ORDER_6: 6,
COURSE_ORDER_7: 7,
} as const;
export type StoreNameKey = keyof typeof STORE_NAMES;
+2 -1
View File
@@ -1,5 +1,6 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { STORE_NAMES } from "./storeNames";
interface SunzhongshanStore {
// 存储每个场景(place)的已访问展品ID集合
@@ -118,7 +119,7 @@ export const useSunzhongshanStore = create<SunzhongshanStore>()(
},
}),
{
name: "sunzhongshan-storage",
name: STORE_NAMES.SUNZHONGSHAN,
partialize: (state) => ({
visitedExhibits: serializeVisitedExhibits(state.visitedExhibits),
reflectionFlags: state.reflectionFlags,
+36
View File
@@ -0,0 +1,36 @@
import { create } from "zustand";
import { persist } from "zustand/middleware";
import { STORE_NAMES } from "./storeNames";
interface UserStore {
courseId: string | null;
uid: string | null;
setCourseInfo: (info: { courseId?: string | null; uid?: string | null }) => void;
resetCourseInfo: () => void;
}
export const useUserStore = create<UserStore>()(
persist(
(set) => ({
courseId: null,
uid: null,
setCourseInfo: (info) => {
set((state) => ({
courseId: info.courseId ?? state.courseId,
uid: info.uid ?? state.uid,
}));
},
resetCourseInfo: () => {
set({ courseId: null, uid: null });
},
}),
{
name: STORE_NAMES.USER,
}
)
);