@chatwarden/player-react 0.0.0-stage → 0.1.2

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.
Files changed (94) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +377 -2
  3. package/dist/src/Dialog.d.ts +13 -0
  4. package/dist/src/Dialog.d.ts.map +1 -0
  5. package/dist/src/Dialog.js +94 -0
  6. package/dist/src/Dialog.js.map +1 -0
  7. package/dist/src/FollowUp.d.ts +35 -0
  8. package/dist/src/FollowUp.d.ts.map +1 -0
  9. package/dist/src/FollowUp.js +69 -0
  10. package/dist/src/FollowUp.js.map +1 -0
  11. package/dist/src/MyRecord.d.ts +12 -0
  12. package/dist/src/MyRecord.d.ts.map +1 -0
  13. package/dist/src/MyRecord.js +17 -0
  14. package/dist/src/MyRecord.js.map +1 -0
  15. package/dist/src/NoticeQueue.d.ts +26 -0
  16. package/dist/src/NoticeQueue.d.ts.map +1 -0
  17. package/dist/src/NoticeQueue.js +90 -0
  18. package/dist/src/NoticeQueue.js.map +1 -0
  19. package/dist/src/Picker.d.ts +14 -0
  20. package/dist/src/Picker.d.ts.map +1 -0
  21. package/dist/src/Picker.js +14 -0
  22. package/dist/src/Picker.js.map +1 -0
  23. package/dist/src/ReportDialog.d.ts +50 -0
  24. package/dist/src/ReportDialog.d.ts.map +1 -0
  25. package/dist/src/ReportDialog.js +157 -0
  26. package/dist/src/ReportDialog.js.map +1 -0
  27. package/dist/src/RestrictedChatLine.d.ts +12 -0
  28. package/dist/src/RestrictedChatLine.d.ts.map +1 -0
  29. package/dist/src/RestrictedChatLine.js +19 -0
  30. package/dist/src/RestrictedChatLine.js.map +1 -0
  31. package/dist/src/RulesPage.d.ts +10 -0
  32. package/dist/src/RulesPage.d.ts.map +1 -0
  33. package/dist/src/RulesPage.js +17 -0
  34. package/dist/src/RulesPage.js.map +1 -0
  35. package/dist/src/client.d.ts +51 -0
  36. package/dist/src/client.d.ts.map +1 -0
  37. package/dist/src/client.js +98 -0
  38. package/dist/src/client.js.map +1 -0
  39. package/dist/src/constants.d.ts +5 -0
  40. package/dist/src/constants.d.ts.map +1 -0
  41. package/dist/src/constants.js +5 -0
  42. package/dist/src/constants.js.map +1 -0
  43. package/dist/src/format.d.ts +14 -0
  44. package/dist/src/format.d.ts.map +1 -0
  45. package/dist/src/format.js +55 -0
  46. package/dist/src/format.js.map +1 -0
  47. package/dist/src/hooks.d.ts +15 -0
  48. package/dist/src/hooks.d.ts.map +1 -0
  49. package/dist/src/hooks.js +29 -0
  50. package/dist/src/hooks.js.map +1 -0
  51. package/dist/src/i18n.d.ts +129 -0
  52. package/dist/src/i18n.d.ts.map +1 -0
  53. package/dist/src/i18n.js +167 -0
  54. package/dist/src/i18n.js.map +1 -0
  55. package/dist/src/index.d.ts +21 -0
  56. package/dist/src/index.d.ts.map +1 -0
  57. package/dist/src/index.js +11 -0
  58. package/dist/src/index.js.map +1 -0
  59. package/dist/src/reporting.d.ts +20 -0
  60. package/dist/src/reporting.d.ts.map +1 -0
  61. package/dist/src/reporting.js +45 -0
  62. package/dist/src/reporting.js.map +1 -0
  63. package/dist/src/safeHref.d.ts +5 -0
  64. package/dist/src/safeHref.d.ts.map +1 -0
  65. package/dist/src/safeHref.js +41 -0
  66. package/dist/src/safeHref.js.map +1 -0
  67. package/dist/src/transport.d.ts +69 -0
  68. package/dist/src/transport.d.ts.map +1 -0
  69. package/dist/src/transport.js +74 -0
  70. package/dist/src/transport.js.map +1 -0
  71. package/dist/src/ui.d.ts +91 -0
  72. package/dist/src/ui.d.ts.map +1 -0
  73. package/dist/src/ui.js +116 -0
  74. package/dist/src/ui.js.map +1 -0
  75. package/package.json +73 -4
  76. package/src/Dialog.tsx +117 -0
  77. package/src/FollowUp.tsx +139 -0
  78. package/src/MyRecord.tsx +60 -0
  79. package/src/NoticeQueue.tsx +203 -0
  80. package/src/Picker.tsx +60 -0
  81. package/src/ReportDialog.tsx +304 -0
  82. package/src/RestrictedChatLine.tsx +42 -0
  83. package/src/RulesPage.tsx +49 -0
  84. package/src/client.ts +132 -0
  85. package/src/constants.ts +5 -0
  86. package/src/format.ts +53 -0
  87. package/src/hooks.ts +41 -0
  88. package/src/i18n.ts +187 -0
  89. package/src/index.ts +32 -0
  90. package/src/reporting.ts +51 -0
  91. package/src/safeHref.ts +36 -0
  92. package/src/styles.css +516 -0
  93. package/src/transport.ts +134 -0
  94. package/src/ui.tsx +199 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,378 @@
