This repository was archived by the owner on Dec 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.tsx
More file actions
284 lines (240 loc) · 5.81 KB
/
Copy pathindex.tsx
File metadata and controls
284 lines (240 loc) · 5.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import styled from 'styled-components';
import { GraphQLClient, gql } from 'graphql-request';
import {
KeyPair,
encodeOperation,
initWebAssembly,
signAndEncodeEntry,
} from 'p2panda-js';
import { ANIMALS } from './animals';
import type { FunctionComponent } from 'react';
type Fields = string[];
type FieldIndex = number;
type DocumentViewId = string;
const PRIVATE_KEY_STORE = 'privateKey';
const BOARD_SIZE = 4;
const GQL_NEXT_ARGS = gql`
query NextArgs($publicKey: String!, $viewId: String) {
nextArgs(publicKey: $publicKey, viewId: $viewId) {
logId
seqNum
backlink
skiplink
}
}
`;
const GQL_PUBLISH = gql`
mutation Publish($entry: String!, $operation: String!) {
publish(entry: $entry, operation: $operation) {
logId
seqNum
backlink
skiplink
}
}
`;
type NextArgs = {
logId: string;
seqNum: string;
backlink?: string;
skiplink?: string;
};
async function nextArgs(
client: GraphQLClient,
publicKey: string,
viewId?: DocumentViewId,
): Promise<NextArgs> {
const result = await client.request(GQL_NEXT_ARGS, {
publicKey,
viewId,
});
return result.nextArgs;
}
async function publish(
client: GraphQLClient,
entry: string,
operation: string,
): Promise<NextArgs> {
const result = await client.request(GQL_PUBLISH, {
entry,
operation,
});
return result.publish;
}
function initialiseKeyPair(): KeyPair {
const privateKey = window.localStorage.getItem(PRIVATE_KEY_STORE);
if (privateKey) {
return new KeyPair(privateKey);
}
const keyPair = new KeyPair();
window.localStorage.setItem(PRIVATE_KEY_STORE, keyPair.privateKey());
return keyPair;
}
function publicKeyToAnimal(publicKey: string): string {
const value = parseInt(publicKey.slice(0, 8), 16);
return ANIMALS[value % ANIMALS.length];
}
async function updateBoardField(
client: GraphQLClient,
keyPair: KeyPair,
schemaId: string,
viewId: DocumentViewId,
fieldIndex: FieldIndex,
animal: string,
): Promise<void> {
const args = await nextArgs(client, keyPair.publicKey(), viewId);
const payload = encodeOperation({
action: 'update',
previousOperations: viewId.split('_'),
schemaId,
fields: {
[`game_field_${fieldIndex}`]: animal,
},
});
const entry = signAndEncodeEntry(
{
...args,
payload,
},
keyPair,
);
await publish(client, entry, payload);
}
async function fetchBoard(
client: GraphQLClient,
schemaId: string,
documentId: string,
): Promise<{ viewId: DocumentViewId; fields: Fields }> {
const fields = new Array(BOARD_SIZE * BOARD_SIZE).fill(0).map((_, index) => {
return `game_field_${index + 1}`;
});
const query = gql`
query FetchBoard($documentId: String!) {
board: ${schemaId}(id: $documentId) {
meta {
viewId
}
fields {
${fields.join(' ')}
}
}
}
`;
const result = await client.request(query, {
documentId,
});
return {
viewId: result.board.meta.viewId,
fields: fields.map((fieldName) => {
return result.board.fields[fieldName];
}),
};
}
type GameBoardProps = {
fields: Fields;
onSetField: (index: FieldIndex) => void;
};
const StyledGameBoard = styled.div`
display: grid;
grid-template-columns: repeat(${BOARD_SIZE}, 1fr);
grid-auto-rows: 200px;
gap: 1em;
`;
const GameBoardField = styled.div`
display: inline-grid;
background-color: red;
cursor: pointer;
`;
const GameBoard: FunctionComponent<GameBoardProps> = ({
fields,
onSetField,
}) => {
return (
<StyledGameBoard>
{fields.map((field, index) => {
return (
<GameBoardField
key={`field-${index}`}
onClick={() => {
onSetField(index + 1);
}}
>
{field}
</GameBoardField>
);
})}
</StyledGameBoard>
);
};
type GameProps = {
keyPair: KeyPair;
config: Configuration;
};
const Game: FunctionComponent<GameProps> = ({ keyPair, config }) => {
const client = useMemo(() => {
return new GraphQLClient(config.endpoint);
}, [config.endpoint]);
const publicKey = useMemo(() => {
return keyPair.publicKey();
}, [keyPair]);
const animal = useMemo(() => {
return publicKeyToAnimal(publicKey);
}, [publicKey]);
const [viewId, setViewId] = useState<DocumentViewId>();
const [fields, setFields] = useState<Fields>();
const onSetField = useCallback(
async (fieldIndex: FieldIndex) => {
if (!viewId) {
return;
}
// Apply update locally first
setFields((value) => {
if (!value) {
return;
}
value[fieldIndex - 1] = animal;
return [...value];
});
// Send update to node
await updateBoardField(
client,
keyPair,
config.schemaId,
viewId,
fieldIndex,
animal,
);
},
[viewId, client, keyPair, config, animal],
);
useEffect(() => {
const init = async () => {
const board = await fetchBoard(
client,
config.schemaId,
config.documentId,
);
setViewId(board.viewId);
setFields(board.fields);
};
init();
}, [client, publicKey, config.schemaId, config.documentId]);
return <>{fields && <GameBoard fields={fields} onSetField={onSetField} />}</>;
};
export type Configuration = {
endpoint: string;
schemaId: string;
documentId: string;
};
export const ZooAdventures: FunctionComponent<Configuration> = (config) => {
const [keyPair, setKeyPair] = useState<KeyPair>();
useEffect(() => {
const init = async () => {
await initWebAssembly();
setKeyPair(initialiseKeyPair());
};
init();
}, []);
return keyPair ? <Game keyPair={keyPair} config={config} /> : null;
};