Skip to content

Commit

Permalink
more things
Browse files Browse the repository at this point in the history
  • Loading branch information
franciscoBSalgueiro committed Mar 28, 2024
1 parent 45dcffb commit 1afe344
Show file tree
Hide file tree
Showing 7 changed files with 63 additions and 56 deletions.
16 changes: 9 additions & 7 deletions src/components/boards/Board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,7 @@ import {
forceEnPassant,
positionFromFen,
} from "@/utils/chessops";
import {
type GameHeaders,
type TreeNode,
getNodeAtPath,
} from "@/utils/treeReducer";
import { getNodeAtPath } from "@/utils/treeReducer";
import {
ActionIcon,
Box,
Expand Down Expand Up @@ -70,6 +66,7 @@ import { memo, useContext, useEffect, useMemo, useState } from "react";
import { useHotkeys } from "react-hotkeys-hook";
import { match } from "ts-pattern";
import { useStore } from "zustand";
import { useShallow } from "zustand/react/shallow";
import ShowMaterial from "../common/ShowMaterial";
import { TreeStateContext } from "../common/TreeStateContext";
import { updateCardPerformance } from "../files/opening";
Expand Down Expand Up @@ -122,14 +119,19 @@ function Board({
const store = useContext(TreeStateContext)!;

const root = useStore(store, (s) => s.root);
const rootFen = useStore(store, (s) => s.root.fen);
const moves = useStore(
store,
useShallow((s) => getVariationLine(s.root, s.position)),
);
const position = useStore(store, (s) => s.position);
const headers = useStore(store, (s) => s.headers);
const currentNode = useStore(store, (s) => s.currentNode());

const arrows = useAtomValue(
bestMovesFamily({
fen: root.fen,
gameMoves: getVariationLine(root, position),
fen: rootFen,
gameMoves: moves,
}),
);

Expand Down
15 changes: 6 additions & 9 deletions src/components/boards/BoardAnalysis.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,25 +44,21 @@ function BoardAnalysis() {

const reset = useStore(store, (s) => s.reset);
const clearShapes = useStore(store, (s) => s.clearShapes);
const save = useStore(store, (s) => s.save);
const root = useStore(store, (s) => s.root);
const headers = useStore(store, (s) => s.headers);

const saveFile = useCallback(async () => {
saveToFile({
dir: documentDir,
headers,
root,
setCurrentTab,
tab: currentTab,
markAsSaved: () => save(),
store,
});
}, [headers, setCurrentTab, currentTab, save]);
}, [setCurrentTab, currentTab]);
useEffect(() => {
if (currentTab?.file && autoSave && dirty) {
saveFile();
}
}, [currentTab?.file, saveFile, autoSave, headers, dirty]);
}, [currentTab?.file, saveFile, autoSave, dirty]);

const addGame = useCallback(() => {
setCurrentTab((prev) => {
if (!prev?.file) return prev;
Expand All @@ -75,7 +71,8 @@ function BoardAnalysis() {
path: currentTab?.file?.path,
text: "\n\n",
});
}, [setCurrentTab, reset, currentTab?.file?.path, headers]); //root]);
}, [setCurrentTab, reset, currentTab?.file?.path]);