1
- # Temporary Holding Version
1
+ # @chatwarden/player-react
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The player side of Chatwarden, the open-source chat moderation kit for games: a few small React components a game embeds so a
4
+ player can see what happened to them. A dialog for notices (a warning, a restriction, a ban, a thank-you for a report), a "My
5
+ record" list, the community rules, a dialog to report another player, and one line that says why the chat is off. They talk to the
6
+ kit's player routes through a small injected transport, so the same components run against a real server (`fetch`) or against the
7
+ real routes running in the page (a demo). It is the counterpart of `@chatwarden/hub-react`, which is for your moderators.
8
+
9
+ Status: pre-release, as-is, no support promise.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @chatwarden/player-react @chatwarden/core react react-dom
15
+ ```
16
+
17
+ `react` and `react-dom` (18.3 or 19) are peer dependencies, so your game has one copy of React. The components use only APIs that
18
+ exist in 18.3 (`useId`, `useRef`). The unit and interaction tests run on React 19; the consumer smoke test installs React 18.3, type-checks against
19
+ `@types/react` 18 and renders every component on the server, but clicks and focus have not been exercised on 18. `@chatwarden/core` is a peer too, for its types
20
+ only: no run-time import of it, or of the HTTP package, is in the bundle. Node 22.13 or newer for the tooling; the components
21
+ themselves run in a browser and import no `node:` module.
22
+
23
+ Your server needs `@chatwarden/http` for the routes the components call (`playerRoutes`). The JavaScript is under 15 KB gzipped
24
+ with React external, and the stylesheet under 6 KB.
25
+
26
+ ## Quick start
27
+
28
+ On the server you already mount the kit's player routes (see `@chatwarden/http`). In the game, make a client once and render what you need.
29
+
30
+ ```ts
31
+ import { fetchTransport, createPlayerClient } from '@chatwarden/player-react';
32
+
33
+ // The player routes are mounted at /player on this origin. Cookies go along with each call: the server decides who is asking.
34
+ export const client = createPlayerClient({ transport: fetchTransport({ baseUrl: '/player', credentials: 'same-origin' }) });
35
+
36
+ const notices = await client.notices(); // what is waiting for this player, oldest first
37
+ console.log(notices.length);
38
+ ```
39
+
40
+ ```tsx
41
+ import '@chatwarden/player-react/styles.css';
42
+ import { MyRecord, NoticeQueue, RulesPage } from '@chatwarden/player-react';
43
+ import { client } from './client';
44
+
45
+ export function GameShell({ inMatch }: { inMatch: boolean }) {
46
+ return (
47
+ <>
48
+ {/* Notices wait while a match is on, and open when it ends. */}
49
+ <NoticeQueue client={client} canShow={!inMatch} appealUrl="https://example.com/appeal" />
50
+ <MyRecord client={client} appealUrl="https://example.com/appeal" />
51
+ <RulesPage client={client} />
52
+ </>
53
+ );
54
+ }
55
+ ```
56
+
57
+ How reporting works is the studio's setting (the Reporting section of the moderator hub, or `reporting` in code): one tap, pick a reason
58
+ first, or reason required, with the reasons, their groups and hints, and the thank-you. Read it from `GET /rules` and pass it to the
59
+ dialog. Your server adds the room and the seats and calls the kit:
60
+
61
+ ```ts
62
+ import type { ReportDetailResult, ReportResult } from '@chatwarden/core';
63
+ import type { ReportFollowUp, ReportDraft } from '@chatwarden/player-react';
64
+
65
+ // `cw` is your createChatwarden(...) instance. Call these behind your own routes, for example POST /report and POST /report/:id/detail:
66
+ // `roomId` and the seats come from your session, never from the client.
67
+ export function takeReport(roomId: string, mySeat: string, theirSeat: string, draft: ReportDraft): Promise<ReportResult> {
68
+ return cw.reports.submit({ roomId, reporterSeat: mySeat, targetSeat: theirSeat, ...draft });
69
+ }
70
+
71
+ // The optional follow-up of a one-tap report: a reason and a note, within ten minutes, once, from the reporter only.
72
+ export function addToReport(reportId: string, mySeat: string, detail: ReportFollowUp): Promise<ReportDetailResult> {
73
+ return cw.reports.addDetail(reportId, mySeat, detail);
74
+ }
75
+ ```
76
+
77
+ Load the settings before the dialog is drawn, so it opens in the right flow and never changes under the player's hands. A failed load
78
+ should still give the studio's default (one tap). That is also what the dialog does when it gets no `reporting`, so the fallback below only
79
+ spells it out, with the dialog's own words:
80
+
81
+ ```ts
82
+ import { useEffect, useState } from 'react';
83
+ import type { PlayerClient, PlayerReporting } from '@chatwarden/player-react';
84
+
85
+ /** One tap, no reasons to offer afterwards, the dialog's own thank-you: what a player gets when the settings cannot be loaded. */
86
+ const ONE_TAP: PlayerReporting = { flow: 'one_tap', thanks: '', reasons: [] };
87
+
88
+ /** The studio's reporting settings from `GET /rules`: `undefined` while they load, the one-tap fallback if that fails. */
89
+ export function useReporting(client: PlayerClient): PlayerReporting | undefined {
90
+ const [reporting, setReporting] = useState<PlayerReporting>();
91
+ useEffect(() => {
92
+ let live = true;
93
+ client.rules().then(
94
+ (rules) => live && setReporting(rules.reporting ?? ONE_TAP),
95
+ () => live && setReporting(ONE_TAP),
96
+ );
97
+ return () => {
98
+ live = false;
99
+ };
100
+ }, [client]);
101
+ return reporting;
102
+ }
103
+ ```
104
+
105
+ ```tsx
106
+ import { ReportDialog } from '@chatwarden/player-react';
107
+ import type { PlayerClient } from '@chatwarden/player-react';
108
+
109
+ export function ReportMessage({ client, line, name, close }: { client: PlayerClient; line: string; name: string; close: () => void }) {
110
+ const reporting = useReporting(client);
111
+ if (reporting === undefined) return <p role="status">Loading…</p>;
112
+ return (
113
+ <ReportDialog
114
+ line={line}
115
+ targetName={name}
116
+ reporting={reporting}
117
+ onClose={close}
118
+ onSubmit={(draft) => fetch('/report', { method: 'POST', body: JSON.stringify(draft) }).then((r) => r.json())}
119
+ onAddDetail={(id, detail) => fetch(`/report/${id}/detail`, { method: 'POST', body: JSON.stringify(detail) }).then((r) => r.json())}
120
+ />
121
+ );
122
+ }
123
+ ```
124
+
125
+ - **One tap is the studio's default, applied when you pass `reporting`.** The dialog asks "Report this message?" with the line in quotes and a
126
+ Report button. The report is filed at once and the studio's thank-you is shown. With `onAddDetail` there is then an optional "Add a reason"
127
+ step (a reason and a note) that attaches to the same report, offered until `detailUntil` (the kit's ten minutes). Closing at any point is
128
+ fine: the report is already filed. The heading then reads "Report sent" and the thank-you is announced.
129
+ - **Pick a reason first / reason required.** The reasons in groups, with "Something else" last, then a note when the reason asks for one.
130
+ A reason is optional in the first ("Skip and report") and required in the second.
131
+ - **A reason is a hint.** The kit stores it as `reportedReason`; the moderators (and later the AI) decide what the report really is.
132
+ - **Without `reporting`** the dialog is one tap with its own words and no reasons to offer afterwards: the same as when `GET /rules` cannot be
133
+ loaded. Pass `reporting` before the dialog opens: one that arrives later changes the flow under the player.
134
+ - **Stale settings.** If the studio changes the list while a dialog is open, the kit refuses an unknown reason (`reason_unknown`) or a
135
+ missing one (`reason_required`) and the dialog says so. Read `GET /rules` again before the next report.
136
+
137
+ ## Put it on your server
138
+
139
+ The components call the kit's player routes. The simplest way to run them is to **serve the built game page and the player routes under
140
+ one origin**: the page's calls go to the same host, the player's cookie or session goes along, and there is no CORS to set up.
141
+
142
+ With Express, mount the routes with the adapter from `@chatwarden/http`, then your game's built files:
143
+
144
+ ```ts
145
+ import express from 'express';
146
+ import { playerRoutes } from '@chatwarden/http';
147
+ import type { KitRequest } from '@chatwarden/http';
148
+ import { toExpress } from '@chatwarden/http/express';
149
+
150
+ // `cw` is your createChatwarden(...) instance. Your own sign-in decides who is asking: here, the session cookie your login set.
151
+ declare function keyFromSession(cookie: string | undefined): string | undefined;
152
+
153
+ const app = express();
154
+ app.use(
155
+ '/player',
156
+ toExpress(
157
+ playerRoutes(cw, {
158
+ identify: (req: KitRequest) => ({ clientKey: keyFromSession(req.headers.cookie), ip: req.remoteAddress ?? null }),
159
+ }),
160
+ { fallthrough: false },
161
+ ),
162
+ );
163
+ app.use(express.static('dist/game')); // your built game page, which renders the components
164
+ app.listen(3000);
165
+ ```
166
+
167
+ Any other server works the same way, because the player routes are plain HTTP (`createRouter(playerRoutes(...))` gives you a function from a
168
+ request to a response for any framework; see `@chatwarden/http`). Another origin needs the player routes to answer CORS for the page's
169
+ origin with credentials, and `credentials: 'include'` in the transport.
170
+
171
+ ## Signing players in
172
+
173
+ The components send no identity of their own. Who is asking is decided on the server by the `identify` function you give
174
+ `playerRoutes`: it returns the player's `clientKey` or `accountId` and the real client address, from your session, never from the page.
175
+ Two ways to carry the credential:
176
+
177
+ - **Cookies.** On the same origin the browser sends the page's cookies with each call (`credentials: 'same-origin'` is the default), and
178
+ `identify` reads the session from `req.headers.cookie`.
179
+ - **A header.** `fetchTransport({ baseUrl, headers })` adds the headers to every call (a token your game already has, or a CSRF header).
180
+ The headers are fixed when the transport is made; for a token that changes, make the transport on each call:
181
+
182
+ ```ts
183
+ import { fetchTransport, createPlayerClient } from '@chatwarden/player-react';
184
+ import type { Transport } from '@chatwarden/player-react';
185
+
186
+ declare function currentSessionToken(): string;
187
+
188
+ // A new fetchTransport per call, so the header is always the current token.
189
+ const rotating: Transport = (req) => fetchTransport({ baseUrl: '/player', headers: { 'x-chatwarden-key': currentSessionToken() } })(req);
190
+
191
+ export const client = createPlayerClient({ transport: rotating });
192
+ ```
193
+
194
+ The key in a header or cookie is a credential: keep it out of URLs and logs, and have `identify` read it from there (the kit hashes it and
195
+ keeps nothing raw). A caller `identify` cannot name gets empty lists and a `200`, never someone else's record.
196
+
197
+ ## Content Security Policy
198
+
199
+ The components need no `'unsafe-inline'` and no `'unsafe-eval'`. They inject no `<style>`, set no inline `style` attribute, use no
200
+ `dangerouslySetInnerHTML` and load no third-party resource. Allow:
201
+
202
+ - `script-src`: where your game's bundle is served from.
203
+ - `style-src`: where `styles.css` is served from (`'self'`, or a hash if you inline it yourself).
204
+ - `connect-src`: the origin of the player routes (`'self'` when they are under the same origin, as above).
205
+
206
+ ## Options
207
+
208
+ Every component also takes `t`, `locale`, `now`, `timeZone`, `theme` and `className` (see [Words and languages](#words-and-languages) and
209
+ Theming).
210
+
211
+ ### Components
212
+
213
+ | Component | What it shows | Props besides the common ones |
214
+ | --- | --- | --- |
215
+ | `NoticeQueue` | The pending notices, oldest first, one at a time in a modal dialog. A warning has an Acknowledge button; every other notice has Got it. Both call `POST /notices/:id/ack`. Nothing is rendered when there is nothing to show. | `client`, `canShow` (default `true`), `appealUrl`, `refreshKey`, `onAcknowledged(notice)`, `onPendingChange(count)` |
216
+ | `MyRecord` | What is on the player's record now, newest first, from `GET /record`; or "Your record is clear". | `client`, `appealUrl`, `refreshKey` |
217
+ | `RulesPage` | The summary and the numbered rules from `GET /rules`. The numbers are the kit's: a retired rule leaves a gap. | `client`, `refreshKey` |
218
+ | `ReportDialog` | The studio's report flow (one tap, reason first, reason required) with grouped reasons and an optional note, and an optional "Add a reason" step after a one-tap report. Maps every refusal the kit has to its own plain message and shows how many reports are left today. | `onSubmit(draft)` returning a `ReportResult`, `onClose`, `reporting` (from `GET /rules`), `onAddDetail(reportId, detail)`, `line`, `targetName` |
219
+ | `RestrictedChatLine` | One line for where a chat box would be: why the player cannot type and until when. | `until` (epoch ms or `null`), `byModerator`, `refCode` |
220
+
221
+ - **The hold.** `canShow={false}` keeps notices and shows nothing, so a notice never interrupts a match. They are kept, not dropped and
222
+ not acknowledged, and appear in order when `canShow` turns `true`. The list is asked for once more at that moment, so a warning that
223
+ landed during the match is shown before the next one. `onPendingChange(count)` tells your game how many are waiting.
224
+ - **Focus.** A dialog moves focus to its heading when it opens and keeps it inside: Tab wraps at the ends (a radio group counts as one
225
+ stop), a click on the backdrop does not move focus, and anything outside that takes focus is sent back. When the last notice closes
226
+ focus goes back to what had it. If that element is gone, focus goes to `returnFocusTo()` when you pass one, and otherwise to the page
227
+ body. Escape does not dismiss a notice (it has to be acknowledged); it closes the report dialog, unless a report is on its way.
228
+ - **Acknowledge.** One request at a time: a second click while one is on its way does nothing. A failed request keeps the notice and
229
+ says why, inline; the main button tries again. If it keeps failing, **Close for now** closes the dialog without acknowledging: the
230
+ notices stay pending and come back on the next refresh (`refreshKey`) or the next release of a hold. A 404 means it is already done,
231
+ so the notice closes. A new notice that arrives while the dialog is open is announced to screen readers (`aria-live="polite"`).
232
+ - **The appeal link.** `appealUrl` makes "Think this is a mistake?" a link on a warning, restriction or ban. It must be an `https:`
233
+ address or a relative one (`/appeal`); anything else (`http:`, `javascript:`, `//host`, spaces, control characters, a backslash, an
234
+ entity) is left out. It is the same rule hub-react uses for links, and a test runs both on one table.
235
+ - **The report dialog.** Render it when the player chooses to report, and unmount it in `onClose`. A refusal is a result, not an
236
+ error: `duplicate`, `rate`, `self`, `not_player`, `off` and `suspended` each have their own message. Reject from `onSubmit` only
237
+ when no answer arrived; the dialog keeps what was typed and offers to send again.
238
+ - **Where the dialog is drawn.** It is `position: fixed`, drawn in place. If an ancestor of the component has a `transform`, `filter`,
239
+ `contain` or `will-change: transform`, the browser makes the dialog relative to that ancestor and it can be clipped or off-centre. Pass
240
+ `container={document.body}` (or a layer of your own) to `NoticeQueue` or `ReportDialog` to draw it there instead; the theme and
241
+ `className` still apply, and tokens set on `body` or `:root` reach it (see Theming).
242
+ - **Refreshing.** Change `refreshKey` to ask the server again, for example when your own push channel says a notice is pending.
243
+
244
+ ### `PlayerClient`
245
+
246
+ `createPlayerClient({ transport })` gives four methods over the kit's player routes. They resolve with typed values and reject with a `PlayerError`
247
+ (`status`, `code`, `retryAfter`). The types are the kit's own (`PlayerNotice`, `ReportResult`, `ReportRefusal`).
248
+
249
+ | Method | Route |
250
+ | --- | --- |
251
+ | `notices()` | `GET /notices` |
252
+ | `ack(id)` | `POST /notices/:id/ack` (`true`, or `false` for a notice that is not the caller's or is gone) |
253
+ | `record()` | `GET /record` |
254
+ | `rules()` | `GET /rules` |
255
+
256
+ ### Transports
257
+
258
+ A transport is `(request) => Promise<{ status, headers, body }>`. It resolves for any HTTP status and rejects only when no answer
259
+ arrived. The type is the same as the one in `@chatwarden/hub-react`, written out here so this package does not depend on that one; a
260
+ test keeps the two assignable both ways.
261
+
262
+ - `fetchTransport({ baseUrl, headers?, credentials?, fetch? })`: `fetch` against the routes your server mounts.
263
+ - `routerTransport(handle, { headers? })`: calls `createRouter(playerRoutes(...))` in the same process, for a demo or a test.
264
+
265
+ ### Words and languages
266
+
267
+ Every word the components show is a key in the English catalog (`en`), named `player.<area>.<thing>`. Plural forms add the plural
268
+ category last (`player.report.remaining.one`, `.other`) and are chosen by `Intl.PluralRules` for the `locale`. To translate, spread English
269
+ under your text so a gap falls back to English instead of showing a key:
270
+
271
+ ```ts
272
+ import { createT, en } from '@chatwarden/player-react';
273
+
274
+ const de = { 'player.notice.acknowledge': 'Verstanden', 'player.notice.gotIt': 'Okay' };
275
+ export const t = createT({ ...en, ...de }, 'de');
276
+ ```
277
+
278
+ Pass it as `<NoticeQueue t={t} locale="de" ... />`. Dates and times use `Intl` with the same locale; pass `timeZone="UTC"` to show a
279
+ fixed zone, or leave it out to use the player's own. The copy is written for a player in the middle of a game: second person,
280
+ plain words, never shaming, and it says what happened, until when, and what the player can do.
281
+
282
+ ## Theming
283
+
284
+ The components ship one stylesheet, `@chatwarden/player-react/styles.css`. Import it once (a bundler, or a `<link>`). Every colour, size,
285
+ radius and space is a `--cw-*` custom property, with a light and a dark value, and every rule is scoped under `.cw-player`.
286
+
287
+ - **Three inputs make it yours.** Set `--cw-surface` (the base: panels and the dialog), `--cw-accent` (your next action, links and
288
+ the focus ring) and `--cw-radius` (how round things are) on any element above the components, on `.cw-player`, or on the `className` you
289
+ pass (see "Re-theme it"). Every other token has a default that works on them. The font is yours already: the components inherit it, and `--cw-font` is only there if you want another.
290
+ - **Light and dark.** By default the components follow the player's `prefers-color-scheme`. The `theme` prop (or `data-cw-theme="light"`
291
+ or `"dark"` on `.cw-player` or any ancestor) forces one. Set it from your game's own setting.
292
+ - **Re-theme it.** Set a token on any element above the components (`body`, `:root`, a wrapper around your game's UI), on `.cw-player`, or on
293
+ the `className` you pass: `body { --cw-accent: #7a2e8a }` themes every component alike. The stylesheet never declares a public `--cw-*`
294
+ name on `.cw-player` (that would hide what you set above it): its defaults sit under private `--cwd-*` names at zero specificity
295
+ (`:where(.cw-player)`), so any rule of yours wins whatever its order, and every rule reads `var(--cw-x, var(--cwd-x))`, your value if
296
+ there is one, ours if not. Set `--cw-*` names only; the `--cwd-*` ones are not part of the contract. A dialog drawn into another
297
+ `container` has its own root there, so a value set on a wrapper around the component does not reach it: set the token on `body` or
298
+ `:root`, or on the `className` you pass.
299
+ - **Strict CSP.** The stylesheet is a file. The components inject no `<style>`, set no inline `style` and use no `dangerouslySetInnerHTML`.
300
+ - **Browsers.** The colours use `light-dark()` (Chrome 123, Firefox 120, Safari 17.5, all 2024). Older browsers that lack
301
+ `light-dark()` get the light colours from a fallback block in the stylesheet, so the components keep their colours; they follow
302
+ neither the player's dark setting nor the `theme` prop.
303
+
304
+ ```css
305
+ /* On any element above the components: the whole page, a wrapper around your game's UI, or the className you pass. */
306
+ body {
307
+ --cw-surface: light-dark(#fffaf0, #1d1a14);
308
+ --cw-accent: light-dark(#7a2e8a, #d9a3e6);
309
+ --cw-accent-ink: light-dark(#ffffff, #2a0f31);
310
+ --cw-radius: 2px;
311
+ }
312
+ ```
313
+
314
+ **Colour only where it means something.** The accent is your next action, a link, a choice you made and the focus ring. Red is a failure
315
+ and the red side of a referee card. Yellow is the yellow side of a referee card. Everything else is neutral.
316
+
317
+ The one signature detail is the referee card, the same as in the moderator hub, so a sanction looks the same to staff and to the player:
318
+ a yellow card for a warning, half yellow and half red for a restriction, red for a ban. The words always say the same as the card, so
319
+ colour is never the only signal. Every text token is at least 4.5:1 against every surface it is drawn on, in both themes; a test computes
320
+ it from the values below.
321
+
322
+ | Token | Default (light, dark) | Used for |
323
+ | --- | --- | --- |
324
+ | `--cw-surface` | `#ffffff`, `#151c28` | The base: panels, the dialog, buttons. |
325
+ | `--cw-surface-sunken` | `#eef0f4`, `#111722` | Hover fill, wells, the player's own lines. |
326
+ | `--cw-border` | `#e0e3ea`, `#242d3c` | Hairlines around panels and fields. |
327
+ | `--cw-border-strong` | `#7a8397`, `#6b7893` | The border of a field or a button (3:1 against the surface). |
328
+ | `--cw-ink` | `#151b27`, `#e8ebf1` | Body text. |
329
+ | `--cw-ink-muted` | `#4f5a6e`, `#9ba4b6` | Secondary text, labels. |
330
+ | `--cw-accent` | `#2950d3`, `#7d9bff` | Your next action: the primary button, links, a chosen category, the focus ring. |
331
+ | `--cw-accent-ink` | `#ffffff`, `#0e131c` | Text on an accent background. |
332
+ | `--cw-accent-soft` | `#e7ecfb`, `#1d2847` | The background of the chosen category. |
333
+ | `--cw-red` | `#c42f3b`, `#ff6b74` | A failure, and the red side of a referee card. |
334
+ | `--cw-red-soft` | `#fbe4e6`, `#3a1a1f` | The background of an error. |
335
+ | `--cw-yellow` | `#e5ad00`, `#f2c84b` | The yellow side of a referee card. Nothing else is yellow. |
336
+ | `--cw-shadow-ink` | `#151b27`, `#000000` | What the shadow and the dimmed backdrop are made from. |
337
+ | `--cw-font` | not set (inherits) | The font. Left unset on purpose, so it is your game's own; set it to use another. |
338
+ | `--cw-text-s` | `0.8125rem` | Small text: labels, facts, hints. |
339
+ | `--cw-text-m` | `0.9375rem` | Body text. |
340
+ | `--cw-text-l` | `1.125rem` | Titles. |
341
+ | `--cw-leading` | `1.5` | Body line height. |
342
+ | `--cw-radius` | `10px` | Panels and the dialog. |
343
+ | `--cw-radius-s` | `6px` | Buttons, fields and lines. |
344
+ | `--cw-border-width` | `1px` | Every border. |
345
+ | `--cw-space-1` | `0.25rem` | Smallest gap. |
346
+ | `--cw-space-2` | `0.5rem` | Small gap. |
347
+ | `--cw-space-3` | `0.75rem` | Medium gap. |
348
+ | `--cw-space-4` | `1rem` | Standard padding. |
349
+ | `--cw-space-5` | `1.5rem` | Large gap, the dialog padding. |
350
+ | `--cw-control-height` | `2.5rem` | Minimum height of buttons and choices. |
351
+ | `--cw-dialog-width` | `30rem` | The widest a dialog gets (it is never wider than the screen). |
352
+ | `--cw-layer` | `1000` | The stacking order of the dialog, above your game. |
353
+
354
+ ## Security notes
355
+
356
+ - **Nothing else about anyone reaches the page.** The components show only what `GET /notices` and `GET /record` return: the rule, the
357
+ end, the reference code (`M-XXXXX`) and the player's own lines. They keep only those fields and drop the rest, so no person ref, room id,
358
+ moderator, reason or other player's name is in the markup, even if a server sent one. The notice id is a handle for the acknowledge call
359
+ and is never put in the page.
360
+ - **The player's lines are text.** They are rendered as text, never as HTML, whatever they contain. The kit has already masked any blocked
361
+ word in them (`******`); the components show that as it is.
362
+ - **Rules and the report note are text too.** Markup in a rule title or a summary is shown as the characters it is.
363
+ - **The appeal link is checked.** Only an `https:` address or a relative one becomes a link (hub-react's rule: no `http:`, no whitespace or control characters, no backslash, no entity, no `//host`), and it opens with
364
+ `rel="noopener noreferrer"`.
365
+ - **Who is asking is the server's job.** The player routes read the caller from your `identify` hook, never from the page. The components
366
+ send no identity of their own. Keep the routes behind your own session, and keep `cache-control: no-store` (the kit sends it) through any proxy.
367
+ - **Reports are limited on the server.** The kit refuses a duplicate, a report against yourself, an empty seat and more reports than the
368
+ daily limit, and the dialog says so in plain words; none of this depends on the page.
369
+ - **Server text is not echoed.** Error messages come from the components' own catalog, not from the response body.
370
+ - **Content-Security-Policy.** Nothing is injected at run time. Allow the stylesheet file and, if the components call another origin,
371
+ that origin in `connect-src`.
372
+
373
+ ## Links
374
+
375
+ - [Apache-2.0 license](https://github.com/hainix/chatwarden/blob/main/LICENSE)
376
+ - [Player API routes](https://github.com/hainix/chatwarden/tree/main/packages/http#the-routes)
377
+ - [Source and other packages](https://github.com/hainix/chatwarden)
378
+ - [Issues](https://github.com/hainix/chatwarden/issues)
@@ -0,0 +1,13 @@
1
+ import type { ReactNode, RefObject } from 'react';
2
+ export declare function Dialog({ labelledBy, initialFocus, onEscape, returnFocusTo, children, }: {
3
+ /** The id of the heading that names the window. */
4
+ labelledBy: string;
5
+ /** What takes focus when it opens: the heading. */
6
+ initialFocus: RefObject<HTMLElement | null>;
7
+ /** Called on Escape. Leave it out when the window must not be dismissed. */
8
+ onEscape?: () => void;
9
+ /** Where focus goes on close when the element that had it before is gone. */
10
+ returnFocusTo?: () => HTMLElement | null;
11
+ children: ReactNode;
12
+ }): import("react").JSX.Element;
13
+ //# sourceMappingURL=Dialog.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Dialog.d.ts","sourceRoot":"","sources":["../../src/Dialog.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAiB,SAAS,EAAE,SAAS,EAAE,MAAM,OAAO,CAAC;AAyBjE,wBAAgB,MAAM,CAAC,EACrB,UAAU,EACV,YAAY,EACZ,QAAQ,EACR,aAAa,EACb,QAAQ,GACT,EAAE;IACD,mDAAmD;IACnD,UAAU,EAAE,MAAM,CAAC;IACnB,mDAAmD;IACnD,YAAY,EAAE,SAAS,CAAC,WAAW,GAAG,IAAI,CAAC,CAAC;IAC5C,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IACtB,6EAA6E;IAC7E,aAAa,CAAC,EAAE,MAAM,WAAW,GAAG,IAAI,CAAC;IACzC,QAAQ,EAAE,SAAS,CAAC;CACrB,+BA0EA"}