diff --git a/src/Components/Playground.tsx b/src/Components/Playground.tsx index 6b468b2..a450a55 100644 --- a/src/Components/Playground.tsx +++ b/src/Components/Playground.tsx @@ -6,6 +6,8 @@ import { FunctionComponent, useMemo, useState } from 'react' import { BlocklyWorkspace } from 'react-blockly' import type { GroupKey, LevelKey } from '../data/levels' import type { Database } from '../database/Database' +import { FinishedLevelId } from '../database/tables/FinishedLevel' +import { useFinishedLevelId } from '../utilities/useFinishedLevelId' import styles from './Playground.module.css' const initialXml = @@ -102,8 +104,9 @@ export const Playground: FunctionComponent<{ }), [allowedBlocks], ) - const { create } = useEvolu() + const { createOrUpdate } = useEvolu() const [code, setCode] = useState('') + const finishedLevelId = useFinishedLevelId(groupKey, levelKey) // @TODO: update theme with media query changes (workspace.setTheme(theme)) @@ -166,7 +169,16 @@ export const Playground: FunctionComponent<{ variant="contained" color="success" onClick={() => { - create('finishedLevel', { + createOrUpdate('finishedLevel', { + id: + finishedLevelId ?? + FinishedLevelId.make( + Math.random() + .toString(16) + .substring( + 2, + ) /* @TODO: This is very dumb. Assign to each level static global id. Or save each success to FinishedLevelTabel individually (multiple per level). */, + ), levelKey, groupKey, rating: PositiveInt.make(Math.floor(Math.random() * 3) + 1), diff --git a/src/utilities/useFinishedLevelId.ts b/src/utilities/useFinishedLevelId.ts new file mode 100644 index 0000000..ec0d176 --- /dev/null +++ b/src/utilities/useFinishedLevelId.ts @@ -0,0 +1,22 @@ +import { cast, useQuery } from '@evolu/react' +import { useMemo } from 'react' +import { GroupKey, LevelKey } from '../data/levels' +import { evolu } from '../database/Database' + +export const useFinishedLevelId = (groupKey: GroupKey, levelKey: LevelKey) => { + const query = useMemo( + () => + evolu.createQuery((database) => + database + .selectFrom('finishedLevel') + .select(['id']) + .where('isDeleted', 'is not', cast(true)) + .where('groupKey', 'is', groupKey) + .where('levelKey', 'is', levelKey), + ), + [groupKey, levelKey], + ) + const { row } = useQuery(query) + + return row?.id ?? null +}