@celljs/ta-play 0.0.0-stage → 4.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/index.js ADDED
@@ -0,0 +1,1490 @@
1
+ // ../ta-protocol/esm/common/language.js
2
+ var TaLanguageUtil;
3
+ (function(TaLanguageUtil2) {
4
+ TaLanguageUtil2.ALL = ["zh-CN", "zh-TW", "en-US", "ja-JP"];
5
+ TaLanguageUtil2.NAMES = { "zh-CN": "简体中文", "zh-TW": "繁體中文", "en-US": "English", "ja-JP": "日本語" };
6
+ function of(tag) {
7
+ const said = (tag !== null && tag !== undefined ? tag : "").toLowerCase().replace(/_/g, "-");
8
+ if (/^zh(\b|-)/.test(said)) {
9
+ return /-hant\b/.test(said) || !/-hans\b/.test(said) && /-(tw|hk|mo)\b/.test(said) ? "zh-TW" : "zh-CN";
10
+ }
11
+ return /^ja(\b|-)/.test(said) ? "ja-JP" : "en-US";
12
+ }
13
+ TaLanguageUtil2.of = of;
14
+ function server(env = typeof process === "undefined" ? {} : process.env) {
15
+ return of(env.TA_LANGUAGE || env.LC_ALL || env.LC_MESSAGES || env.LANG);
16
+ }
17
+ TaLanguageUtil2.server = server;
18
+ function pick(language, words) {
19
+ return words[of(language)];
20
+ }
21
+ TaLanguageUtil2.pick = pick;
22
+ function say(words) {
23
+ return words[server()];
24
+ }
25
+ TaLanguageUtil2.say = say;
26
+ function chinese(language) {
27
+ return of(language).startsWith("zh");
28
+ }
29
+ TaLanguageUtil2.chinese = chinese;
30
+ function cjk(language) {
31
+ return of(language) !== "en-US";
32
+ }
33
+ TaLanguageUtil2.cjk = cjk;
34
+ function list(language, items) {
35
+ return items.join(cjk(language) ? "、" : ", ");
36
+ }
37
+ TaLanguageUtil2.list = list;
38
+ })(TaLanguageUtil || (TaLanguageUtil = {}));
39
+
40
+ // web-src/i18n.ts
41
+ var EN = {
42
+ boardTitle: "This round",
43
+ finished: "{done} of {all} finished",
44
+ noneYet: "Nobody finished yet",
45
+ missedBy: "{n} missed",
46
+ classNext: "Next round, for everyone",
47
+ classNextText: "Everyone played “{title}”: {done} of {all} finished{avg}.{topics} Make the next round for all of us from it: harder where most did well, what many missed again in another way. A game for several, to play together again.",
48
+ avgText: ", {score}/{total} on average",
49
+ topicsText: " Missed most: {list}.",
50
+ topicCount: "{topic} ({n})",
51
+ you: "You",
52
+ mistake: "{topic} ({note})",
53
+ listSep: "; ",
54
+ untitled: "A game",
55
+ making: "Making the game…",
56
+ lines: "{n} lines so far",
57
+ start: "Play",
58
+ restart: "Again",
59
+ close: "Close",
60
+ full: "Full screen",
61
+ together: "Play together",
62
+ players: "{min}–{max} players",
63
+ playersFrom: "{min}+ players",
64
+ pickRoom: "Play in which chat",
65
+ noRooms: "No group chats yet",
66
+ noRoomsHint: "Make one in Group chats, then come back",
67
+ members: "{n} people",
68
+ tooBig: "Too big to send to a chat",
69
+ sent: "In “{room}”: the others join from Games in its apps",
70
+ said: "Started the game “{title}”: join from Games in the apps of this chat",
71
+ score: "This round: {score}/{total}",
72
+ points: "This round: {score}",
73
+ missed: "{n} to work on",
74
+ next: "Next round, from this one",
75
+ nextText: "I finished “{title}”{score}.{summary}{mistakes} Make me the next round from it: harder where I did well, what I missed again in another way.",
76
+ scoreText: ": {score}/{total}",
77
+ pointsText: ": {score}",
78
+ mistakesText: " I missed: {list}.",
79
+ failed: "The game went wrong: {message}",
80
+ fix: "Have Ta fix it",
81
+ fixText: "“{title}” went wrong as I played: {message}. Fix it and send it again.",
82
+ app: "Games",
83
+ appNone: "None playing",
84
+ appPlaying: "Playing “{title}”",
85
+ line: "{name} started “{title}” · tap to join",
86
+ roomEmpty: "No game in this chat",
87
+ roomEmptyHint: "Ask Ta for one in a conversation and tap Play together on it",
88
+ join: "Join",
89
+ safe: "Games run apart: they cannot see your files or conversations",
90
+ by: "Started by {name} · {online} online",
91
+ end: "End the game",
92
+ sendFailed: "Could not send it: {message}",
93
+ joinFailed: "Could not join: {message}"
94
+ };
95
+ var ZH = {
96
+ boardTitle: "本局成绩",
97
+ finished: "{done}/{all} 人玩完",
98
+ noneYet: "还没人玩完",
99
+ missedBy: "错 {n} 处",
100
+ classNext: "按全班出下一局",
101
+ classNextText: "大家玩完了《{title}》:{done}/{all} 人玩完{avg}。{topics}按全班的情况出下一局,大家再一起玩:多数人会的加点难度,错得多的换个玩法再练。",
102
+ avgText: ",平均 {score}/{total}",
103
+ topicsText: "错得多的:{list}。",
104
+ topicCount: "{topic}({n} 人)",
105
+ you: "你",
106
+ mistake: "{topic}({note})",
107
+ listSep: ";",
108
+ untitled: "小游戏",
109
+ making: "正在做游戏…",
110
+ lines: "已写 {n} 行",
111
+ start: "开始",
112
+ restart: "重来",
113
+ close: "收起",
114
+ full: "全屏",
115
+ together: "一起玩",
116
+ players: "{min}–{max} 人",
117
+ playersFrom: "{min} 人以上",
118
+ pickRoom: "发到哪个群一起玩",
119
+ noRooms: "还没有群聊",
120
+ noRoomsHint: "在「群聊」里建一个,再回来发",
121
+ members: "{n} 人",
122
+ tooBig: "游戏太大,发不到群里",
123
+ sent: "已发到「{room}」,群里的人从群应用「小游戏」加入",
124
+ said: "发起了小游戏《{title}》,在群应用「小游戏」里加入",
125
+ score: "本局 {score}/{total}",
126
+ points: "本局 {score} 分",
127
+ missed: "{n} 处要再练",
128
+ next: "按这局出下一局",
129
+ nextText: "玩完了《{title}》{score}。{summary}{mistakes}按这局给我出下一局:做得好的加点难度,错的换个玩法再练。",
130
+ scoreText: ",{score}/{total}",
131
+ pointsText: ",{score} 分",
132
+ mistakesText: "错在:{list}。",
133
+ failed: "游戏出错了:{message}",
134
+ fix: "让 Ta 修好",
135
+ fixText: "《{title}》玩的时候出错了:{message}。帮我修好,重新发一版。",
136
+ app: "小游戏",
137
+ appNone: "没在玩",
138
+ appPlaying: "在玩《{title}》",
139
+ line: "{name} 发起了《{title}》 · 点开一起玩",
140
+ roomEmpty: "群里还没有在玩的游戏",
141
+ roomEmptyHint: "在对话里让 Ta 做一个,点卡片上的「一起玩」发到这里",
142
+ join: "加入",
143
+ safe: "游戏在隔离的环境里运行,看不到你的文件和对话",
144
+ by: "{name} 发起 · {online} 人在线",
145
+ end: "结束游戏",
146
+ sendFailed: "发不出去:{message}",
147
+ joinFailed: "加入不了:{message}"
148
+ };
149
+ var ZH_TW = {
150
+ boardTitle: "本局成績",
151
+ finished: "{done}/{all} 人玩完",
152
+ noneYet: "還沒人玩完",
153
+ missedBy: "錯 {n} 處",
154
+ classNext: "照全班出下一局",
155
+ classNextText: "大家玩完了《{title}》:{done}/{all} 人玩完{avg}。{topics}照全班的情況出下一局,大家再一起玩:多數人會的加點難度,錯得多的換個玩法再練。",
156
+ avgText: ",平均 {score}/{total}",
157
+ topicsText: "錯得多的:{list}。",
158
+ topicCount: "{topic}({n} 人)",
159
+ you: "你",
160
+ mistake: "{topic}({note})",
161
+ listSep: ";",
162
+ untitled: "小遊戲",
163
+ making: "正在做遊戲…",
164
+ lines: "已寫 {n} 行",
165
+ start: "開始",
166
+ restart: "重來",
167
+ close: "收起",
168
+ full: "全螢幕",
169
+ together: "一起玩",
170
+ players: "{min}–{max} 人",
171
+ playersFrom: "{min} 人以上",
172
+ pickRoom: "發到哪個群一起玩",
173
+ noRooms: "還沒有群聊",
174
+ noRoomsHint: "在「群聊」裡建一個,再回來發",
175
+ members: "{n} 人",
176
+ tooBig: "遊戲太大,發不到群裡",
177
+ sent: "已發到「{room}」,群裡的人從群應用「小遊戲」加入",
178
+ said: "發起了小遊戲《{title}》,在群應用「小遊戲」裡加入",
179
+ score: "本局 {score}/{total}",
180
+ points: "本局 {score} 分",
181
+ missed: "{n} 處要再練",
182
+ next: "照這局出下一局",
183
+ nextText: "玩完了《{title}》{score}。{summary}{mistakes}照這局幫我出下一局:做得好的加點難度,錯的換個玩法再練。",
184
+ scoreText: ",{score}/{total}",
185
+ pointsText: ",{score} 分",
186
+ mistakesText: "錯在:{list}。",
187
+ failed: "遊戲出錯了:{message}",
188
+ fix: "讓 Ta 修好",
189
+ fixText: "《{title}》玩的時候出錯了:{message}。幫我修好,重新發一版。",
190
+ app: "小遊戲",
191
+ appNone: "沒在玩",
192
+ appPlaying: "在玩《{title}》",
193
+ line: "{name} 發起了《{title}》 · 點開一起玩",
194
+ roomEmpty: "群裡還沒有在玩的遊戲",
195
+ roomEmptyHint: "在對話裡讓 Ta 做一個,點卡片上的「一起玩」發到這裡",
196
+ join: "加入",
197
+ safe: "遊戲在隔離的環境裡執行,看不到你的檔案和對話",
198
+ by: "{name} 發起 · {online} 人在線",
199
+ end: "結束遊戲",
200
+ sendFailed: "發不出去:{message}",
201
+ joinFailed: "加入不了:{message}"
202
+ };
203
+ var JA = {
204
+ boardTitle: "今回の結果",
205
+ finished: "{all} 人中 {done} 人が終了",
206
+ noneYet: "まだ誰も終わっていません",
207
+ missedBy: "間違い {n}",
208
+ classNext: "みんなの結果で次へ",
209
+ classNextText: "みんなで「{title}」を遊びました:{all} 人中 {done} 人が終了{avg}。{topics}みんなの結果をもとに次の回を作ってください。多くができたところは少し難しく、間違いの多かったところは別のやり方で。みんなでまた一緒に遊ぶゲームで。",
210
+ avgText: "(平均 {score}/{total})",
211
+ topicsText: "間違いが多かった:{list}。",
212
+ topicCount: "{topic}({n} 人)",
213
+ you: "あなた",
214
+ mistake: "{topic}({note})",
215
+ listSep: "、",
216
+ untitled: "ミニゲーム",
217
+ making: "ゲームを作成中…",
218
+ lines: "{n} 行まで",
219
+ start: "遊ぶ",
220
+ restart: "もう一度",
221
+ close: "閉じる",
222
+ full: "全画面",
223
+ together: "みんなで遊ぶ",
224
+ players: "{min}–{max} 人",
225
+ playersFrom: "{min} 人以上",
226
+ pickRoom: "どのチャットで遊ぶ",
227
+ noRooms: "グループチャットはまだありません",
228
+ noRoomsHint: "「グループチャット」で作ってから戻ってください",
229
+ members: "{n} 人",
230
+ tooBig: "大きすぎてチャットに送れません",
231
+ sent: "「{room}」に送りました。ほかの人はアプリの「ミニゲーム」から参加します",
232
+ said: "ミニゲーム「{title}」を始めました。このチャットのアプリ「ミニゲーム」から参加できます",
233
+ score: "今回 {score}/{total}",
234
+ points: "今回 {score} 点",
235
+ missed: "練習したいところ {n} 件",
236
+ next: "これをもとに次へ",
237
+ nextText: "「{title}」を遊び終えました{score}。{summary}{mistakes}これをもとに次の回を作ってください。できたところは少し難しく、間違えたところは別のやり方でもう一度。",
238
+ scoreText: "({score}/{total})",
239
+ pointsText: "({score} 点)",
240
+ mistakesText: "間違えたところ:{list}。",
241
+ failed: "ゲームでエラーが起きました:{message}",
242
+ fix: "Ta に直してもらう",
243
+ fixText: "「{title}」を遊んでいてエラーが起きました:{message}。直してもう一度送ってください。",
244
+ app: "ミニゲーム",
245
+ appNone: "遊んでいません",
246
+ appPlaying: "「{title}」で遊び中",
247
+ line: "{name} が「{title}」を始めました · タップで参加",
248
+ roomEmpty: "このチャットで遊んでいるゲームはありません",
249
+ roomEmptyHint: "会話で Ta に作ってもらい、カードの「みんなで遊ぶ」でここに送ってください",
250
+ join: "参加",
251
+ safe: "ゲームは隔離された環境で動き、ファイルや会話は見えません",
252
+ by: "{name} が開始 · {online} 人オンライン",
253
+ end: "ゲームを終える",
254
+ sendFailed: "送れません:{message}",
255
+ joinFailed: "参加できません:{message}"
256
+ };
257
+ var WORDS = { "zh-CN": ZH, "zh-TW": ZH_TW, "en-US": EN, "ja-JP": JA };
258
+ var PlayWords;
259
+ ((PlayWords) => {
260
+ function of(language) {
261
+ return TaLanguageUtil.pick(language, WORDS);
262
+ }
263
+ PlayWords.of = of;
264
+ function fill(text, params = {}) {
265
+ return text.replace(/\{(\w+)\}/g, (all, name) => (name in params) ? String(params[name]) : all);
266
+ }
267
+ PlayWords.fill = fill;
268
+ })(PlayWords ||= {});
269
+
270
+ // web-src/play-protocol.ts
271
+ var LANGUAGE = "ta-play";
272
+ var GAME_KEY = "play:game";
273
+ function stateKey(game, key = "") {
274
+ return `play:${game}:${key}`;
275
+ }
276
+ var RESULT_PREFIX = "~result:";
277
+ function resultKey(game, member) {
278
+ return stateKey(game, RESULT_PREFIX + member);
279
+ }
280
+ var LIMITS = {
281
+ html: 48000,
282
+ key: 64,
283
+ value: 16000,
284
+ keys: 200,
285
+ perSecond: 20
286
+ };
287
+
288
+ // web-src/play-doc.ts
289
+ var PLAY_CSP = "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:; connect-src 'none'; form-action 'none'; frame-src 'none'";
290
+ var PLAY_SANDBOX = "allow-scripts";
291
+ var PLAY_BRIDGE = `(function(){
292
+ var on={},ready,ta={me:null,players:[],state:{},solo:true,saved:undefined,
293
+ ready:new Promise(function(r){ready=r}),
294
+ on:function(t,f){(on[t]=on[t]||[]).push(f)},
295
+ set:function(k,v){if(v===null||v===undefined)delete ta.state[k];else ta.state[k]=v;post({type:'set',key:String(k),value:v===undefined?null:v})},
296
+ send:function(d,to){post({type:'send',data:d,to:to})},
297
+ save:function(v){ta.saved=v;post({type:'save',value:v})},
298
+ finish:function(r){post({type:'finish',result:r||{}})}};
299
+ function post(m){m.ta=1;try{parent.postMessage(m,'*')}catch(e){}}
300
+ function emit(t,a){(on[t]||[]).forEach(function(f){try{f.apply(null,a)}catch(e){console.error(e)}})}
301
+ addEventListener('message',function(e){var m=e.data;if(e.source!==parent||!m||m.ta!==1)return;
302
+ if(m.type==='init'){ta.me=m.me;ta.players=m.players;ta.state=m.state||{};ta.solo=m.solo;ta.saved=m.saved;ready(ta);emit('ready',[ta])}
303
+ else if(m.type==='state'){if(m.value===null)delete ta.state[m.key];else ta.state[m.key]=m.value;emit('state',[m.key,m.value,m.by])}
304
+ else if(m.type==='message')emit('message',[m.data,m.from])
305
+ else if(m.type==='players'){ta.players=m.players;emit('players',[m.players])}});
306
+ addEventListener('error',function(e){post({type:'error',message:String(e.message||e.type)})});
307
+ addEventListener('unhandledrejection',function(e){post({type:'error',message:String(e.reason&&e.reason.message||e.reason)})});
308
+ try{var m={},s={getItem:function(k){return k in m?m[k]:null},setItem:function(k,v){m[k]=String(v)},removeItem:function(k){delete m[k]},clear:function(){m={}},key:function(i){return Object.keys(m)[i]||null}};Object.defineProperty(s,'length',{get:function(){return Object.keys(m).length}});
309
+ Object.defineProperty(window,'localStorage',{value:s,configurable:true});Object.defineProperty(window,'sessionStorage',{value:s,configurable:true})}catch(e){}
310
+ window.ta=ta;post({type:'hello'});
311
+ })();`;
312
+ var TITLE = /<title[^>]*>([^<]*)<\/title>/i;
313
+ function meta(html, name) {
314
+ const tag = new RegExp(`<meta[^>]*name=["']?${name}["']?[^>]*>`, "i").exec(html)?.[0];
315
+ return tag ? /content=["']([^"']*)["']/i.exec(tag)?.[1]?.trim() : undefined;
316
+ }
317
+ var PlayDocs;
318
+ ((PlayDocs) => {
319
+ function read(code) {
320
+ const html = code.trim().replace(/^`{3,}\s*html\s*\n|\n`{3,}$/gi, "").trim();
321
+ if (!/<(script|body|canvas|svg|div|button)\b/i.test(html)) {
322
+ return;
323
+ }
324
+ const title = TITLE.exec(html)?.[1]?.trim();
325
+ return {
326
+ ...title ? { title: decode(title) } : {},
327
+ ...players(meta(html, "ta-players")),
328
+ aspect: aspect(meta(html, "ta-aspect")),
329
+ html,
330
+ bytes: new TextEncoder().encode(html).length
331
+ };
332
+ }
333
+ PlayDocs.read = read;
334
+ function players(text) {
335
+ const match = text && /^(\d+)\s*(?:([-~–])\s*(\d+)|(\+))?$/.exec(text);
336
+ if (!match) {
337
+ return {};
338
+ }
339
+ const min = Math.min(100, Math.max(1, Number(match[1])));
340
+ const max = match[4] ? 100 : match[3] ? Math.min(100, Math.max(min, Number(match[3]))) : min;
341
+ return max > 1 ? { players: { min, max } } : {};
342
+ }
343
+ function aspect(text) {
344
+ const match = text && /^(\d+(?:\.\d+)?)(?:\s*[/:]\s*(\d+(?:\.\d+)?))?$/.exec(text);
345
+ const value = match ? Number(match[1]) / (match[2] ? Number(match[2]) : 1) : 0.8;
346
+ return Number.isFinite(value) && value > 0 ? Math.min(2, Math.max(0.5, value)) : 0.8;
347
+ }
348
+ function decode(text) {
349
+ return text.replace(/&(amp|lt|gt|quot|#39);/g, (_, name) => ({ amp: "&", lt: "<", gt: ">", quot: '"', "#39": "'" })[name] ?? "");
350
+ }
351
+ function document2(html) {
352
+ return `<!doctype html><html><head><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="${PLAY_CSP}"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"><style>html,body{margin:0;height:100%;overflow:hidden;touch-action:manipulation;-webkit-user-select:none;user-select:none}</style><script>${PLAY_BRIDGE}</script></head>${html}`;
353
+ }
354
+ PlayDocs.document = document2;
355
+ function id(html) {
356
+ let hash = 2166136261;
357
+ for (let index = 0;index < html.length; index++) {
358
+ hash ^= html.charCodeAt(index);
359
+ hash = Math.imul(hash, 16777619) >>> 0;
360
+ }
361
+ return hash.toString(36);
362
+ }
363
+ PlayDocs.id = id;
364
+ function shareable(doc) {
365
+ return doc.bytes <= LIMITS.html;
366
+ }
367
+ PlayDocs.shareable = shareable;
368
+ function result(value) {
369
+ const input = value && typeof value === "object" ? value : {};
370
+ const number = (n) => typeof n === "number" && Number.isFinite(n) ? n : undefined;
371
+ const line = (text, max) => typeof text === "string" && text.trim() ? text.trim().replace(/\s+/g, " ").slice(0, max) : undefined;
372
+ const score = number(input.score);
373
+ const total = number(input.total);
374
+ const summary = line(input.summary, 200);
375
+ const mistakes = (Array.isArray(input.mistakes) ? input.mistakes : []).map((one) => {
376
+ const mistake = one && typeof one === "object" ? one : { topic: one };
377
+ const topic = line(mistake.topic, 60);
378
+ const note = line(mistake.note, 120);
379
+ return topic ? { topic, ...note ? { note } : {} } : undefined;
380
+ }).filter((one) => !!one).slice(0, 10);
381
+ return {
382
+ ...score !== undefined ? { score } : {},
383
+ ...total !== undefined ? { total } : {},
384
+ ...summary ? { summary } : {},
385
+ ...mistakes.length ? { mistakes } : {}
386
+ };
387
+ }
388
+ PlayDocs.result = result;
389
+ })(PlayDocs ||= {});
390
+
391
+ class PlayRate {
392
+ perSecond;
393
+ start = 0;
394
+ count = 0;
395
+ constructor(perSecond = LIMITS.perSecond) {
396
+ this.perSecond = perSecond;
397
+ }
398
+ allow(now = Date.now()) {
399
+ if (now - this.start >= 1000) {
400
+ this.start = now;
401
+ this.count = 0;
402
+ }
403
+ if (this.count >= this.perSecond) {
404
+ return false;
405
+ }
406
+ this.count++;
407
+ return true;
408
+ }
409
+ }
410
+ function playValue(value) {
411
+ try {
412
+ const json = JSON.stringify(value ?? null);
413
+ return json.length <= LIMITS.value ? JSON.parse(json) : undefined;
414
+ } catch {
415
+ return;
416
+ }
417
+ }
418
+
419
+ // web-src/react.ts
420
+ var React;
421
+ function bind(react) {
422
+ React = react;
423
+ }
424
+
425
+ // web-src/play-frame.tsx
426
+ function PlayFrame({ html, game, title, link, saves, aspect, onFinish, onError }) {
427
+ const frame = React.useRef(null);
428
+ const document2 = React.useMemo(() => PlayDocs.document(html), [html]);
429
+ const handlers = React.useRef({ onFinish, onError });
430
+ handlers.current = { onFinish, onError };
431
+ React.useEffect(() => {
432
+ const element = frame.current;
433
+ if (!element) {
434
+ return;
435
+ }
436
+ const writes = new PlayRate;
437
+ const sends = new PlayRate;
438
+ const toGame = (message) => element.contentWindow?.postMessage({ ...message, ta: 1 }, "*");
439
+ let stop;
440
+ const heard = (event) => {
441
+ if (event.source !== element.contentWindow || !element.contentWindow) {
442
+ return;
443
+ }
444
+ const message = event.data;
445
+ if (message?.ta !== 1) {
446
+ return;
447
+ }
448
+ switch (message.type) {
449
+ case "hello":
450
+ stop?.();
451
+ stop = undefined;
452
+ saves.get(game).then((saved) => {
453
+ toGame({ type: "init", me: link.me, players: link.players(), state: link.state(), solo: link.solo, saved: saved ?? null });
454
+ stop = link.listen({
455
+ state: (key, value, by) => toGame({ type: "state", key, value, by }),
456
+ message: (data, from) => toGame({ type: "message", data, from }),
457
+ players: (players) => toGame({ type: "players", players })
458
+ });
459
+ });
460
+ return;
461
+ case "set": {
462
+ const value = playValue(message.value);
463
+ if (typeof message.key === "string" && message.key && message.key.length <= LIMITS.key && value !== undefined && writes.allow()) {
464
+ link.set(message.key, value);
465
+ }
466
+ return;
467
+ }
468
+ case "send": {
469
+ const data = playValue(message.data);
470
+ if (data !== undefined && sends.allow()) {
471
+ link.send(data, typeof message.to === "string" ? message.to : undefined);
472
+ }
473
+ return;
474
+ }
475
+ case "save": {
476
+ const value = playValue(message.value);
477
+ if (value !== undefined && writes.allow()) {
478
+ saves.set(game, value);
479
+ }
480
+ return;
481
+ }
482
+ case "finish": {
483
+ const result = PlayDocs.result(message.result);
484
+ link.finish(result);
485
+ handlers.current.onFinish?.(result);
486
+ return;
487
+ }
488
+ case "error":
489
+ handlers.current.onError?.(String(message.message ?? "").slice(0, 300));
490
+ return;
491
+ }
492
+ };
493
+ window.addEventListener("message", heard);
494
+ return () => {
495
+ window.removeEventListener("message", heard);
496
+ stop?.();
497
+ };
498
+ }, [link, game, saves]);
499
+ return /* @__PURE__ */ React.createElement("iframe", {
500
+ ref: frame,
501
+ className: "tpy-frame",
502
+ title,
503
+ sandbox: PLAY_SANDBOX,
504
+ srcDoc: document2,
505
+ referrerPolicy: "no-referrer",
506
+ style: aspect ? { aspectRatio: String(aspect) } : undefined,
507
+ "data-own-gestures": ""
508
+ });
509
+ }
510
+
511
+ // web-src/play-link.ts
512
+ class SoloLink {
513
+ solo = true;
514
+ me;
515
+ values = {};
516
+ constructor(name) {
517
+ this.me = { id: "me", name, online: true, host: true, self: true };
518
+ }
519
+ players() {
520
+ return [this.me];
521
+ }
522
+ state() {
523
+ return { ...this.values };
524
+ }
525
+ set(key, value) {
526
+ if (value === null) {
527
+ delete this.values[key];
528
+ } else if (key in this.values || Object.keys(this.values).length < LIMITS.keys) {
529
+ this.values[key] = value;
530
+ }
531
+ }
532
+ send() {}
533
+ finish() {}
534
+ listen() {
535
+ return () => {
536
+ return;
537
+ };
538
+ }
539
+ }
540
+
541
+ class RoomLink {
542
+ rooms;
543
+ hear;
544
+ room;
545
+ game;
546
+ values;
547
+ solo = false;
548
+ members;
549
+ prefix;
550
+ constructor(rooms, hear, room, game, values) {
551
+ this.rooms = rooms;
552
+ this.hear = hear;
553
+ this.room = room;
554
+ this.game = game;
555
+ this.values = values;
556
+ this.members = room.members;
557
+ this.prefix = stateKey(game.id);
558
+ }
559
+ static async open(rooms, hear, room, game) {
560
+ const prefix = stateKey(game.id);
561
+ const state = await rooms.getState(room.id, prefix);
562
+ const values = {};
563
+ for (const [key, { value }] of Object.entries(state)) {
564
+ if (key.startsWith(prefix) && value !== null && !key.startsWith(prefix + RESULT_PREFIX)) {
565
+ values[key.slice(prefix.length)] = value;
566
+ }
567
+ }
568
+ return new RoomLink(rooms, hear, room, game, values);
569
+ }
570
+ get me() {
571
+ const self = this.members.find((member) => member.self);
572
+ return self ? this.player(self) : { id: "", name: "", online: true, host: false, self: true };
573
+ }
574
+ players() {
575
+ return this.members.filter((member) => !member.guest).map((member) => this.player(member));
576
+ }
577
+ player(member) {
578
+ return { id: member.member, name: member.name, online: member.online || member.self, host: member.member === this.game.by, self: member.self };
579
+ }
580
+ state() {
581
+ return { ...this.values };
582
+ }
583
+ set(key, value) {
584
+ if (key.startsWith(RESULT_PREFIX)) {
585
+ return;
586
+ }
587
+ if (value === null) {
588
+ delete this.values[key];
589
+ } else if (key in this.values || Object.keys(this.values).length < LIMITS.keys) {
590
+ this.values[key] = value;
591
+ } else {
592
+ return;
593
+ }
594
+ this.rooms.setState(this.room.id, this.prefix + key, value).catch((error) => console.warn("A game could not keep its state:", error));
595
+ }
596
+ send(data, to) {
597
+ this.rooms.send(this.room.id, { "ta-play": this.game.id, data }, to).catch((error) => console.warn("A game could not send:", error));
598
+ }
599
+ finish(result) {
600
+ const self = this.members.find((member) => member.self);
601
+ if (!self) {
602
+ return;
603
+ }
604
+ const value = { ...result, name: self.name, at: Date.now() };
605
+ this.rooms.setState(this.room.id, resultKey(this.game.id, self.member), value).catch((error) => console.warn("A game could not keep its result:", error));
606
+ }
607
+ listen(listener) {
608
+ const self = () => this.members.find((member) => member.self)?.member;
609
+ return this.hear?.((event) => {
610
+ if (event.type === "rooms") {
611
+ this.rooms.listRooms().then((rooms) => {
612
+ const room = rooms.find((one) => one.id === this.room.id);
613
+ if (room && RoomLink.changed(this.members, room.members)) {
614
+ this.members = room.members;
615
+ listener.players(this.players());
616
+ }
617
+ });
618
+ return;
619
+ }
620
+ if (event.type === "state" && event.room === this.room.id && event.key.startsWith(this.prefix) && !event.key.startsWith(this.prefix + RESULT_PREFIX) && event.by !== self()) {
621
+ const key = event.key.slice(this.prefix.length);
622
+ if (event.value === null) {
623
+ delete this.values[key];
624
+ } else {
625
+ this.values[key] = event.value;
626
+ }
627
+ listener.state(key, event.value, event.by);
628
+ return;
629
+ }
630
+ if (event.type === "message" && event.room === this.room.id) {
631
+ const data = event.data;
632
+ if (data && typeof data === "object" && data["ta-play"] === this.game.id) {
633
+ listener.message(data.data, event.from);
634
+ }
635
+ }
636
+ }, { messages: true }) ?? (() => {
637
+ return;
638
+ });
639
+ }
640
+ static changed(before, after) {
641
+ const key = (members) => members.map((member) => `${member.member}:${member.name}:${member.online}`).join("|");
642
+ return key(before) !== key(after);
643
+ }
644
+ }
645
+
646
+ class RoomGames {
647
+ rooms;
648
+ hear;
649
+ static TOO_BIG = "too-big";
650
+ static NOT_MEMBER = "not-a-member";
651
+ games = new Map;
652
+ listeners = new Set;
653
+ constructor(rooms, hear) {
654
+ this.rooms = rooms;
655
+ this.hear = hear;
656
+ }
657
+ start() {
658
+ return this.hear?.((event) => this.heard(event), { messages: false, state: [GAME_KEY] }) ?? (() => {
659
+ return;
660
+ });
661
+ }
662
+ subscribe = (listener) => {
663
+ this.listeners.add(listener);
664
+ return () => this.listeners.delete(listener);
665
+ };
666
+ get(room) {
667
+ if (!this.games.has(room)) {
668
+ this.games.set(room, null);
669
+ this.read(room);
670
+ }
671
+ return this.games.get(room) ?? undefined;
672
+ }
673
+ async read(room) {
674
+ try {
675
+ const state = await this.rooms?.getState(room, GAME_KEY);
676
+ this.put(room, state?.[GAME_KEY]?.value);
677
+ } catch {
678
+ this.games.delete(room);
679
+ }
680
+ }
681
+ heard(event) {
682
+ if (event.type === "state" && event.key === GAME_KEY) {
683
+ this.put(event.room, event.value);
684
+ }
685
+ }
686
+ put(room, value) {
687
+ const game = RoomGames.game(value) ?? null;
688
+ const before = this.games.get(room);
689
+ this.games.set(room, game);
690
+ if (before?.id === game?.id && before?.at === game?.at) {
691
+ return;
692
+ }
693
+ for (const listener of this.listeners) {
694
+ listener();
695
+ }
696
+ }
697
+ async begin(room, html, title, said) {
698
+ const self = room.members.find((member) => member.self);
699
+ if (!this.rooms || !self) {
700
+ throw new Error(RoomGames.NOT_MEMBER);
701
+ }
702
+ if (new TextEncoder().encode(html).length > LIMITS.html) {
703
+ throw new Error(RoomGames.TOO_BIG);
704
+ }
705
+ const before = this.games.get(room.id);
706
+ const game = { id: PlayDocs.id(html), title, html, by: self.member, name: self.name, at: Date.now() };
707
+ if (before && before.id !== game.id) {
708
+ await this.clear(room.id, before.id);
709
+ }
710
+ await this.rooms.setState(room.id, GAME_KEY, game);
711
+ this.put(room.id, game);
712
+ if (said) {
713
+ await this.rooms.say(room.id, said).catch(() => {
714
+ return;
715
+ });
716
+ }
717
+ return game;
718
+ }
719
+ async end(room, game) {
720
+ await this.clear(room, game.id);
721
+ if (this.games.get(room)?.id === game.id) {
722
+ await this.rooms?.setState(room, GAME_KEY, null);
723
+ this.put(room, null);
724
+ }
725
+ }
726
+ async clear(room, id) {
727
+ const state = await this.rooms?.getState(room, stateKey(id)) ?? {};
728
+ await Promise.all(Object.keys(state).map((key) => this.rooms?.setState(room, key, null)));
729
+ }
730
+ static mayEnd(room, game) {
731
+ return room.owner || !!room.admin || room.members.some((member) => member.self && member.member === game.by);
732
+ }
733
+ static game(value) {
734
+ const game = value;
735
+ if (!game || typeof game !== "object") {
736
+ return;
737
+ }
738
+ const { id, title, html, by, name, at } = game;
739
+ if (typeof id !== "string" || typeof html !== "string" || typeof by !== "string" || html.length > LIMITS.html * 2) {
740
+ return;
741
+ }
742
+ return {
743
+ id,
744
+ title: typeof title === "string" ? title.slice(0, 80) : "",
745
+ html,
746
+ by,
747
+ name: typeof name === "string" ? name.slice(0, 40) : "",
748
+ at: typeof at === "number" ? at : 0
749
+ };
750
+ }
751
+ }
752
+
753
+ class PlaySaves {
754
+ storage;
755
+ static KEY = "saved";
756
+ static MAX = 50;
757
+ constructor(storage) {
758
+ this.storage = storage;
759
+ }
760
+ async get(game) {
761
+ const all = await this.storage.get(PlaySaves.KEY).catch(() => {
762
+ return;
763
+ }) ?? {};
764
+ return all[game]?.value;
765
+ }
766
+ async set(game, value) {
767
+ const all = await this.storage.get(PlaySaves.KEY).catch(() => {
768
+ return;
769
+ }) ?? {};
770
+ all[game] = { value, at: Date.now() };
771
+ const kept = Object.entries(all).sort(([, a], [, b]) => b.at - a.at).slice(0, PlaySaves.MAX);
772
+ await this.storage.set(PlaySaves.KEY, Object.fromEntries(kept));
773
+ }
774
+ }
775
+
776
+ class RoomResults {
777
+ rooms;
778
+ hear;
779
+ room;
780
+ game;
781
+ results = new Map;
782
+ constructor(rooms, hear, room, game) {
783
+ this.rooms = rooms;
784
+ this.hear = hear;
785
+ this.room = room;
786
+ this.game = game;
787
+ }
788
+ start(changed) {
789
+ const prefix = resultKey(this.game, "");
790
+ let live = true;
791
+ this.rooms.getState(this.room, prefix).then((state) => {
792
+ for (const [key, { value }] of Object.entries(state)) {
793
+ this.put(key.slice(prefix.length), value);
794
+ }
795
+ if (live) {
796
+ changed(this.list());
797
+ }
798
+ }).catch(() => {
799
+ return;
800
+ });
801
+ const stop = this.hear?.((event) => {
802
+ if (event.type === "state" && event.room === this.room && event.key.startsWith(prefix)) {
803
+ this.put(event.key.slice(prefix.length), event.value);
804
+ changed(this.list());
805
+ }
806
+ }, { messages: false, state: [prefix] }) ?? (() => {
807
+ return;
808
+ });
809
+ return () => {
810
+ live = false;
811
+ stop();
812
+ };
813
+ }
814
+ put(member, value) {
815
+ const result = RoomResults.result(value);
816
+ if (result && member) {
817
+ this.results.set(member, { ...result, member });
818
+ } else {
819
+ this.results.delete(member);
820
+ }
821
+ }
822
+ list() {
823
+ return [...this.results.values()].sort((a, b) => (b.score ?? -1) - (a.score ?? -1) || a.at - b.at);
824
+ }
825
+ static result(value) {
826
+ if (!value || typeof value !== "object") {
827
+ return;
828
+ }
829
+ const input = value;
830
+ const name = typeof input.name === "string" ? input.name.slice(0, 40) : "";
831
+ const at = typeof input.at === "number" ? input.at : 0;
832
+ return { ...PlayDocs.result(value), name, at };
833
+ }
834
+ static topics(results) {
835
+ const counts = new Map;
836
+ for (const result of results) {
837
+ for (const topic of new Set((result.mistakes ?? []).map((one) => one.topic))) {
838
+ counts.set(topic, (counts.get(topic) ?? 0) + 1);
839
+ }
840
+ }
841
+ return [...counts.entries()].map(([topic, count]) => ({ topic, count })).sort((a, b) => b.count - a.count).slice(0, 5);
842
+ }
843
+ }
844
+
845
+ // web-src/play-text.ts
846
+ var PlayText;
847
+ ((PlayText) => {
848
+ function score(words, result) {
849
+ const parts = [
850
+ result.score !== undefined && (result.total !== undefined ? PlayWords.fill(words.score, { score: result.score, total: result.total }) : PlayWords.fill(words.points, { score: result.score })),
851
+ result.mistakes?.length && PlayWords.fill(words.missed, { n: result.mistakes.length })
852
+ ].filter((part) => !!part);
853
+ return parts.length ? parts.join(" · ") : undefined;
854
+ }
855
+ PlayText.score = score;
856
+ function next(words, title, result) {
857
+ const score2 = result.score === undefined ? "" : result.total !== undefined ? PlayWords.fill(words.scoreText, { score: result.score, total: result.total }) : PlayWords.fill(words.pointsText, { score: result.score });
858
+ const list = (result.mistakes ?? []).map((one) => one.note ? PlayWords.fill(words.mistake, { topic: one.topic, note: one.note }) : one.topic).join(words.listSep);
859
+ return PlayWords.fill(words.nextText, {
860
+ title,
861
+ score: score2,
862
+ summary: result.summary ? `${result.summary.replace(/[。.!!]$/, "")}。` : "",
863
+ mistakes: list ? PlayWords.fill(words.mistakesText, { list }) : ""
864
+ }).replace(/\s{2,}/g, " ");
865
+ }
866
+ PlayText.next = next;
867
+ function fix(words, title, message) {
868
+ return PlayWords.fill(words.fixText, { title, message });
869
+ }
870
+ PlayText.fix = fix;
871
+ function classNext(words, title, results, all) {
872
+ const scored = results.filter((one) => one.score !== undefined);
873
+ const total = scored.find((one) => one.total !== undefined)?.total;
874
+ const mean = scored.length ? Math.round(scored.reduce((sum, one) => sum + (one.score ?? 0), 0) / scored.length * 10) / 10 : undefined;
875
+ const avg = mean === undefined || total === undefined ? "" : PlayWords.fill(words.avgText, { score: mean, total });
876
+ const list = RoomResults.topics(results).map((one) => PlayWords.fill(words.topicCount, { topic: one.topic, n: one.count })).join(words.listSep);
877
+ return PlayWords.fill(words.classNextText, {
878
+ title,
879
+ done: results.length,
880
+ all: Math.max(all, results.length),
881
+ avg,
882
+ topics: list ? PlayWords.fill(words.topicsText, { list }) : ""
883
+ }).replace(/\s{2,}/g, " ");
884
+ }
885
+ PlayText.classNext = classNext;
886
+ })(PlayText ||= {});
887
+
888
+ // web-src/play-card.tsx
889
+ function playParts(pi) {
890
+ const icons = pi.ui.icons;
891
+ function Icon({ name, size = 16 }) {
892
+ const Shape = icons[name];
893
+ return Shape ? /* @__PURE__ */ React.createElement(Shape, {
894
+ size
895
+ }) : null;
896
+ }
897
+ function useBusy() {
898
+ const [busy, setBusy] = React.useState(false);
899
+ const fallback = React.useCallback(async (action) => {
900
+ setBusy(true);
901
+ try {
902
+ return await action();
903
+ } finally {
904
+ setBusy(false);
905
+ }
906
+ }, []);
907
+ return pi.ui.useBusy?.() ?? [busy, fallback];
908
+ }
909
+ function Button({
910
+ icon,
911
+ label,
912
+ onClick,
913
+ primary,
914
+ disabled,
915
+ title
916
+ }) {
917
+ const [busy, run] = useBusy();
918
+ return /* @__PURE__ */ React.createElement("button", {
919
+ type: "button",
920
+ className: busy ? "tpy-btn ta-busy" : "tpy-btn",
921
+ "data-primary": primary ? "" : undefined,
922
+ disabled,
923
+ title,
924
+ onClick: () => void run(onClick)
925
+ }, busy && /* @__PURE__ */ React.createElement("span", {
926
+ className: primary ? "ta-spinner ta-busy-mark ta-on-brand" : "ta-spinner ta-busy-mark"
927
+ }), icon && /* @__PURE__ */ React.createElement(Icon, {
928
+ name: icon,
929
+ size: 15
930
+ }), label);
931
+ }
932
+ function After({ words, result, error, next, fix }) {
933
+ const score = result && PlayText.score(words, result);
934
+ return /* @__PURE__ */ React.createElement(React.Fragment, null, result && (score || result.summary) && /* @__PURE__ */ React.createElement("div", {
935
+ className: "tpy-line"
936
+ }, /* @__PURE__ */ React.createElement("span", null, score && /* @__PURE__ */ React.createElement("span", {
937
+ className: "tpy-score"
938
+ }, score), score && result.summary && " · ", result.summary), next && /* @__PURE__ */ React.createElement(Button, {
939
+ icon: "Sparkles",
940
+ label: words.next,
941
+ onClick: next,
942
+ primary: true
943
+ })), error && /* @__PURE__ */ React.createElement("div", {
944
+ className: "tpy-line",
945
+ "data-tone": "bad"
946
+ }, /* @__PURE__ */ React.createElement("span", null, PlayWords.fill(words.failed, { message: error })), fix && /* @__PURE__ */ React.createElement(Button, {
947
+ icon: "Wrench",
948
+ label: words.fix,
949
+ onClick: fix
950
+ })));
951
+ }
952
+ function Full({
953
+ title,
954
+ words,
955
+ onClose,
956
+ onRestart,
957
+ children
958
+ }) {
959
+ const FullScreen = pi.ui.FullScreen;
960
+ const body = /* @__PURE__ */ React.createElement("div", {
961
+ className: "tpy-full"
962
+ }, /* @__PURE__ */ React.createElement("div", {
963
+ className: "tpy-full-bar"
964
+ }, /* @__PURE__ */ React.createElement("button", {
965
+ type: "button",
966
+ className: "tpy-icon-btn",
967
+ "aria-label": words.close,
968
+ onClick: onClose
969
+ }, /* @__PURE__ */ React.createElement(Icon, {
970
+ name: "X",
971
+ size: 20
972
+ })), /* @__PURE__ */ React.createElement("span", {
973
+ className: "tpy-title"
974
+ }, title), /* @__PURE__ */ React.createElement("button", {
975
+ type: "button",
976
+ className: "tpy-icon-btn",
977
+ "aria-label": words.restart,
978
+ onClick: onRestart
979
+ }, /* @__PURE__ */ React.createElement(Icon, {
980
+ name: "RotateCcw",
981
+ size: 18
982
+ }))), /* @__PURE__ */ React.createElement("div", {
983
+ className: "tpy-fill"
984
+ }, children), /* @__PURE__ */ React.createElement("div", {
985
+ className: "tpy-full-foot"
986
+ }));
987
+ return FullScreen ? /* @__PURE__ */ React.createElement(FullScreen, null, body) : body;
988
+ }
989
+ function RoomPicker({ words, onPick, onClose }) {
990
+ const [rooms, setRooms] = React.useState();
991
+ const [busy, run] = useBusy();
992
+ const [picked, setPicked] = React.useState();
993
+ React.useEffect(() => {
994
+ let live = true;
995
+ pi.rooms?.listRooms().then((all) => live && setRooms(all.filter((room) => room.status === "member" && !room.unlisted))).catch(() => live && setRooms([]));
996
+ return () => {
997
+ live = false;
998
+ };
999
+ }, []);
1000
+ const Empty = pi.ui.Empty;
1001
+ return /* @__PURE__ */ React.createElement(pi.ui.Dialog, {
1002
+ title: words.pickRoom,
1003
+ onClose
1004
+ }, !rooms ? /* @__PURE__ */ React.createElement(pi.ui.Loading, null) : rooms.length ? /* @__PURE__ */ React.createElement("div", {
1005
+ className: "tpy-rooms"
1006
+ }, rooms.map((room) => /* @__PURE__ */ React.createElement("button", {
1007
+ key: room.id,
1008
+ type: "button",
1009
+ className: "tpy-room",
1010
+ disabled: busy,
1011
+ onClick: () => {
1012
+ setPicked(room.id);
1013
+ run(() => onPick(room));
1014
+ }
1015
+ }, busy && picked === room.id ? /* @__PURE__ */ React.createElement("span", {
1016
+ className: "ta-spinner ta-later"
1017
+ }) : /* @__PURE__ */ React.createElement(Icon, {
1018
+ name: "Users"
1019
+ }), /* @__PURE__ */ React.createElement("span", {
1020
+ className: "tpy-room-name"
1021
+ }, room.title), /* @__PURE__ */ React.createElement("span", {
1022
+ className: "tpy-muted"
1023
+ }, PlayWords.fill(words.members, { n: room.members.length }))))) : /* @__PURE__ */ React.createElement(Empty, {
1024
+ compact: true,
1025
+ title: words.noRooms,
1026
+ hint: words.noRoomsHint
1027
+ }));
1028
+ }
1029
+ function Results({
1030
+ words,
1031
+ room,
1032
+ game,
1033
+ host,
1034
+ title,
1035
+ send
1036
+ }) {
1037
+ const [results, setResults] = React.useState([]);
1038
+ React.useEffect(() => new RoomResults(pi.rooms, pi.onRoomEvent?.bind(pi), room.id, game).start(setResults), [room.id, game]);
1039
+ const all = room.members.filter((member) => !member.guest).length;
1040
+ const count = results.length ? PlayWords.fill(words.finished, { done: results.length, all: Math.max(all, results.length) }) : words.noneYet;
1041
+ if (!host) {
1042
+ return /* @__PURE__ */ React.createElement("div", {
1043
+ className: "tpy-line tpy-muted"
1044
+ }, count);
1045
+ }
1046
+ const topics = RoomResults.topics(results);
1047
+ return /* @__PURE__ */ React.createElement("div", {
1048
+ className: "tpy-board"
1049
+ }, /* @__PURE__ */ React.createElement("div", {
1050
+ className: "tpy-board-head"
1051
+ }, /* @__PURE__ */ React.createElement("span", {
1052
+ className: "tpy-title"
1053
+ }, words.boardTitle), /* @__PURE__ */ React.createElement("span", {
1054
+ className: "tpy-muted"
1055
+ }, count)), results.map((one) => /* @__PURE__ */ React.createElement("div", {
1056
+ key: one.member,
1057
+ className: "tpy-board-row"
1058
+ }, /* @__PURE__ */ React.createElement("span", {
1059
+ className: "tpy-room-name"
1060
+ }, one.name), !!one.mistakes?.length && /* @__PURE__ */ React.createElement("span", {
1061
+ className: "tpy-muted"
1062
+ }, PlayWords.fill(words.missedBy, { n: one.mistakes.length })), /* @__PURE__ */ React.createElement("span", {
1063
+ className: "tpy-score"
1064
+ }, one.score === undefined ? "" : one.total === undefined ? one.score : `${one.score}/${one.total}`))), !!topics.length && /* @__PURE__ */ React.createElement("div", {
1065
+ className: "tpy-muted"
1066
+ }, PlayWords.fill(words.topicsText, {
1067
+ list: topics.map((one) => PlayWords.fill(words.topicCount, { topic: one.topic, n: one.count })).join(words.listSep)
1068
+ }).trim()), send && !!results.length && /* @__PURE__ */ React.createElement("div", {
1069
+ className: "tpy-bar"
1070
+ }, /* @__PURE__ */ React.createElement(Button, {
1071
+ icon: "Sparkles",
1072
+ label: words.classNext,
1073
+ primary: true,
1074
+ onClick: () => send(PlayText.classNext(words, title, results, all))
1075
+ })));
1076
+ }
1077
+ return { Icon, Button, After, Full, RoomPicker, Results };
1078
+ }
1079
+ function playCard(pi, parts, games, saves) {
1080
+ const { Icon, Button, After, Full, RoomPicker, Results } = parts;
1081
+ function Card({ code, closed, send }) {
1082
+ const words = PlayWords.of(pi.ui.language);
1083
+ const doc = React.useMemo(() => closed ? PlayDocs.read(code) : undefined, [code, closed]);
1084
+ const compact = (pi.ui.useDevice?.().layout ?? "expanded") === "compact";
1085
+ const [playing, setPlaying] = React.useState(false);
1086
+ const [run, setRun] = React.useState(0);
1087
+ const [result, setResult] = React.useState();
1088
+ const [error, setError] = React.useState();
1089
+ const [together, setTogether] = React.useState();
1090
+ const [picking, setPicking] = React.useState(false);
1091
+ const [note, setNote] = React.useState();
1092
+ const solo = React.useMemo(() => new SoloLink(words.you), [words.you]);
1093
+ const stage = React.useRef(null);
1094
+ if (!closed) {
1095
+ return /* @__PURE__ */ React.createElement("div", {
1096
+ className: "tpy-card tpy-making"
1097
+ }, /* @__PURE__ */ React.createElement(Icon, {
1098
+ name: "Gamepad2"
1099
+ }), /* @__PURE__ */ React.createElement("span", null, words.making), /* @__PURE__ */ React.createElement("span", {
1100
+ className: "tpy-muted"
1101
+ }, PlayWords.fill(words.lines, { n: code.split(`
1102
+ `).length })));
1103
+ }
1104
+ if (!doc) {
1105
+ throw new Error("This block holds no game");
1106
+ }
1107
+ const title = doc.title ?? words.untitled;
1108
+ const link = together?.link ?? solo;
1109
+ const play = () => {
1110
+ setResult(undefined);
1111
+ setError(undefined);
1112
+ setRun((n) => n + 1);
1113
+ setPlaying(true);
1114
+ };
1115
+ const start = async (room) => {
1116
+ try {
1117
+ const game = await games.begin(room, doc.html, title, PlayWords.fill(words.said, { title }));
1118
+ const link2 = await RoomLink.open(pi.rooms, pi.onRoomEvent?.bind(pi), room, game);
1119
+ setTogether({ room, game, link: link2 });
1120
+ setNote(PlayWords.fill(words.sent, { room: room.title }));
1121
+ play();
1122
+ } catch (failure) {
1123
+ const message = failure instanceof Error ? failure.message : String(failure);
1124
+ setNote(message === RoomGames.TOO_BIG ? words.tooBig : PlayWords.fill(words.sendFailed, { message }));
1125
+ }
1126
+ setPicking(false);
1127
+ };
1128
+ const frame = /* @__PURE__ */ React.createElement(PlayFrame, {
1129
+ key: run,
1130
+ html: doc.html,
1131
+ game: together?.game.id ?? PlayDocs.id(doc.html),
1132
+ title,
1133
+ link,
1134
+ saves,
1135
+ aspect: compact ? undefined : doc.aspect,
1136
+ onFinish: setResult,
1137
+ onError: setError
1138
+ });
1139
+ const fullScreen = !compact && typeof document !== "undefined" && !!document.fullscreenEnabled;
1140
+ return /* @__PURE__ */ React.createElement("div", {
1141
+ className: "tpy-card",
1142
+ "data-compact": compact ? "" : undefined
1143
+ }, /* @__PURE__ */ React.createElement("div", {
1144
+ className: "tpy-head"
1145
+ }, /* @__PURE__ */ React.createElement(Icon, {
1146
+ name: "Gamepad2"
1147
+ }), /* @__PURE__ */ React.createElement("span", {
1148
+ className: "tpy-title"
1149
+ }, title), doc.players && /* @__PURE__ */ React.createElement("span", {
1150
+ className: "tpy-muted"
1151
+ }, players(words, doc))), playing && !compact ? /* @__PURE__ */ React.createElement("div", {
1152
+ className: "tpy-stage",
1153
+ ref: stage
1154
+ }, frame) : /* @__PURE__ */ React.createElement("button", {
1155
+ type: "button",
1156
+ className: "tpy-cover",
1157
+ style: { aspectRatio: String(doc.aspect) },
1158
+ "aria-label": words.start,
1159
+ onClick: play
1160
+ }, /* @__PURE__ */ React.createElement("span", {
1161
+ className: "tpy-cover-play"
1162
+ }, /* @__PURE__ */ React.createElement(Icon, {
1163
+ name: "Play",
1164
+ size: 26
1165
+ }))), playing && compact && /* @__PURE__ */ React.createElement(Full, {
1166
+ title,
1167
+ words,
1168
+ onClose: () => setPlaying(false),
1169
+ onRestart: () => setRun((n) => n + 1)
1170
+ }, frame), /* @__PURE__ */ React.createElement("div", {
1171
+ className: "tpy-bar"
1172
+ }, playing && !compact ? /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Button, {
1173
+ icon: "RotateCcw",
1174
+ label: words.restart,
1175
+ onClick: () => setRun((n) => n + 1)
1176
+ }), fullScreen && /* @__PURE__ */ React.createElement(Button, {
1177
+ icon: "Maximize2",
1178
+ label: words.full,
1179
+ onClick: () => stage.current?.requestFullscreen?.().catch(() => {
1180
+ return;
1181
+ })
1182
+ }), /* @__PURE__ */ React.createElement(Button, {
1183
+ icon: "X",
1184
+ label: words.close,
1185
+ onClick: () => setPlaying(false)
1186
+ })) : /* @__PURE__ */ React.createElement(Button, {
1187
+ icon: "Play",
1188
+ label: words.start,
1189
+ onClick: play,
1190
+ primary: true
1191
+ }), /* @__PURE__ */ React.createElement("span", {
1192
+ className: "tpy-spacer"
1193
+ }), pi.rooms && !together && /* @__PURE__ */ React.createElement(Button, {
1194
+ icon: "Users",
1195
+ label: words.together,
1196
+ onClick: () => setPicking(true),
1197
+ disabled: !PlayDocs.shareable(doc),
1198
+ title: PlayDocs.shareable(doc) ? undefined : words.tooBig
1199
+ })), note && /* @__PURE__ */ React.createElement("div", {
1200
+ className: "tpy-line tpy-muted"
1201
+ }, note), /* @__PURE__ */ React.createElement(After, {
1202
+ words,
1203
+ result,
1204
+ error,
1205
+ next: send && !together && result ? () => send(PlayText.next(words, title, result)) : undefined,
1206
+ fix: send && error ? () => send(PlayText.fix(words, title, error)) : undefined
1207
+ }), together && /* @__PURE__ */ React.createElement(Results, {
1208
+ words,
1209
+ room: together.room,
1210
+ game: together.game.id,
1211
+ host: true,
1212
+ title,
1213
+ send
1214
+ }), picking && /* @__PURE__ */ React.createElement(RoomPicker, {
1215
+ words,
1216
+ onPick: start,
1217
+ onClose: () => setPicking(false)
1218
+ }));
1219
+ }
1220
+ return Card;
1221
+ }
1222
+ function players(words, doc) {
1223
+ const range = doc.players;
1224
+ if (!range) {
1225
+ return;
1226
+ }
1227
+ return range.max >= 100 ? PlayWords.fill(words.playersFrom, { min: range.min }) : PlayWords.fill(words.players, { min: range.min, max: range.max });
1228
+ }
1229
+
1230
+ // web-src/play-room.tsx
1231
+ function roomPage(pi, parts, games, saves) {
1232
+ const { Icon, Button, After, Results } = parts;
1233
+ function Page({ room }) {
1234
+ const words = PlayWords.of(pi.ui.language);
1235
+ const game = React.useSyncExternalStore(games.subscribe, () => games.get(room.id));
1236
+ const [joined, setJoined] = React.useState();
1237
+ const [failed, setFailed] = React.useState();
1238
+ const [run, setRun] = React.useState(0);
1239
+ const [result, setResult] = React.useState();
1240
+ const [error, setError] = React.useState();
1241
+ const current = joined && game && joined.game.id === game.id ? joined : undefined;
1242
+ if (!game) {
1243
+ return /* @__PURE__ */ React.createElement(pi.ui.Empty, {
1244
+ title: words.roomEmpty,
1245
+ hint: words.roomEmptyHint
1246
+ });
1247
+ }
1248
+ const join = async () => {
1249
+ setFailed(undefined);
1250
+ try {
1251
+ setJoined({ game, link: await RoomLink.open(pi.rooms, pi.onRoomEvent?.bind(pi), room, game) });
1252
+ setResult(undefined);
1253
+ setError(undefined);
1254
+ setRun((n) => n + 1);
1255
+ } catch (failure) {
1256
+ setFailed(PlayWords.fill(words.joinFailed, { message: failure instanceof Error ? failure.message : String(failure) }));
1257
+ }
1258
+ };
1259
+ const online = room.members.filter((member) => !member.guest && (member.online || member.self)).length;
1260
+ const title = game.title || words.untitled;
1261
+ return /* @__PURE__ */ React.createElement("div", {
1262
+ className: "tpy-room-page"
1263
+ }, /* @__PURE__ */ React.createElement("div", {
1264
+ className: "tpy-room-head"
1265
+ }, /* @__PURE__ */ React.createElement(Icon, {
1266
+ name: "Gamepad2",
1267
+ size: 18
1268
+ }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", {
1269
+ className: "tpy-title"
1270
+ }, title), /* @__PURE__ */ React.createElement("div", {
1271
+ className: "tpy-muted"
1272
+ }, PlayWords.fill(words.by, { name: game.name, online }))), current && /* @__PURE__ */ React.createElement(Button, {
1273
+ icon: "RotateCcw",
1274
+ label: words.restart,
1275
+ onClick: () => setRun((n) => n + 1)
1276
+ }), RoomGames.mayEnd(room, game) && /* @__PURE__ */ React.createElement(Button, {
1277
+ icon: "Square",
1278
+ label: words.end,
1279
+ onClick: () => games.end(room.id, game)
1280
+ })), current ? /* @__PURE__ */ React.createElement("div", {
1281
+ className: "tpy-fill"
1282
+ }, /* @__PURE__ */ React.createElement(PlayFrame, {
1283
+ key: run,
1284
+ html: game.html,
1285
+ game: PlayDocs.id(game.html),
1286
+ title,
1287
+ link: current.link,
1288
+ saves,
1289
+ onFinish: setResult,
1290
+ onError: setError
1291
+ })) : /* @__PURE__ */ React.createElement("div", {
1292
+ className: "tpy-room-join"
1293
+ }, /* @__PURE__ */ React.createElement(Button, {
1294
+ icon: "Play",
1295
+ label: words.join,
1296
+ onClick: join,
1297
+ primary: true
1298
+ }), /* @__PURE__ */ React.createElement("span", {
1299
+ className: "tpy-muted"
1300
+ }, failed ?? words.safe)), current && /* @__PURE__ */ React.createElement("div", {
1301
+ style: { padding: "0 12px 10px" }
1302
+ }, /* @__PURE__ */ React.createElement(After, {
1303
+ words,
1304
+ result,
1305
+ error
1306
+ }), /* @__PURE__ */ React.createElement(Results, {
1307
+ words,
1308
+ room,
1309
+ game: game.id,
1310
+ host: RoomGames.mayEnd(room, game),
1311
+ title
1312
+ })));
1313
+ }
1314
+ return Page;
1315
+ }
1316
+
1317
+ // web-src/style.ts
1318
+ var STYLE = `
1319
+ /* A game of a reply (\`\`\`ta-play): its name, a cover to start it or the game in its frame, what to do under it. */
1320
+ .tpy-card {
1321
+ --tpy-s: var(--ta-font-scale, 1);
1322
+ margin: 2px 0 12px;
1323
+ padding: 12px;
1324
+ max-width: 560px;
1325
+ border: 1px solid var(--ta-border);
1326
+ border-radius: 12px;
1327
+ background: var(--ta-card);
1328
+ color: var(--ta-text);
1329
+ font-size: calc(13px * var(--tpy-s));
1330
+ line-height: 1.5;
1331
+ }
1332
+ .tpy-head { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; min-width: 0; }
1333
+ .tpy-head > svg { flex: none; color: var(--ta-accent); }
1334
+ .tpy-title { flex: 1; min-width: 0; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1335
+ .tpy-muted { color: var(--ta-muted); font-size: calc(12px * var(--tpy-s)); }
1336
+ .tpy-making { display: flex; align-items: center; gap: 8px; }
1337
+ .tpy-making > svg { color: var(--ta-accent); animation: tpy-bob 1.2s ease-in-out infinite; }
1338
+ @keyframes tpy-bob { 50% { transform: translateY(-2px) rotate(-8deg); } }
1339
+ .tpy-cover {
1340
+ position: relative;
1341
+ display: flex;
1342
+ align-items: center;
1343
+ justify-content: center;
1344
+ width: 100%;
1345
+ max-height: min(60vh, 520px);
1346
+ border: 0;
1347
+ border-radius: 10px;
1348
+ background:
1349
+ radial-gradient(120% 90% at 20% 10%, color-mix(in srgb, var(--ta-accent) 30%, transparent), transparent 60%),
1350
+ radial-gradient(90% 80% at 90% 100%, color-mix(in srgb, var(--ta-accent) 18%, transparent), transparent 60%),
1351
+ var(--ta-hover);
1352
+ color: var(--ta-text);
1353
+ cursor: pointer;
1354
+ }
1355
+ .tpy-cover-play {
1356
+ display: flex;
1357
+ align-items: center;
1358
+ justify-content: center;
1359
+ width: 56px;
1360
+ height: 56px;
1361
+ border-radius: 50%;
1362
+ background: var(--ta-brand);
1363
+ color: var(--ta-brand-text);
1364
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.18);
1365
+ transition: transform 0.15s;
1366
+ }
1367
+ .tpy-cover:hover .tpy-cover-play { transform: scale(1.06); }
1368
+ .tpy-cover:active .tpy-cover-play { transform: scale(0.96); }
1369
+ .tpy-stage { position: relative; display: flex; justify-content: center; border-radius: 10px; overflow: hidden; background: #000; }
1370
+ .tpy-stage:fullscreen { align-items: center; border-radius: 0; }
1371
+ .tpy-frame { display: block; width: 100%; max-height: min(60vh, 520px); border: 0; background: #fff; }
1372
+ /* On a phone it plays over the whole page: the cover in the reply stays small. */
1373
+ .tpy-card[data-compact] .tpy-cover { max-height: 200px; }
1374
+ .tpy-stage:fullscreen .tpy-frame { width: auto; height: 100%; max-width: 100%; max-height: none; }
1375
+ .tpy-fill { flex: 1; min-height: 0; display: flex; background: #000; }
1376
+ .tpy-fill > .tpy-frame { flex: 1; width: 100%; height: 100%; max-height: none; }
1377
+ .tpy-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 10px; }
1378
+ .tpy-btn {
1379
+ display: inline-flex;
1380
+ align-items: center;
1381
+ gap: 6px;
1382
+ height: 30px;
1383
+ padding: 0 12px;
1384
+ border: 0;
1385
+ border-radius: 8px;
1386
+ background: var(--ta-hover);
1387
+ color: var(--ta-text);
1388
+ font: inherit;
1389
+ cursor: pointer;
1390
+ white-space: nowrap;
1391
+ }
1392
+ .tpy-btn:hover { background: var(--ta-hover-strong); }
1393
+ .tpy-btn[data-primary] { background: var(--ta-brand); color: var(--ta-brand-text); }
1394
+ .tpy-btn[data-primary]:hover { filter: brightness(1.06); }
1395
+ .tpy-btn:disabled { opacity: 0.5; cursor: default; }
1396
+ .tpy-spacer { flex: 1; }
1397
+ .tpy-line { display: flex; align-items: center; gap: 8px; margin-top: 10px; min-width: 0; }
1398
+ .tpy-line > span:first-child { flex: 1; min-width: 0; }
1399
+ .tpy-line[data-tone='bad'] > span:first-child { color: var(--ta-red); }
1400
+ .tpy-score { font-weight: 600; font-variant-numeric: tabular-nums; }
1401
+ /* On a phone: the game over the whole page, a bar to leave it on top. */
1402
+ .tpy-full { display: flex; flex-direction: column; height: 100%; background: #000; }
1403
+ .tpy-full-bar {
1404
+ display: flex;
1405
+ align-items: center;
1406
+ gap: 4px;
1407
+ padding: calc(env(safe-area-inset-top, 0px) + 6px) 8px 6px;
1408
+ background: var(--ta-main);
1409
+ color: var(--ta-text);
1410
+ }
1411
+ .tpy-full-bar .tpy-title { text-align: center; }
1412
+ .tpy-icon-btn { display: flex; align-items: center; justify-content: center; width: 36px; height: 36px; border: 0; border-radius: 8px; background: none; color: inherit; cursor: pointer; }
1413
+ .tpy-icon-btn:active { background: var(--ta-hover); }
1414
+ .tpy-full-foot { padding-bottom: env(safe-area-inset-bottom, 0px); background: #000; }
1415
+ /* The chats to play in. */
1416
+ .tpy-rooms { display: flex; flex-direction: column; gap: 2px; min-width: min(320px, 80vw); max-height: 50vh; overflow: auto; }
1417
+ .tpy-room { display: flex; align-items: center; gap: 10px; padding: 10px; border: 0; border-radius: 8px; background: none; color: var(--ta-text); font: inherit; text-align: left; cursor: pointer; }
1418
+ .tpy-room:hover { background: var(--ta-hover); }
1419
+ .tpy-room-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
1420
+ /* How the players of a room did, for its host. */
1421
+ .tpy-board { display: flex; flex-direction: column; gap: 2px; margin-top: 10px; padding-top: 10px; border-top: 1px solid var(--ta-border); }
1422
+ .tpy-board-head { display: flex; align-items: baseline; gap: 8px; margin-bottom: 4px; }
1423
+ .tpy-board-head .tpy-title { flex: 1; }
1424
+ .tpy-board-row { display: flex; align-items: center; gap: 10px; padding: 4px 0; }
1425
+ .tpy-board-row .tpy-score { min-width: 44px; text-align: right; }
1426
+ /* The game of a room, in its panel. */
1427
+ .tpy-room-page { display: flex; flex-direction: column; height: 100%; min-height: 0; }
1428
+ .tpy-room-head { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--ta-border); }
1429
+ .tpy-room-head > div { flex: 1; min-width: 0; }
1430
+ .tpy-room-join { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; padding: 24px; text-align: center; }
1431
+ `;
1432
+ function injectStyle() {
1433
+ const element = document.createElement("style");
1434
+ element.dataset.taPackage = "ta-play";
1435
+ element.textContent = STYLE;
1436
+ document.head.appendChild(element);
1437
+ return () => element.remove();
1438
+ }
1439
+
1440
+ // web-src/index.tsx
1441
+ function activate(pi) {
1442
+ bind(pi.React);
1443
+ if (!pi.registerCodeRenderer) {
1444
+ return () => {
1445
+ return;
1446
+ };
1447
+ }
1448
+ const removeStyle = injectStyle();
1449
+ const games = new RoomGames(pi.rooms, pi.onRoomEvent?.bind(pi));
1450
+ const saves = new PlaySaves(pi.storage);
1451
+ const parts = playParts(pi);
1452
+ pi.registerCodeRenderer(LANGUAGE, playCard(pi, parts, games, saves), { spoken: (code) => PlayDocs.read(code)?.title });
1453
+ let stopGames = () => {
1454
+ return;
1455
+ };
1456
+ if (pi.rooms) {
1457
+ stopGames = games.start();
1458
+ pi.registerRoomAddon?.({
1459
+ subscribe: games.subscribe,
1460
+ page: roomPage(pi, parts, games, saves),
1461
+ tile: (room) => {
1462
+ if (room.unlisted) {
1463
+ return;
1464
+ }
1465
+ const words = PlayWords.of(pi.ui.language);
1466
+ const game = games.get(room.id);
1467
+ return {
1468
+ label: words.app,
1469
+ icon: "Gamepad2",
1470
+ status: game ? PlayWords.fill(words.appPlaying, { title: game.title || words.untitled }) : words.appNone
1471
+ };
1472
+ },
1473
+ line: (room) => {
1474
+ const game = room.unlisted ? undefined : games.get(room.id);
1475
+ if (!game) {
1476
+ return;
1477
+ }
1478
+ const words = PlayWords.of(pi.ui.language);
1479
+ return { text: PlayWords.fill(words.line, { name: game.name, title: game.title || words.untitled }), icon: "Gamepad2" };
1480
+ }
1481
+ });
1482
+ }
1483
+ return () => {
1484
+ stopGames();
1485
+ removeStyle();
1486
+ };
1487
+ }
1488
+ export {
1489
+ activate as default
1490
+ };