const keyMap = useAtomValue(keyMapAtom);
useHotkeys([
[keyMap.SAVE_FILE.keys, () => saveFile()],
Expand Down
38 changes: 21 additions & 17 deletions src/components/panels/analysis/AnalysisPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,12 @@ import {
import { getVariationLine } from "@/utils/chess";
import { getPiecesCount, hasCaptures, positionFromFen } from "@/utils/chessops";
import type { Engine } from "@/utils/engines";
import { getNodeAtPath } from "@/utils/treeReducer";
import { DragDropContext, Draggable, Droppable } from "@hello-pangea/dnd";
import {
Accordion,
ActionIcon,
Button,
Card,
Grid,
Group,
Paper,
Popover,
Expand All @@ -28,7 +26,6 @@ import {
Tabs,
Text,
} from "@mantine/core";
import { shallowEqual } from "@mantine/hooks";
import {
IconChevronsRight,
IconPlayerPause,
Expand All @@ -37,8 +34,9 @@ import {
} from "@tabler/icons-react";
import { useNavigate } from "@tanstack/react-router";
import { useAtom, useAtomValue } from "jotai";
import { memo, useContext, useMemo } from "react";
import { memo, useContext, useDeferredValue, useMemo } from "react";
import { useStore } from "zustand";
import { useShallow } from "zustand/react/shallow";
import BestMoves, { arrowColors } from "./BestMoves";
import EngineSelection from "./EngineSelection";
import LogsPanel from "./LogsPanel";
Expand All @@ -48,11 +46,21 @@ import TablebaseInfo from "./TablebaseInfo";

function AnalysisPanel() {
const store = useContext(TreeStateContext)!;
const root = useStore(store, (s) => s.root);
const rootFen = useStore(store, (s) => s.root.fen);
const position = useStore(store, (s) => s.position);
const headers = useStore(store, (s) => s.headers);
const currentNode = getNodeAtPath(root, position);
const currentNodeFen = useStore(
store,
useShallow((s) => s.currentNode().fen),
);
const is960 = useMemo(() => headers.variant === "Chess960", [headers]);
const moves = useStore(
store,
useShallow((s) => getVariationLine(s.root, s.position, is960)),
);
const currentNodeHalfMoves = useStore(
store,
useShallow((s) => s.currentNode().halfMoves),
);

const [engines, setEngines] = useAtom(enginesAtom);
const loadedEngines = useMemo(
Expand All @@ -68,13 +76,7 @@ function AnalysisPanel() {
const [tab, setTab] = useAtom(currentAnalysisTabAtom);
const [expanded, setExpanded] = useAtom(currentExpandedEnginesAtom);

const is960 = useMemo(() => headers.variant === "Chess960", [headers]);

const moves = useMemo(
() => getVariationLine(root, position, is960),
[root, position, is960],
);
const [pos] = positionFromFen(currentNode.fen);
const [pos] = positionFromFen(currentNodeFen);
const navigate = useNavigate();

return (
Expand Down Expand Up @@ -111,7 +113,7 @@ function AnalysisPanel() {
(getPiecesCount(pos) <= 7 ||
(getPiecesCount(pos) === 8 && hasCaptures(pos))) && (
<>
<TablebaseInfo fen={currentNode.fen} turn={pos.turn} />
<TablebaseInfo fen={currentNodeFen} turn={pos.turn} />
<Space h="sm" />
</>
)}
Expand Down Expand Up @@ -210,7 +212,7 @@ function AnalysisPanel() {
engine={engine}
fen={rootFen}
moves={moves}
halfMoves={currentNode.halfMoves}
halfMoves={currentNodeHalfMoves}
dragHandleProps={
provided.dragHandleProps
}
Expand Down Expand Up @@ -302,7 +304,9 @@ function EngineSummary({
engineMovesFamily({ engine: engine.name, tab: activeTab! }),
);

const curEval = ev.get(`${fen}:${moves.join(",")}`);
const curEval = useDeferredValue(
useMemo(() => ev.get(`${fen}:${moves.join(",")}`), [ev, fen, moves]),
);
const score = curEval && curEval.length > 0 ? curEval[0].score : null;

return (
Expand Down
11 changes: 2 additions & 9 deletions src/components/tabs/ConfirmChangesModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { Button, Group, Modal, Stack, Text } from "@mantine/core";
import { useLoaderData } from "@tanstack/react-router";
import { useAtom } from "jotai";
import { useContext } from "react";
import { useStore } from "zustand";
import { TreeStateContext } from "../common/TreeStateContext";

function ConfirmChangesModal({
Expand All @@ -17,21 +16,15 @@ function ConfirmChangesModal({
closeTab: () => void;
}) {
const [currentTab, setCurrentTab] = useAtom(currentTabAtom);
const store = useContext(TreeStateContext);
const storeSave = store !== null ? useStore(store, (s) => s.save) : () => {};
const store = useContext(TreeStateContext)!;
const { documentDir } = useLoaderData({ from: "/" });

function save() {
const { root, headers } = JSON.parse(
sessionStorage.getItem(currentTab?.value || "") || "{}",
);
saveToFile({
dir: documentDir,
setCurrentTab,
tab: currentTab,
headers,
root,
markAsSaved: () => storeSave(),
store,
});
}

Expand Down
11 changes: 11 additions & 0 deletions src/components/tabs/ImportModal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,17 @@ export default function ImportModal({
return;
}
fileInfo = newFile.value;
} else {
fileInfo = {
path: file,
numGames: count,
name: filename,
lastModified: Date.now(),
metadata: {
type: "game",
tags: [],
},
};
}
}
const tree = await parsePGN(input);
Expand Down
12 changes: 7 additions & 5 deletions src/state/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ANNOTATION_INFO, type Annotation } from "@/utils/annotation";
import { parseSanOrUci, positionFromFen } from "@/utils/chessops";
import { isPrefix } from "@/utils/misc";
import { getAnnotation } from "@/utils/score";
import { playSound } from "@/utils/sound";
import {
type GameHeaders,
type TreeNode,
Expand All @@ -20,7 +21,7 @@ import { produce } from "immer";
import { type StateCreator, createStore } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";

interface TreeStoreState {
export interface TreeStoreState {
root: TreeNode;
headers: GameHeaders;
position: number[];
Expand Down Expand Up @@ -121,7 +122,8 @@ export const createTreeStore = (id?: string, initialTree?: TreeState) => {
const node = getNodeAtPath(state.root, state.position);
const [pos] = positionFromFen(node.fen);
if (!pos || !node.children[0]?.move) return state;
// playSound(san.includes("x"), san.includes("+"));
const san = makeSan(pos, node.children[0].move);
playSound(san.includes("x"), san.includes("+"));
if (node && node.children.length > 0) {
return {
...state,
Expand Down Expand Up @@ -391,9 +393,9 @@ function makeMove({
const san = makeSan(pos, move);
if (san === "--") return; // invalid move
pos.play(move);
// if (sound) {
// playSound(san.includes("x"), san.includes("+"));
// }
if (sound) {
playSound(san.includes("x"), san.includes("+"));
}
if (changeHeaders && pos.isEnd()) {
if (pos.isCheckmate()) {
state.headers.result = pos.turn === "white" ? "0-1" : "1-0";
Expand Down
16 changes: 7 additions & 9 deletions src/utils/tabs.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { type FileMetadata, fileMetadataSchema } from "@/components/files/file";
import type { TreeStoreState } from "@/state/store";
import { save } from "@tauri-apps/api/dialog";
import { z } from "zod";
import type { StoreApi } from "zustand";
import { getPGN, parsePGN } from "./chess";
import { invoke } from "./invoke";
import type { GameHeaders, TreeNode } from "./treeReducer";
Expand Down Expand Up @@ -85,17 +87,13 @@ export async function createTab({
export async function saveToFile({
dir,
tab,
root,
headers,
setCurrentTab,
markAsSaved,
store,
}: {
dir: string;
tab: Tab | undefined;
root: TreeNode;
headers: GameHeaders;
setCurrentTab: React.Dispatch<React.SetStateAction<Tab>>;
markAsSaved: () => void;
store: StoreApi<TreeStoreState>;
}) {
let filePath: string;
if (tab?.file) {
Expand Down Expand Up @@ -131,13 +129,13 @@ export async function saveToFile({
await invoke("write_game", {
file: filePath,
n: tab?.gameNumber || 0,
pgn: `${getPGN(root, {
headers,
pgn: `${getPGN(store.getState().root, {
headers: store.getState().headers,
comments: true,
extraMarkups: true,
glyphs: true,
variations: true,
})}\n\n`,
});
markAsSaved();
store.getState().save();
}

0 comments on commit 1afe344

Please sign in to comment.