-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·1005 lines (932 loc) · 28.1 KB
/
index.js
File metadata and controls
executable file
·1005 lines (932 loc) · 28.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env node
const VERSION = "2.0.1";
/**
* This script assumes you have the [github cli](https://cli.github.com/) installed and are logged into it. It assumes a node version >= 22.14
* It has no other dependencies (no node_modules!)
*
* It will start a web server at the configured port (default is 4455) that will refetch PRs assigned to
* the user logged into your gh cli. It will also fetch PRs that have requested review for the logged in user
*
* It will do all of this for all of the repos configured in `config.github.repos`.
*
* configuration can be passed in with the --config flag, see the --help text for more information
*
* It refetches from Github once an hour.
*/
/** CONFIGURATION */
import { parseArgs } from "node:util";
const { values } = parseArgs({
options: {
repo: {
type: 'string',
short: 'r',
multiple: true,
},
"add-repo": {
type: "string",
multiple: true
},
username: {
type: 'string',
short: "u"
},
port: {
type: 'string',
short: 'p',
},
hostname: {
type: 'string',
short: 'n',
},
config: {
type: 'string',
short: 'c',
},
help: {
type: 'boolean',
short: 'h'
},
version: {
type: 'boolean',
short: 'v'
}
}
});
if (values.version) {
console.log(VERSION);
process.exit(0);
}
const defaultConfig = {
server: {
port: 4455,
hostname: "localhost"
},
github: {}
}
if (values.help) {
console.log(`
GITHUB DASHBOARD
Show a quick overview of github PRs in your browser, using the gh utility.
OPTIONS
-c, --config Load a config file. Flags overwrite config values. See JSCHEMA section for details.
-h, --help This help text
GITHUB CONFIG
All the data from repos/username must be accessible by the gh utility.
--add-repo Adds a repo to final configuration. Does not overwrite config file like --repo does.
Can be specified multiple times.
-r, --repo The repo name to load PRs for. "<organization>/<repo>" pattern.
Can be specified multiple times.
-u, --username The username to load assigned PRs for.
SERVER CONFIG
-p, --port Default: 4455 The port to bind the server to
-n, --hostname Default: locahost The hostname to bind the server to.
EXAMPLES
./index.js -r benkenawell/wedding-site -u benkenawell -p 3333
JSCHEMA
Following the spec available at https://jschema.org/
This config file should adhere to the following JSchema definition
{
server: {
port: @int,
hostname: @string
},
github: {
username: @string,
repos: [ @string ]
}
}
`);
process.exit(0)
}
import { readFileSync, existsSync } from "node:fs";
import { styleText } from "node:util";
/** semi structed logging output */
const logger = {
error(...args) {
console.error(styleText('redBright', '[ERROR]'), ...args);
},
info(...args) {
console.info(styleText('blue', '[INFO]'), ...args);
}
}
let config = {};
// TODO: load the config file from ~/.config/rmrk-gitdash and add a ./index.js --edit-config flag that opens the config.json there.
if (values.config) {
if (!existsSync(values.config)) {
logger.error('config file does not exist');
process.exit(1);
}
const configFile = readFileSync(values.config, { encoding: 'utf8' })
try {
config = JSON.parse(configFile);
} catch {
logger.error('could not parse config file');
process.exit(1);
}
}
if (!config.server) config.server = {};
if (values.port) config.server.port = parseInt(values.port);
if (values.hostname) config.server.hostname = values.hostname;
if (!config.server.port) config.server.port = defaultConfig.server.port;
if (!config.server.hostname) config.server.hostname = defaultConfig.server.hostname;
if (!config.github) config.github = {};
if (values.username) config.github.username = values.username;
if (values.repo) config.github.repos = values.repo;
if (values["add-repo"])
config.github.repos = Array.from(new Set([...config.github.repos, ...values['add-repo']]));
if (!config.github.repos) config.github.repos = [];
Object.freeze(config); // done building config.
if (!config.github.username) {
logger.error("must provide a username");
process.exit(1);
}
import { exec as nodeExec } from "node:child_process";
import { createServer } from "node:http";
import { DatabaseSync } from "node:sqlite";
// TODO: let us choose where to put the sqlite database
const database = new DatabaseSync(":memory:");
/** DATABASE SETUP */
database.exec(`
CREATE TABLE repo (
id integer primary key,
organization text,
name text,
identifier text generated always as (concat(organization, '/', name)),
href text generated always as (concat('https://github.com/', identifier))
)
`);
database.exec(`
CREATE UNIQUE INDEX repo_identifier_idx on repo(identifier);
`);
// TODO: there might be a better way to tell the "type" column
database.exec(`
CREATE TABLE pull_request (
id integer primary key,
number integer,
title text,
branch text,
status text,
date text, -- pr's createdAt date
review_decision text,
repo_id integer,
assignees text, -- json array of login names
reviewers text -- json array of login names
);
`);
// enforce the repo_id, number combo is unique
database.exec(`
CREATE UNIQUE INDEX repo_pr_number_idx on pull_request (repo_id, number);
`);
/** UTILITY FUNCTIONS */
/**
* promisify node's exec fucntion
* @param {string} command
* @returns {Promise<undefined | string>}
*/
function exec(command) {
return new Promise((res, rej) => {
nodeExec(command, (err, stdout, stderr) => {
if (err) rej(err);
if (stdout) res(stdout);
res();
});
});
}
/**
* @param {string} str
*/
function snakeToCamel(str) {
return str
.toLowerCase()
.replace(/([-_][a-z])/g, (group) =>
group.toUpperCase().replace("-", "").replace("_", ""),
);
}
/** GH CLI TO SQLITE */
const insertRepo = database.prepare(
`INSERT INTO repo (organization, name) values (?, ?);`,
);
for (const repo of config.github.repos) {
insertRepo.run(...repo.split("/"));
}
const upsertPullRequest = database.prepare(
`INSERT INTO pull_request(repo_id, number, title, branch, status, date, review_decision, assignees, reviewers) VALUES ($repoId, $number, $title, $branch, $status, $date, $reviewDecision, $assignees, $reviewers)
ON CONFLICT (repo_id, number) DO UPDATE SET
title = excluded.title,
branch = excluded.branch,
status = excluded.status,
date = excluded.date,
review_decision = excluded.review_decision,
assignees = excluded.assignees,
reviewers = excluded.reviewers
WHERE
repo_id = excluded.repo_id AND number = excluded.number;
`,
);
const deletePullRequests = database.prepare("DELETE FROM pull_request;");
function repoSearch(repoIdentifier, search) {
return `gh pr ls --repo '${repoIdentifier}' --search '${search}' --json title,number,headRefName,state,createdAt,reviewDecision,isDraft,assignees,reviewRequests`;
}
const searches = ['assignee:@me', 'user-review-requested:@me'];
async function loadPrs() {
// TODO: just delete the intersection we don't update
//
// delete all the pull requests before we pull again.
deletePullRequests.run();
for (const repo of database.prepare("select * from repo").all()) {
for (const search of searches) {
const prs = await exec(repoSearch(repo.identifier, search)).then(JSON.parse);
for (const pr of prs)
upsertPullRequest.run({
$repoId: repo.id,
$number: pr.number,
$title: pr.title,
$branch: pr.headRefName,
$status: pr.isDraft ? "DRAFT" : pr.state,
$date: pr.createdAt,
$reviewDecision: pr.reviewDecision,
$assignees: JSON.stringify(pr.assignees.map((a) => a.login)),
$reviewers: JSON.stringify(pr.reviewRequests.map((a) => a.login)),
});
}
}
}
// TODO: load these periodically and maybe SSE to the front end.
// right now it loads every hour
setInterval(
() => {
logger.info("loading PRs", new Date());
loadPrs();
},
1000 * 60 * 60,
);
/** DOMAIN MODELING */
// these model the Repo/PR domain
// they pull from the SQLITE DB
const SQLITE = {
Repo: class {
static *all() {
for (const repo of database.prepare("SELECT * from repo;").iterate())
yield new SQLITE.Repo(repo);
}
/**
* @param {string} identifier
*/
static insert(identifier) {
const parsedRepo = identifier.split("/");
if (parsedRepo.length === 2)
return database
.prepare("INSERT INTO repo (organization, name) VALUES (?, ?)")
.run(...parsedRepo)
else throw new Error(`Malformed repo identifier: ${identifier}`)
}
/**
* @param {string} identifier
*/
static get(identifier) {
const entry = database
.prepare("SELECT * from repo where identifier = ?")
.get(identifier);
return new SQLITE.Repo(entry);
}
/**
* @param {string} identifier
*/
static remove(identifier) {
return database.prepare('DELETE FROM repo where identifier = ?').run(identifier)
}
constructor(entry) {
this._columns = [...Object.keys(entry)];
for (const [key, value] of Object.entries(entry))
this[snakeToCamel(key)] = value;
}
pullRequests() {
const prs = database
.prepare("SELECT * from pull_request where repo_id = ?")
.all(this.id);
return prs.map((pr) => new SQLITE.PullRequest(pr));
}
open_prs() {
return database
.prepare(
"SELECT pull_request.* FROM pull_request, json_each(pull_request.assignees) where repo_id = ? and json_each.value = ?",
)
.all(this.id, config.github.username)
.map((pr) => new SQLITE.PullRequest(pr));
}
review_requested() {
const prs = database
.prepare(
"SELECT pull_request.* from pull_request, json_each(pull_request.reviewers) where repo_id = ? and json_each.value = ?;",
)
.all(this.id, config.github.username);
return prs.map((pr) => new SQLITE.PullRequest(pr));
}
},
PullRequest: class {
/**
* @param {number | SQLITE.Repo} repo
* @param {number} number
*/
static get(repo, number) {
const entry = database
.prepare("SELECT * from pull_request where repo_id = ? and number = ?")
.get(typeof repo === "number" ? repo : repo.id, number);
return new SQLITE.PullRequest(entry);
}
constructor(entry) {
this._columns = [...Object.keys(entry)];
for (const [key, value] of Object.entries(entry))
this[snakeToCamel(key)] = value;
}
get repo() {
return new SQLITE.Repo(
database.prepare("SELECT * from repo where id = ?").get(this.repoId),
);
}
get href() {
return this.repo.href + "/pull/" + this.number;
}
},
};
// TODO: add support for multiple name
// TODO: add support for ampersand within a value (is this suppotted by HTTP?)
class FormData {
constructor(encodedFormData) {
const decoded = decodeURIComponent(encodedFormData);
const entries = decoded.split("&");
for (const entry of entries) {
const [key, value] = entry.split("=");
this[key] = value;
}
}
}
// setTimeout(() => {
// console.log(SQLITE.Repo.get("outdoorly/acorn").pullRequests().at(0).repo);
// }, [1000]);
// setTimeout(() => {
// console.log(SQLITE.Repo.get("outdoorly/acorn").open_prs());
// }, 1000);
const reviewState = ["OPEN", "DRAFT", ""];
// TODO: is COMMENTED a review decision?
const reviewDecisionOrder = [
"CHANGES_REQUESTED",
"APPROVED",
"REVIEW_REQUIRED",
"",
];
/**
* sorts an array of PullRequest's by state, then reviewDecision
* in the order described by the corresponding arrays above
* @param {PullRequest} a
* @param {PullRequest} b
*/
function sortReviewDecision(a, b) {
return (
reviewState.indexOf(a.status) - reviewState.indexOf(b.status) ||
reviewDecisionOrder.indexOf(a.reviewDecision) -
reviewDecisionOrder.indexOf(b.reviewDecision)
);
}
/** SERVER */
// TODO: create a POST /repo endpoint where someone can add a repo to the list to load
// TODO: create a way to force our backend to reload the PRs from github
// TODO: create a SSE endpoint for new/updated PRs
const server = createServer(async (req, res) => {
// to add assets for loading, add them here
// all assets become immutable, based on their urlPath
const assets = {
stylesheet: [copyable.stylesheet, toast.stylesheet],
script: [
copyable.script,
toast.script,
lazyLoad.script,
fetchFrame.script,
localtime.script,
],
};
let asset; // an asset, if we find one
if ((asset = assets.stylesheet.find((s) => s.urlPath === req.url))) {
res.writeHead(200, {
"Content-Type": "text/css",
"Cache-Control": "public, max-age=604800, immutable",
});
res.end(asset.content);
return;
}
// if we've reached here, asset is null from the previous find
if ((asset = assets.script.find((s) => s.urlPath === req.url))) {
res.writeHead(200, {
"Content-Type": "text/javascript",
"Cache-Control": "public, max-age=604800, immutable",
});
res.end(asset.content);
return;
}
if (req.method === "POST" && req.url === "/repo") {
let body = "";
req.on("data", (chunk) => {
body += chunk;
});
req.on("end", () => {
const formData = new FormData(body);
// use a hidden _method input to implement other HTTP methods
if (formData._method && ['DELETE', 'PUT', 'PATCH'].includes(formData._method)) {
if (formData._method === 'DELETE') {
SQLITE.Repo.remove(formData.repo);
res.writeHead(303, { Location: "/" });
res.end();
}
} else { // POST request
// TODO: verify I can add this repo
try {
if (formData.repo) SQLITE.Repo.insert(formData.repo);
loadPrs().then(() => {
res.writeHead(303, { Location: "/" });
res.end();
});
} catch (e) {
console.error(e.message)
res.writeHead(303, { Location: "/" });
res.end();
}
}
});
return;
}
const repos = [...SQLITE.Repo.all()];
if (req.url === "/prs/review-request") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
// TODO: maybe we don't need to reload _all_ the PRs here
loadPrs().then(() => {
res.end(PARTIALS.reviewFetchFrame(repos));
});
return;
}
if (req.url === "/prs/assigned") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
// TODO: maybe we don't need to reload _all_ the PRs here
loadPrs().then(() => {
res.end(PARTIALS.assignedFetchFrame(repos));
});
return;
}
if (req.url === "/") {
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
res.end(`
<!doctype html>
<html>
<head>
<title>Github Pull Requests</title>
<style>
header > form {
display: inline;
margin-inline: 10px;
}
.repo {
display: block;
}
.pr {
display: grid;
grid-template-columns: 10ch 25ch 6ch 2fr 1fr 25ch;
align-items: center;
&[data-status="DRAFT"] {
opacity: 0.6;
}
&[data-review-decision="CHANGES_REQUESTED"] {
background-color: color(from red srgb r g b / 20%);
}
&[data-review-decision="APPROVED"] {
background-color: color(from green srgb r g b / 20%);
}
}
lazy-load {
display: block;
}
@keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@keyframes rotate-clockwise {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
fetch-frame.loading ul {
animation: fade-out 1s alternate infinite;
}
button.refetch {
all: unset;
display: inline-block;
width: 16px;
height: 16px;
transform-origin: bottom;
}
fetch-frame.loading button.refetch {
animation: rotate-clockwise 1s linear forwards infinite;
}
</style>
<link rel="stylesheet" href="${copyable.stylesheet.urlPath}">
<script src="${copyable.script.urlPath}"></script>
<link rel="stylesheet" href="${toast.stylesheet.urlPath}">
<script src="${toast.script.urlPath}"></script>
<script src="${lazyLoad.script.urlPath}" defer></script>
<script src="${fetchFrame.script.urlPath}" defer></script>
<script src="${localtime.script.urlPath}"></script>
</head>
<body>
<header>
<h1>Current PR landscape</h1>
<form id="add-repo" action="/repo" method="post">
<label>Add repo <input name="repo"></label>
<button>Add</button>
</form>
<form id="delete-repo" action="/repo" method="post">
<input type="hidden" name="_method" value="DELETE">
Remove a repo:
${SQLITE.Repo.all().map(repo => `<button name="repo" value="${repo.identifier}">${repo.identifier}</button> `).toArray().join('\n')}
</form>
</header>
${PARTIALS.reviewFetchFrame(repos)}
${PARTIALS.assignedFetchFrame(repos)}
</body>
</html>
`);
}
res.statusCode = 404;
res.end();
});
server.on("listening", () => {
logger.info("server is listening at", server.address());
});
logger.info("loading PRs from github into memory");
loadPrs().then(() => {
logger.info("server is starting...");
server.listen(config.server.port, config.server.hostname);
});
/** DYNAMIC PARTIAL TEMPLATES */
const PARTIALS = {
/** fetch frame container for review requested PRs */
reviewFetchFrame(repos) {
return `
<fetch-frame src="/prs/review-request">
<h2>
My Review Requests
<button data-fetcher class="refetch">${refreshSVG}</button>
</h2>
<ul class="repo">
${repos.map(PARTIALS.reviewRequested).join("\n")}
</ul>
</fetch-frame>`;
},
/** given a repo, return the PRs */
reviewRequested(repo) {
return `<li class="repo">
<h3>${repo.name}</h3>
<ul>
${repo
.review_requested()
.map(
(pr) =>
`<li class="pr" data-status="${pr.status}">
<span>${pr.status}</span>
<span></span>
<a href="${pr.href}" target="_blank">${pr.number}</a>
<span>${pr.title}</span>
<button data-copyable="origin/${pr.branch}">${pr.branch}</button>
<time datetime="${pr.date}">${pr.date}</time>
</li>`,
)
.join("\n")}
</ul>
</li>`;
},
/** fetch frame container for PRs assigned to me */
assignedFetchFrame(repos) {
return `
<fetch-frame src="/prs/assigned">
<h2>
My PRs
<button data-fetcher class="refetch">${refreshSVG}</button>
</h2>
<ul>
${repos.map(PARTIALS.openPrs).join("\n")}
</ul>
</fetch-frame>`;
},
/** given a repo, return html representation of every PR */
openPrs(repo) {
return `<li class="repo">
<h3>${repo.name}</h3>
<ul>
${repo
.open_prs()
.sort(sortReviewDecision)
.map(
(pr) =>
`<li class="pr" data-status="${pr.status}" data-review-decision="${pr.reviewDecision}">
<span>${pr.status}</span>
<span>${pr.reviewDecision}</span>
<a href="${pr.href}" target="_blank">${pr.number}</a>
<span>${pr.title}</span>
<button data-copyable>${pr.branch}</button>
<time datetime="${pr.date}">${pr.date}</time>
</li>`,
)
.join("\n")}
</ul>
</li>`;
},
};
/** ASSET PIPELINE */
import { createHash } from "node:crypto";
import { hostname } from "node:os";
const Hash = {
/**
* returns the sha256 digest of the content that was passed in.
* @param {string} content
* @returns {Buffer} a buffer of the contents, hashed with a sha256 algorithm
*/
digest(content) {
return createHash("sha256").update(content).digest();
},
/**
* performs a XOR Fold to get a buffer half the size of the one passed int
* @param {Buffer} buf
* @returns {Buffer} a buffer half the length of the input
*/
fold(buf) {
const half = buf.length / 2;
const folded = Buffer.alloc(half);
for (let i = 0; i < half; i++) folded[i] = buf[i] ^ buf[i + half];
return folded;
},
};
function asset({ name, content, extension }) {
if (name.includes("."))
throw new Error(
"name shouldn't have an extension, cannot include a period",
);
const hash = Hash.fold(Hash.fold(Hash.fold(Hash.digest(content)))).toString(
"base64url",
);
const assetName = `${name}-${hash}.${extension}`;
return {
urlPath: `/${assetName}`,
assetName,
fileName: `${name}.${extension}`,
hash,
content,
};
}
/** CLIENT SIDE ASSETS */
const copyable = {
stylesheet: asset({
name: "copyable",
extension: "css",
content: `
button[data-copyable] {
all: unset;
cursor: default;
width: fit-content;
padding: 0px 8px;
border-radius: 3px;
position: relative;
transition: background-color 200ms;
&:hover {
background-color: paleturquoise;
&::after {
content: "📋";
position: absolute;
right: 0;
transform: translateX(100%) translateY(-10%);
font-size: small;
}
}
}
`,
}),
script: asset({
name: "copyable",
extension: "js",
content: `
/** data-copyable script */
function listenForCopyable(node) {
const copyableElements = node.querySelectorAll('[data-copyable]');
for(const elem of copyableElements) {
elem.addEventListener('click', () => {
const text = elem.dataset.copyable || elem.textContent;
navigator.clipboard.writeText(text);
Toast.show({text: 'copied "' + text + '"'});
})
}
}
document.addEventListener('DOMContentLoaded', () => listenForCopyable(document));
document.addEventListener('html:load', (ev) => listenForCopyable(ev.target));
`,
}),
};
const toast = {
stylesheet: asset({
name: "toast",
extension: "css",
content: `
@keyframes toast-fade-in {
from {
opacity: 0;
transform: translateX(-50%) translateY(30%);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(-10%);
}
}
@keyframes toast-fade-out {
from {
opacity: 1;
transform: translateX(-50%) translateY(-10%);
}
to {
opacity: 0;
transform: translateX(-50%) translateY(-40%);
}
}
.toast {
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
display: flex;
align-items: center;
justify-content: center;
background-color: linen;
border-radius: 4px;
padding: 2px 8px;
margin: 8px 12px;
opacity: 1;
transition: bottom 150ms;
&.enter {
animation: toast-fade-in 150ms ease-in forwards;
}
&.exit {
animation: toast-fade-out 150ms ease-out forwards;
}
}
`,
}),
script: asset({
name: "toast",
extension: "js",
content: `
/** Toast script */
// TODO, add a max number of toasts
window.Toast = {};
/** holds the list of all currently active toasts */
Toast.currentList = new Map();
/** id to assign the next toast */
Toast.nextId = 0;
/** set the bottom property correctly for all toasts */
Toast.updatePositions = () => {
let iter = 0;
for(const elem of Toast.currentList.values()) {
elem.style.bottom = 2 * (Toast.currentList.size - iter++) + 'em';
}
}
/** pop a new toast! */
Toast.show = ({text, delay = 5000}) => {
if(!text) return;
const div = document.createElement('div');
div.classList.add('toast');
div.classList.add('enter');
div.innerText = text;
div.id = 'toast-' + Toast.nextId++;
Toast.currentList.set(div.id, div);
Toast.updatePositions();
document.body.appendChild(div);
div.addEventListener('click', () => { Toast.remove(div.id); });
div.addEventListener('animationend', () => {
div.classList.remove('enter');
}, {once: true});
setTimeout(() => {Toast.remove(div.id)}, delay);
return div.id;
};
/** remove a toast */
Toast.remove = (toastId) => {
const div = document.getElementById(toastId);
div.classList.add('exit');
Toast.currentList.delete(div.id);
Toast.updatePositions();
div.addEventListener('animationend', () => {
document.body.removeChild(div);
}, {once: true});
}
`,
}),
};
const lazyLoad = {
script: asset({
name: "lazyload",
extension: "js",
content: `
class LazyLoad extends HTMLElement {
connectedCallback() {
const source = this.getAttribute('src');
fetch(source, {headers: {"Lazy-Load": "true"}})
.then(resp => resp.text())
.then(txt => {
const parsed = new DOMParser().parseFromString(txt, 'text/html');
const elem = parsed.body.firstChild;
this.replaceWith(elem);
elem.dispatchEvent(new CustomEvent("html:load", {bubbles: true}));
});
}
}
if(!customElements.get('lazy-load'))
customElements.define('lazy-load', LazyLoad);
`,
}),
};
// TODO: change html when loading. Can be given the html via an embedded template tag
// <fetch-frame tmp-html="xxx"><template id="xxx">...</template></fetch-frame>
// TODO: add some classes for added/settling. Insp: https://htmx.org/reference/#classes
// Needs to be `defer`ed when loading, so the dom is loaded first and querySelectorAll works
const fetchFrame = {
script: asset({
name: "fetchframe",
extension: "js",
content: `
class FetchFrame extends HTMLElement {
connectedCallback() {
const fetcherNodes = this.querySelectorAll('[data-fetcher]');
for(const node of fetcherNodes) {
const eventType = node.dataset.fetcher || 'click';
node.addEventListener(eventType, () => {
this.classList.add('loading');
this.fetch().catch(() => {
this.classList.remove('loading')
Toast.show({text: 'could not fetch'});
});
});
}
}
fetch() {
const source = this.getAttribute('src');
return fetch(source)
.then(resp => resp.text())
// TODO: use DOMParser to add an "added" class early
.then(txt => {
const parsed = new DOMParser().parseFromString(txt, 'text/html');
const elem = parsed.body.firstChild;
this.replaceWith(elem);
elem.dispatchEvent(new CustomEvent("html:load", {bubbles: true}));
});
}
}
if(!customElements.get('fetch-frame'))
customElements.define('fetch-frame', FetchFrame);
`,
}),
};
// converts all time tags to user local browser time
const localtime = {
script: asset({
name: "localtime",
extension: "js",
content: `
const DateFormatter = new Intl.DateTimeFormat('en-US', {dateStyle: 'medium'});
const TimeFormatter = new Intl.DateTimeFormat('en-US', {hour: '2-digit', minute: '2-digit'});
function convertTimeTags(node = document) {
const timeNodes = node.querySelectorAll('time[datetime]');
for(const timeNode of timeNodes) {
try {
const dateAttr = new Date(timeNode.getAttribute('datetime'));
const timeStr = TimeFormatter.format(dateAttr);
const dateStr = DateFormatter.format(dateAttr);
timeNode.innerText = timeStr + " " + dateStr;
} catch {}
}
}
window.convertTimeTags = convertTimeTags;
document.addEventListener('DOMContentLoaded', () => convertTimeTags(document));
new MutationObserver((records) => {
for(const record of records) {
if(record.type === 'childList' && record.addedNodes) {
for(const addedNode of record.addedNodes) {
if('querySelectorAll' in addedNode) convertTimeTags(addedNode);
}
}
}
}).observe(document, {childList: true, subtree: true});
`,
}),