-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhtml.js
539 lines (503 loc) · 15.2 KB
/
html.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/**
* HTML component system with raw string templates.
*/
import { readFileSync } from "node:fs";
// A tagged template function to invoke Prettier's built-in formatting
// See https://prettier.io/blog/2020/08/24/2.1.0.html
const html = (...args) => String.raw(...args);
const snippets = {};
const useSnippet = (path) => {
let content = snippets[path];
if (!content) {
content = readFileSync(path);
snippets[path] = content;
}
return content;
};
// Generic complete HTML page
export const Page = ({ body, title, mixpanelToken, myRcUserId }) => html`
<!doctype html>
<html lang="en">
<head>
<title>${title}</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="shortcut icon" type="image/png" href="favicon.ico" />
${
""
/* Mixpanel insert from https://docs.mixpanel.com/docs/quickstart/connect-your-data?sdk=javascript */
/* NOTE: Had to double escape forward slashes, i.e. replace "\/" with "\\/" */
}
${useSnippet("./html/mixpanel.snippet.html")}
<script type="module">
// import mixpanel from 'mixpanel-browser'; // This is a global from mixpanel script snippet
mixpanel.init("${mixpanelToken}", {
debug: true,
track_pageview: true,
persistence: "localStorage",
});
// Set this to a unique identifier for the user performing the event.
const userId = "${myRcUserId || ""}";
if (document.referrer.match("rctv.recurse.com")) {
mixpanel.identify("rctv");
} else if (userId) {
mixpanel.identify(userId);
} else {
mixpanel.reset();
}
</script>
</head>
<body>
<script
src="https://unpkg.com/[email protected]"
integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC"
crossorigin="anonymous"
></script>
${useSnippet("./html/escape-html-htmx-extension.snippet.html")}
<script src="https://unpkg.com/[email protected]/dist/ext/ws.js"></script>
${body}
</body>
</html>
`;
export const RootBody = ({ roomListContent, personalizations, sort }) => {
let body = "";
// Propogate settings back to the websocket connection which are not stored in
// a cookie or are otherwise stateless
body += `<main hx-ext="ws" ws-connect="/websocket?sort=${escapeHtml(sort ?? "")}" id="main">`;
body += html`<h1>RCVerse</h1>`;
body += useSnippet("./html/about.snippet.html");
body += `<details>`;
body += html`<summary>Personalizations</summary>`;
body += html`<p>
<a href="/personalization">Edit your personalizations here</a>
</p>`;
body += html`<p>
Each personalization is applied and then repeated as escaped HTML in text
form so you can see exactly what's going on.
</p>`;
if (!personalizations || personalizations.length === 0) {
body += html`<p><em>You have no personalizations</em></p>`;
}
body += `<ul>`;
body += personalizations
.map(({ url }) => {
const include = url.endsWith(".css")
? CSSInclude({ url })
: url.endsWith(".html")
? HTMLInclude({ url })
: url.endsWith(".js")
? JSInclude({ url })
: "";
return html`<li>
<div>${escapeHtml(include)}</div>
<div>${include}</div>
<details>
<summary>Code</summary>
<pre class="personalization__code-preformatted"><code
hx-get="${url}"
hx-trigger="click once from:closest details"
hx-swap="innerHTML"
hx-ext="escape-html"
class="display-contents"
></code></pre>
</details>
</li>`;
})
.join("\n");
body += `</ul>`;
// Send current list of personalizations to service worker to cache
body += html`<script>
top: {
if (!("serviceWorker" in navigator)) {
console.warning("Couldn't use serviceWorker");
break top;
}
const payload = [
${personalizations
.map(
// `encodeURIComponent` to prevent an HTML or JS injection
({ url, cache }) => `{
url: "${encodeURIComponent(url)}",
cache: ${cache}
}`,
)
.join(",")},
];
navigator.serviceWorker?.controller?.postMessage({
type: "update_personalizations",
payload,
});
navigator.serviceWorker.onmessage = (event) => {
console.log("Received onmessageEvent from service worker:", event);
};
}
</script>`;
body += `</details>`;
body += html`
${roomListContent}
<hl />
<p>You're logged in! - <a href="/logout">log out</a></p>
`;
body += html`</main>`;
return body;
};
export const RoomList = ({ whoIsInTheHub, rooms }) => html`
<dl class="room-list" id="room-list">
${WhoIsInTheHub(whoIsInTheHub)} ${rooms.map(Room).join("\n")}
</dl>
`;
export const JSInclude = ({ url }) => html`<script src="${url}"></script>`;
export const CSSInclude = ({ url }) =>
html`<link rel="stylesheet" type="text/css" href="${url}" />`;
export const HTMLInclude = ({ url }) => html`
<div
hx-get="${url}"
hx-trigger="load"
hx-request="js:noHeaders:true"
class="display-contents"
></div>
`;
// TODO: Could have an iframe preview of the homepage which htmx triggers to
// refresh on every change, but for now can test by refreshing another tab
// TODO: Make a wiki page and link it here as a repository of nice
// personalizations. Probably everything can be on the wiki and can just link to
// the personalization page and the wiki page on the home page and get rid of the
// other words therein
export const Personalization = ({
personalizations,
defaultPersonalizations,
}) => {
return html`<main class="personalization">
<link rel="stylesheet" type="text/css" href="personalizations.css" />
<h1>RCVerse Personalizations</h1>
<p>
Your personalizations are listed below. Personalizations aren't applied on
this page so hopefully this page doesn't break. To test your changes, I
recommend opening the
<a href="/" target="_blank">homepage in another tab</a> and refreshing it
after each change.
</p>
<a href="/">Back to RCVerse Home</a>
${!personalizations || personalizations.length == 0
? html`<p><em>You have no personalizations</em></p>`
: html`<ol>
${personalizations
.map(({ url, cache }, index) =>
PersonalizationListItem({
url,
cache,
index,
total: personalizations.length,
}),
)
.join("\n")}
</ol>`}
<h2>Add personalization</h2>
<p>
You can find
<a
href="https://github.com/recursecenter/wiki/wiki/RCVerse#share-your-personalizations-here"
target="_blank"
>URLs of community-made personalizations in the wiki</a
>.
</p>
<p>
There's a lot more information about how the Personalization system works
and how to make your own on
<a
href="https://github.com/recursecenter/wiki/wiki/RCVerse#personalizations"
target="_blank"
>the wiki page</a
>.
</p>
<form method="POST" action="/personalization">
<label>
URL
<input name="addUrl" value="" placeholder="https://..." />
</label>
<button type="submit">Add</button>
<p>
Security note: Make sure you trust this URL. Check out the contents
yourself and ensure you believe it won't change.
</p>
</form>
<h3>Reset</h3>
<p>
This will reset your personalizations to the current defaults. The current
defaults are listed below so you could manually add what you're missing
yourself instead of wiping everything out.
</p>
<ol>
${defaultPersonalizations
.map(({ url }) => html`<li>${url}</li>`)
.join("\n")}
</ol>
<p>
To confirm and reset your personalizations, please type "confirm" in the
text box. Then hit the button.
</p>
<form method="POST" action="/personalization">
<input type="hidden" name="reset" value="true" />
<input type="text" name="reallyReset" value="" placeholder="Really?" />
<button type="submit">Reset all my personalizations</button>
</form>
</main> `;
};
export const PersonalizationListItem = ({ url, cache, index, total }) => {
const isFirst = index === 0;
const isLast = index === total - 1;
return html`<li>
${url} - <a target="_blank" href="${url}">Visit</a>
<form method="POST" action="/personalization">
<input type="hidden" name="url" value="${url}" />
<input type="submit" name="removeUrl" value="Remove" />
<input type="hidden" name="index" value="${index}" />
${
isFirst
? ""
: html`<input type="submit" name="moveItemUp" value="Move up" />`
}
${
isLast
? ""
: html`<input type="submit" name="moveItemDown" value="Move Down" />`
}
<label>Cache <input type="checkbox" name="cache" ${cache ? "checked" : ""} onchange="this.form.submit()" />
</form>
</li>`;
};
export const Login = ({ reason } = { reason: "" }) => html`
<main>
<h1>RCVerse</h1>
<h2>Whatever you make it</h2>
${reason === "deauthenticated"
? html`<p>
RC Auth said you're not logged in. This might be temporary, so you
might try to refresh and be logged in. Please let Reed know if this
happens frequently.
</p>`
: ""}
<p><a hx-boost="false" href="/getAuthorizationUrl">Log in</a></p>
</main>
`;
export const Room = ({
roomLocation,
roomName,
isEmpty,
participants,
hasNote = false,
noteContent,
noteDateTime,
noteHowManyMinutesAgo,
countPhrase,
hasNowEvent,
nowEventName,
nowEventStartedHowManyMinutesAgo,
nowEventCalendarUrl,
nowEventDateTime,
hasNextEvent,
nextEventName,
nextEventStartsInHowLong,
nextEventCalendarUrl,
nextEventDateTime,
}) => html`
<section
id="room-update-${roomName.replaceAll(" ", "-")}"
class="display-contents"
>
<div class="room ${isEmpty ? "room--non-empty" : ""}">
<dt class="room__header">
<span class="room__header-title">
<h2 class="room__title">${roomName}</h2>
</span>
</dt>
<dd class="room__details">
${Participants({ participants, countPhrase })}
<p>
Join
<a
class="room__join"
href="${roomLocation}"
target="_blank"
rel="noopener noreferrer"
>
${roomName}
</a>
</p>
${hasNowEvent
? html`
<p class="room__event-now">
<a
class="room__event-calendar-link"
href="${nowEventCalendarUrl}"
target="_blank"
>${nowEventName}</a
>
started
<time
datetime="${nowEventDateTime}"
title="${nowEventDateTime} UTC"
>
${nowEventStartedHowManyMinutesAgo}
</time>
</p>
`
: ""}
${hasNextEvent
? html`
<p class="room__event-next">
<a
class="room__event-calendar-link"
href="${nextEventCalendarUrl}"
target="_blank"
>${nextEventName}</a
>
starts
<time
datetime="${nextEventDateTime}"
title="${nextEventDateTime} UTC"
>
${nextEventStartsInHowLong}
</time>
</p>
`
: ""}
${Note({
roomName,
hasNote,
noteContent,
noteDateTime,
noteHowManyMinutesAgo,
})}
</dd>
</div>
</section>
`;
export const Note = ({
roomName,
hasNote,
noteContent,
noteDateTime,
noteHowManyMinutesAgo,
}) => html`
<div class="display-contents">
<div class="room__note">${noteContent}</div>
<span class="room__note-updates">
<button
class="room__note-edit-button"
hx-get="/note.html?roomName=${roomName}"
hx-swap="outerHTML"
hx-target="closest div"
>
${hasNote ? "Edit note" : "Add note"}
</button>
${hasNote
? html`<span class="room__note-update-time" title="${noteDateTime} UTC">
Updated
<time datetime="${noteDateTime}"> ${noteHowManyMinutesAgo} </time>
</span>`
: ""}
</span>
</div>
`;
export const EditNoteForm = ({
roomName,
noteContent,
hasVirtualRCConnectedBlock,
}) => html`
<form
method="POST"
action="/note"
hx-post="/note"
hx-swap="none"
class="note-editor"
>
<input type="hidden" name="room" value="${roomName}" />
<fieldset>
<legend>Note</legend>
<textarea
id="note-editor__text-input-${roomName}"
name="content"
class="note-editor__text-input"
cols="33"
rows="5"
>
${noteContent}</textarea
>
<p>
Use
<a
href="https://daringfireball.net/projects/markdown/basics"
target="_blank"
>Markdown</a
>
for links, bold, and italics.
${hasVirtualRCConnectedBlock
? "Changes synced to VirtualRC."
: "This note is only on RCVerse."}
</p>
<div>
<button type="submit">Update note</button>
</div>
</fieldset>
</form>
`;
export const Participants = ({ participants, countPhrase }) =>
html`<div class="participants">
<span class="participants__faces"
>${participants.map((p) => Participant(p)).join("")}</span
>
${countPhrase ? html`<span class="room__count">${countPhrase}</span>` : ""}
</div>`;
export const Participant = ({
participantName,
faceMarkerImagePath,
lastBatch,
}) => html`
<img
class="participants__face"
src=${faceMarkerImagePath}
title="${participantName} ${lastBatch}"
style="width: 2em;"
/>
`;
export const WhoIsInTheHub = ({
isEmpty,
participants,
iAmCheckedIn,
countPhrase,
}) => html`
<section id="in-the-hub-update" class="display-contents">
<div class="room ${isEmpty ? "room--non-empty" : ""}">
<dt class="room__header">
<h2 class="room__title">Who is in the hub?</h2>
</dt>
<dd class="room__details">
${Participants({ participants, countPhrase })}
<p>
${iAmCheckedIn
? "You are checked in"
: html`<button
class="room__title-button"
hx-post="/checkIntoHub"
hx-swap="none"
>
Check in
</button>`}
</p>
</dd>
</div>
</section>
`;
// Stolen from NakedJSX https://github.com/NakedJSX/core
// Appears to be adapted from this SO answer https://stackoverflow.com/a/77873486
export const escapeHtml = (text) => {
const htmlEscapeMap = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
};
return text.replace(/[&<>"']/g, (m) => htmlEscapeMap[m] ?? "");
};