@georgepxto/github-activity 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +301 -2
- package/bin/cli.js +64 -0
- package/dist/data.d.ts +28 -0
- package/dist/data.js +123 -0
- package/dist/fetch.d.ts +10 -0
- package/dist/fetch.js +53 -0
- package/dist/github-activity.d.ts +23 -0
- package/dist/github-activity.js +352 -0
- package/dist/i18n.d.ts +21 -0
- package/dist/i18n.js +48 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/server.d.ts +2 -0
- package/dist/server.js +2 -0
- package/dist/styles.d.ts +1 -0
- package/dist/styles.js +258 -0
- package/package.json +53 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 georgepxto
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,302 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `<github-activity>`
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A dependency-free web component that renders a GitHub contribution calendar, with stats, month labels, a legend and a wave entrance animation. Works in any stack: plain HTML, React, Vue, Svelte, Astro, Rails templates.
|
|
4
|
+
|
|
5
|
+
<picture>
|
|
6
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/georgepxto/web-components/main/github-activity/screenshots/dark.png">
|
|
7
|
+
<img alt="Contribution calendar with three stats above it: 1,091 contributions, a 7-day longest streak and Wednesday as the most active day" src="https://raw.githubusercontent.com/georgepxto/web-components/main/github-activity/screenshots/light.png" width="880">
|
|
8
|
+
</picture>
|
|
9
|
+
|
|
10
|
+
- No runtime dependencies, Shadow DOM, under 8 kB gzipped
|
|
11
|
+
- Light and dark themes out of the box, fully themable with CSS custom properties and `::part()`
|
|
12
|
+
- English, Portuguese and Spanish built in, any other language through `labels`; dates and month names come from `Intl`
|
|
13
|
+
- Responsive through container queries: splits into two rows in narrow containers
|
|
14
|
+
- Accessible: the graph is a labelled image, every day has a tooltip, motion respects `prefers-reduced-motion`
|
|
15
|
+
- Ships a build-time fetcher and a CLI, so your GitHub token never reaches the browser
|
|
16
|
+
|
|
17
|
+
## Entrance animation
|
|
18
|
+
|
|
19
|
+
When the calendar scrolls into view, the days fill in as a wave from left to right and the stats count up. Set `animation="none"` to turn it off; it is skipped automatically for visitors who prefer reduced motion.
|
|
20
|
+
|
|
21
|
+
<picture>
|
|
22
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/georgepxto/web-components/main/github-activity/screenshots/animation-dark.gif">
|
|
23
|
+
<img alt="The calendar's days appear in a wave from left to right while the stats count up to 1,091 contributions and a 7-day streak" src="https://raw.githubusercontent.com/georgepxto/web-components/main/github-activity/screenshots/animation-light.gif" width="880">
|
|
24
|
+
</picture>
|
|
25
|
+
|
|
26
|
+
## Examples
|
|
27
|
+
|
|
28
|
+
Brazilian Portuguese with a custom dark palette:
|
|
29
|
+
|
|
30
|
+
<img alt="Calendar in Portuguese on a near-black background with mint green levels" src="https://raw.githubusercontent.com/georgepxto/web-components/main/github-activity/screenshots/custom-pt-br.png" width="880">
|
|
31
|
+
|
|
32
|
+
```html
|
|
33
|
+
<github-activity src="/github-activity.json" locale="pt-BR" theme="dark"></github-activity>
|
|
34
|
+
|
|
35
|
+
<style>
|
|
36
|
+
github-activity {
|
|
37
|
+
--gha-level-0: #161b18;
|
|
38
|
+
--gha-accent: #43c97e;
|
|
39
|
+
--gha-text: #e9eeea;
|
|
40
|
+
--gha-muted: #a3ada6;
|
|
41
|
+
--gha-border: #1f2622;
|
|
42
|
+
--gha-cell-radius: 1px;
|
|
43
|
+
}
|
|
44
|
+
</style>
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Violet, round cells, without the stats:
|
|
48
|
+
|
|
49
|
+
<img alt="Calendar with round violet cells on a pale lilac background, no stats row" src="https://raw.githubusercontent.com/georgepxto/web-components/main/github-activity/screenshots/violet-round.png" width="880">
|
|
50
|
+
|
|
51
|
+
```html
|
|
52
|
+
<github-activity src="/github-activity.json" hide="stats"></github-activity>
|
|
53
|
+
|
|
54
|
+
<style>
|
|
55
|
+
github-activity {
|
|
56
|
+
--gha-accent: #7c3aed;
|
|
57
|
+
--gha-level-0: #ede9fe;
|
|
58
|
+
--gha-text: #2e1065;
|
|
59
|
+
--gha-muted: #6d28d9;
|
|
60
|
+
--gha-cell-radius: 50%;
|
|
61
|
+
}
|
|
62
|
+
</style>
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
In narrow containers the stats stack and the year splits into two rows:
|
|
66
|
+
|
|
67
|
+
<img alt="The component at 390 pixels wide, with stacked stats and the calendar split into two halves" src="https://raw.githubusercontent.com/georgepxto/web-components/main/github-activity/screenshots/mobile.png" width="390">
|
|
68
|
+
|
|
69
|
+
## Why the data is fetched separately
|
|
70
|
+
|
|
71
|
+
GitHub only exposes the contribution calendar through its GraphQL API, which requires a token. A token must never be shipped to the browser, so the work is split in two:
|
|
72
|
+
|
|
73
|
+
1. **On your server or at build time**, fetch the calendar with the included CLI or `fetchContributions()` and save it as JSON.
|
|
74
|
+
2. **In the browser**, `<github-activity>` renders that JSON.
|
|
75
|
+
|
|
76
|
+
## Install
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
npm install @georgepxto/github-activity
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
```js
|
|
83
|
+
import '@georgepxto/github-activity';
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Or load it from a CDN with no build step:
|
|
87
|
+
|
|
88
|
+
```html
|
|
89
|
+
<script type="module" src="https://cdn.jsdelivr.net/gh/georgepxto/web-components@main/github-activity/dist/index.js"></script>
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## 1. Get the data
|
|
93
|
+
|
|
94
|
+
Create a token at [github.com/settings/tokens](https://github.com/settings/tokens). A token without extra scopes is enough for public contributions. Keep it in an environment variable or a secret, never in client code.
|
|
95
|
+
|
|
96
|
+
### With the CLI
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
GITHUB_TOKEN=ghp_xxx npx @georgepxto/github-activity octocat --out public/github-activity.json
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
| Option | Description |
|
|
103
|
+
| --- | --- |
|
|
104
|
+
| `-o, --out <file>` | Write to a file instead of stdout |
|
|
105
|
+
| `--from <date>` | Start of the range (at most one year before `--to`) |
|
|
106
|
+
| `--to <date>` | End of the range, defaults to today |
|
|
107
|
+
|
|
108
|
+
### Refresh it every day with GitHub Actions
|
|
109
|
+
|
|
110
|
+
Save the token as a repository secret named `ACTIVITY_TOKEN`, then add `.github/workflows/github-activity.yml`:
|
|
111
|
+
|
|
112
|
+
```yaml
|
|
113
|
+
name: Update GitHub activity
|
|
114
|
+
|
|
115
|
+
on:
|
|
116
|
+
schedule:
|
|
117
|
+
- cron: '0 6 * * *'
|
|
118
|
+
workflow_dispatch:
|
|
119
|
+
|
|
120
|
+
permissions:
|
|
121
|
+
contents: write
|
|
122
|
+
|
|
123
|
+
jobs:
|
|
124
|
+
update:
|
|
125
|
+
runs-on: ubuntu-latest
|
|
126
|
+
steps:
|
|
127
|
+
- uses: actions/checkout@v4
|
|
128
|
+
- uses: actions/setup-node@v4
|
|
129
|
+
with:
|
|
130
|
+
node-version: 22
|
|
131
|
+
- run: npx --yes @georgepxto/github-activity octocat --out public/github-activity.json
|
|
132
|
+
env:
|
|
133
|
+
GITHUB_TOKEN: ${{ secrets.ACTIVITY_TOKEN }}
|
|
134
|
+
- run: |
|
|
135
|
+
git config user.name "github-actions[bot]"
|
|
136
|
+
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
|
137
|
+
git add public/github-activity.json
|
|
138
|
+
git diff --cached --quiet || git commit -m "chore: update github activity"
|
|
139
|
+
git push
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### From your own server or build script
|
|
143
|
+
|
|
144
|
+
```js
|
|
145
|
+
import { fetchContributions } from '@georgepxto/github-activity/server';
|
|
146
|
+
|
|
147
|
+
const data = await fetchContributions({
|
|
148
|
+
username: 'octocat',
|
|
149
|
+
token: process.env.GITHUB_TOKEN,
|
|
150
|
+
});
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
A minimal cached endpoint with the standard `Request`/`Response` API (Node 18+, Deno, Bun, edge runtimes):
|
|
154
|
+
|
|
155
|
+
```js
|
|
156
|
+
import { fetchContributions } from '@georgepxto/github-activity/server';
|
|
157
|
+
|
|
158
|
+
let cache = { data: null, at: 0 };
|
|
159
|
+
|
|
160
|
+
export async function GET() {
|
|
161
|
+
if (!cache.data || Date.now() - cache.at > 6 * 60 * 60 * 1000) {
|
|
162
|
+
cache = { data: await fetchContributions({ username: 'octocat', token: process.env.GITHUB_TOKEN }), at: Date.now() };
|
|
163
|
+
}
|
|
164
|
+
return Response.json(cache.data, { headers: { 'Cache-Control': 'public, max-age=3600' } });
|
|
165
|
+
}
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
`fetchContributions(options)` accepts `username`, `token`, and optionally `from`, `to` (ISO string or `Date`), `signal` and a custom `fetch`.
|
|
169
|
+
|
|
170
|
+
## 2. Render it
|
|
171
|
+
|
|
172
|
+
From a URL:
|
|
173
|
+
|
|
174
|
+
```html
|
|
175
|
+
<github-activity src="/github-activity.json" username="octocat"></github-activity>
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
Inline, with no extra request (handy for server-rendered pages):
|
|
179
|
+
|
|
180
|
+
```html
|
|
181
|
+
<github-activity username="octocat">
|
|
182
|
+
<script type="application/json">{ "weeks": [ ... ] }</script>
|
|
183
|
+
</github-activity>
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
As a property:
|
|
187
|
+
|
|
188
|
+
```js
|
|
189
|
+
const element = document.querySelector('github-activity');
|
|
190
|
+
element.data = await fetch('/github-activity.json').then((response) => response.json());
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### Accepted data
|
|
194
|
+
|
|
195
|
+
Any of these shapes works, so you can also plot activity from GitLab, Codeberg or your own source:
|
|
196
|
+
|
|
197
|
+
- The output of the CLI or `fetchContributions()`
|
|
198
|
+
- The raw GitHub GraphQL response, or its `contributionCalendar` object
|
|
199
|
+
- A flat list of days: `[{ "date": "2026-01-31", "count": 4 }, ...]`. Missing days are filled with zero and levels are computed from the counts. You can pass your own `level` (0 to 4) per day.
|
|
200
|
+
|
|
201
|
+
Invalid dates are dropped and every value is escaped before rendering.
|
|
202
|
+
|
|
203
|
+
## API
|
|
204
|
+
|
|
205
|
+
### Attributes
|
|
206
|
+
|
|
207
|
+
| Attribute | Description |
|
|
208
|
+
| --- | --- |
|
|
209
|
+
| `src` | URL of the JSON to load |
|
|
210
|
+
| `username` | GitHub username, links the caption to the profile |
|
|
211
|
+
| `locale` | Language and formatting, for example `pt-BR`. Defaults to the nearest `lang` attribute, then the browser language |
|
|
212
|
+
| `theme` | `light`, `dark` or `auto` (default, follows `prefers-color-scheme`) |
|
|
213
|
+
| `hide` | Space-separated parts to hide: `stats`, `months`, `caption`, `legend` |
|
|
214
|
+
| `animation` | Set to `none` to disable the entrance animation |
|
|
215
|
+
| `state` | Set by the component: `loading`, `ready` or `error`. Useful for styling |
|
|
216
|
+
|
|
217
|
+
### Properties and methods
|
|
218
|
+
|
|
219
|
+
| Name | Description |
|
|
220
|
+
| --- | --- |
|
|
221
|
+
| `data` | Get the normalized data, or set any accepted shape |
|
|
222
|
+
| `labels` | Partial object that overrides any text (see below) |
|
|
223
|
+
| `reload()` | Fetches `src` again |
|
|
224
|
+
|
|
225
|
+
### Events
|
|
226
|
+
|
|
227
|
+
| Event | `detail` |
|
|
228
|
+
| --- | --- |
|
|
229
|
+
| `load` | The normalized data, after `src` loads |
|
|
230
|
+
| `error` | The error, when loading or parsing fails |
|
|
231
|
+
|
|
232
|
+
## Theming
|
|
233
|
+
|
|
234
|
+
Set these custom properties on the element or any ancestor:
|
|
235
|
+
|
|
236
|
+
| Property | Default (light / dark) |
|
|
237
|
+
| --- | --- |
|
|
238
|
+
| `--gha-accent` | `#1f883d` / `#39d353`. Levels 1 to 3 are mixed from it |
|
|
239
|
+
| `--gha-level-0` | `#eff2f5` / `#151b23`. Empty day |
|
|
240
|
+
| `--gha-level-1` … `--gha-level-4` | Mixes of the accent, override any of them |
|
|
241
|
+
| `--gha-text` | `#1f2328` / `#f0f6fc` |
|
|
242
|
+
| `--gha-muted` | `#59636e` / `#9198a1` |
|
|
243
|
+
| `--gha-border` | `#d1d9e0` / `#3d444d` |
|
|
244
|
+
| `--gha-cell-gap` | `3px` |
|
|
245
|
+
| `--gha-cell-radius` | `2px` |
|
|
246
|
+
| `--gha-cell-max` | `24px`. Largest size a day can grow to |
|
|
247
|
+
|
|
248
|
+
```css
|
|
249
|
+
github-activity {
|
|
250
|
+
--gha-accent: #7c3aed;
|
|
251
|
+
--gha-level-0: #f3f0ff;
|
|
252
|
+
--gha-cell-radius: 50%;
|
|
253
|
+
}
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
Style the internals with `::part()`: `root`, `stats`, `stat`, `graph`, `months`, `cell`, `caption`, `legend`.
|
|
257
|
+
|
|
258
|
+
```css
|
|
259
|
+
github-activity::part(stat) {
|
|
260
|
+
font-family: 'JetBrains Mono', monospace;
|
|
261
|
+
}
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
The component inherits the page font.
|
|
265
|
+
|
|
266
|
+
## Languages
|
|
267
|
+
|
|
268
|
+
English (`en`), Portuguese (`pt`) and Spanish (`es`) are built in. Month names, weekdays, dates and numbers follow the locale automatically. For other languages, or to change any text, set `labels`:
|
|
269
|
+
|
|
270
|
+
```js
|
|
271
|
+
document.querySelector('github-activity').labels = {
|
|
272
|
+
total: 'Beiträge',
|
|
273
|
+
streak: 'Längste Serie',
|
|
274
|
+
busiest: 'Aktivster Tag',
|
|
275
|
+
less: 'Weniger',
|
|
276
|
+
more: 'Mehr',
|
|
277
|
+
source: 'Quelle',
|
|
278
|
+
contributions: { one: 'Beitrag', other: 'Beiträge' },
|
|
279
|
+
days: { one: 'Tag', other: 'Tage' },
|
|
280
|
+
noneOn: 'Keine Beiträge am {date}',
|
|
281
|
+
countOn: '{count} am {date}',
|
|
282
|
+
summary: '{count} auf GitHub vom {from} bis {to}',
|
|
283
|
+
range: '{from} – {to}',
|
|
284
|
+
};
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
## Browser support
|
|
288
|
+
|
|
289
|
+
Chrome and Edge 117+, Safari 16.2+, Firefox 113+. The component uses custom elements, Shadow DOM, CSS subgrid, container queries and `color-mix()`.
|
|
290
|
+
|
|
291
|
+
## Development
|
|
292
|
+
|
|
293
|
+
```sh
|
|
294
|
+
npm install
|
|
295
|
+
npm test
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
`npm test` builds `dist/` and runs the unit tests. To try the demo, serve the package folder over HTTP and open `/demo/`.
|
|
299
|
+
|
|
300
|
+
## License
|
|
301
|
+
|
|
302
|
+
MIT
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { mkdir, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { dirname, resolve } from 'node:path';
|
|
4
|
+
import { parseArgs } from 'node:util';
|
|
5
|
+
import { fetchContributions } from '../dist/server.js';
|
|
6
|
+
|
|
7
|
+
const usage = `Usage: github-activity <username> [options]
|
|
8
|
+
|
|
9
|
+
Fetches a GitHub contribution calendar and prints it as JSON for <github-activity>.
|
|
10
|
+
Reads the token from GITHUB_TOKEN (or GH_TOKEN). A token without scopes is enough.
|
|
11
|
+
|
|
12
|
+
Options:
|
|
13
|
+
-o, --out <file> Write to a file instead of stdout
|
|
14
|
+
--from <date> Start of the range (ISO date, max one year before --to)
|
|
15
|
+
--to <date> End of the range (defaults to today)
|
|
16
|
+
-h, --help Show this message`;
|
|
17
|
+
|
|
18
|
+
const fail = (message) => {
|
|
19
|
+
console.error(`github-activity: ${message}`);
|
|
20
|
+
process.exit(1);
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
let parsed;
|
|
24
|
+
try {
|
|
25
|
+
parsed = parseArgs({
|
|
26
|
+
allowPositionals: true,
|
|
27
|
+
options: {
|
|
28
|
+
out: { type: 'string', short: 'o' },
|
|
29
|
+
from: { type: 'string' },
|
|
30
|
+
to: { type: 'string' },
|
|
31
|
+
help: { type: 'boolean', short: 'h' },
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
} catch (error) {
|
|
35
|
+
fail(`${error.message}\n\n${usage}`);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const { values, positionals } = parsed;
|
|
39
|
+
|
|
40
|
+
if (values.help) {
|
|
41
|
+
console.log(usage);
|
|
42
|
+
process.exit(0);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const username = positionals[0];
|
|
46
|
+
if (!username) fail(`missing <username>\n\n${usage}`);
|
|
47
|
+
|
|
48
|
+
const token = process.env.GITHUB_TOKEN || process.env.GH_TOKEN;
|
|
49
|
+
if (!token) fail('set GITHUB_TOKEN (or GH_TOKEN) in the environment');
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
const data = await fetchContributions({ username, token, from: values.from, to: values.to });
|
|
53
|
+
const json = `${JSON.stringify(data, null, 2)}\n`;
|
|
54
|
+
if (values.out) {
|
|
55
|
+
const file = resolve(values.out);
|
|
56
|
+
await mkdir(dirname(file), { recursive: true });
|
|
57
|
+
await writeFile(file, json, 'utf8');
|
|
58
|
+
console.error(`github-activity: wrote ${data.weeks.length} weeks (${data.total} contributions) to ${values.out}`);
|
|
59
|
+
} else {
|
|
60
|
+
process.stdout.write(json);
|
|
61
|
+
}
|
|
62
|
+
} catch (error) {
|
|
63
|
+
fail(error.message.replace(/^github-activity: /, ''));
|
|
64
|
+
}
|
package/dist/data.d.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export type ContributionLevel = 0 | 1 | 2 | 3 | 4;
|
|
2
|
+
export interface ContributionDay {
|
|
3
|
+
date: string;
|
|
4
|
+
count: number;
|
|
5
|
+
level: ContributionLevel;
|
|
6
|
+
weekday: number;
|
|
7
|
+
}
|
|
8
|
+
export interface ContributionWeek {
|
|
9
|
+
days: ContributionDay[];
|
|
10
|
+
}
|
|
11
|
+
export interface Contributions {
|
|
12
|
+
total: number;
|
|
13
|
+
weeks: ContributionWeek[];
|
|
14
|
+
from: string;
|
|
15
|
+
to: string;
|
|
16
|
+
}
|
|
17
|
+
export interface ContributionStats {
|
|
18
|
+
total: number;
|
|
19
|
+
longestStreak: number;
|
|
20
|
+
busiestWeekday: number | null;
|
|
21
|
+
}
|
|
22
|
+
export interface MonthLabel {
|
|
23
|
+
column: number;
|
|
24
|
+
month: number;
|
|
25
|
+
}
|
|
26
|
+
export declare function normalize(input: unknown): Contributions;
|
|
27
|
+
export declare function getStats(weeks: ContributionWeek[]): ContributionStats;
|
|
28
|
+
export declare function getMonthLabels(weeks: ContributionWeek[], minGap?: number): MonthLabel[];
|
package/dist/data.js
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
const DATE = /^\d{4}-\d{2}-\d{2}$/;
|
|
2
|
+
const DAY = 86_400_000;
|
|
3
|
+
const MAX_DAYS = 3_700;
|
|
4
|
+
const API_LEVELS = {
|
|
5
|
+
NONE: 0,
|
|
6
|
+
FIRST_QUARTILE: 1,
|
|
7
|
+
SECOND_QUARTILE: 2,
|
|
8
|
+
THIRD_QUARTILE: 3,
|
|
9
|
+
FOURTH_QUARTILE: 4,
|
|
10
|
+
};
|
|
11
|
+
const isObject = (value) => typeof value === 'object' && value !== null;
|
|
12
|
+
const pick = (value, ...path) => path.reduce((current, key) => (isObject(current) ? current[key] : undefined), value);
|
|
13
|
+
const toDate = (value) => new Date(`${value}T00:00:00Z`);
|
|
14
|
+
const isoDay = (time) => new Date(time).toISOString().slice(0, 10);
|
|
15
|
+
const unwrap = (input) => {
|
|
16
|
+
const calendar = pick(input, 'data', 'user', 'contributionsCollection', 'contributionCalendar') ??
|
|
17
|
+
pick(input, 'contributionsCollection', 'contributionCalendar') ??
|
|
18
|
+
pick(input, 'contributionCalendar') ??
|
|
19
|
+
input;
|
|
20
|
+
if (Array.isArray(calendar))
|
|
21
|
+
return { days: calendar, total: undefined };
|
|
22
|
+
const weeks = pick(calendar, 'weeks');
|
|
23
|
+
if (Array.isArray(weeks)) {
|
|
24
|
+
return {
|
|
25
|
+
days: weeks.flatMap((week) => {
|
|
26
|
+
const days = pick(week, 'days') ?? pick(week, 'contributionDays');
|
|
27
|
+
return Array.isArray(days) ? days : [];
|
|
28
|
+
}),
|
|
29
|
+
total: pick(calendar, 'total') ?? pick(calendar, 'totalContributions'),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
throw new TypeError('github-activity: unrecognized contributions data');
|
|
33
|
+
};
|
|
34
|
+
const readDay = (value) => {
|
|
35
|
+
if (!isObject(value))
|
|
36
|
+
return null;
|
|
37
|
+
const date = value.date;
|
|
38
|
+
if (typeof date !== 'string' || !DATE.test(date))
|
|
39
|
+
return null;
|
|
40
|
+
const time = toDate(date).getTime();
|
|
41
|
+
if (Number.isNaN(time) || isoDay(time) !== date)
|
|
42
|
+
return null;
|
|
43
|
+
const rawCount = value.count ?? value.contributionCount;
|
|
44
|
+
const count = typeof rawCount === 'number' && Number.isFinite(rawCount) ? Math.max(0, Math.floor(rawCount)) : 0;
|
|
45
|
+
const rawLevel = value.level ?? (typeof value.contributionLevel === 'string' ? API_LEVELS[value.contributionLevel] : undefined);
|
|
46
|
+
const level = typeof rawLevel === 'number' && Number.isInteger(rawLevel) && rawLevel >= 0 && rawLevel <= 4
|
|
47
|
+
? rawLevel
|
|
48
|
+
: undefined;
|
|
49
|
+
return { date, count, level, weekday: toDate(date).getUTCDay() };
|
|
50
|
+
};
|
|
51
|
+
const levelFor = (count, max) => count <= 0 || max <= 0 ? 0 : Math.min(4, Math.max(1, Math.ceil((count / max) * 4)));
|
|
52
|
+
export function normalize(input) {
|
|
53
|
+
const { days: rawDays, total: rawTotal } = unwrap(input);
|
|
54
|
+
const byDate = new Map();
|
|
55
|
+
for (const raw of rawDays) {
|
|
56
|
+
const day = readDay(raw);
|
|
57
|
+
if (day)
|
|
58
|
+
byDate.set(day.date, day);
|
|
59
|
+
}
|
|
60
|
+
const sorted = [...byDate.values()].sort((a, b) => a.date.localeCompare(b.date));
|
|
61
|
+
if (sorted.length === 0)
|
|
62
|
+
throw new TypeError('github-activity: no valid days in contributions data');
|
|
63
|
+
const last = toDate(sorted[sorted.length - 1].date).getTime();
|
|
64
|
+
const start = Math.max(toDate(sorted[0].date).getTime(), last - (MAX_DAYS - 1) * DAY);
|
|
65
|
+
const parsed = [];
|
|
66
|
+
for (let time = start; time <= last; time += DAY) {
|
|
67
|
+
const date = isoDay(time);
|
|
68
|
+
parsed.push(byDate.get(date) ?? { date, count: 0, level: 0, weekday: new Date(time).getUTCDay() });
|
|
69
|
+
}
|
|
70
|
+
const max = Math.max(...parsed.map((day) => day.count));
|
|
71
|
+
const weeks = [];
|
|
72
|
+
for (const day of parsed) {
|
|
73
|
+
const normalized = { ...day, level: day.level ?? levelFor(day.count, max) };
|
|
74
|
+
const current = weeks[weeks.length - 1];
|
|
75
|
+
if (!current || normalized.weekday === 0)
|
|
76
|
+
weeks.push({ days: [normalized] });
|
|
77
|
+
else
|
|
78
|
+
current.days.push(normalized);
|
|
79
|
+
}
|
|
80
|
+
const sum = parsed.reduce((total, day) => total + day.count, 0);
|
|
81
|
+
return {
|
|
82
|
+
total: typeof rawTotal === 'number' && Number.isFinite(rawTotal) ? rawTotal : sum,
|
|
83
|
+
weeks,
|
|
84
|
+
from: parsed[0].date,
|
|
85
|
+
to: parsed[parsed.length - 1].date,
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
export function getStats(weeks) {
|
|
89
|
+
const byWeekday = Array(7).fill(0);
|
|
90
|
+
let total = 0;
|
|
91
|
+
let streak = 0;
|
|
92
|
+
let longestStreak = 0;
|
|
93
|
+
for (const day of weeks.flatMap((week) => week.days)) {
|
|
94
|
+
total += day.count;
|
|
95
|
+
byWeekday[day.weekday] += day.count;
|
|
96
|
+
streak = day.count > 0 ? streak + 1 : 0;
|
|
97
|
+
longestStreak = Math.max(longestStreak, streak);
|
|
98
|
+
}
|
|
99
|
+
const busiest = Math.max(...byWeekday);
|
|
100
|
+
return {
|
|
101
|
+
total,
|
|
102
|
+
longestStreak,
|
|
103
|
+
busiestWeekday: busiest > 0 ? byWeekday.indexOf(busiest) : null,
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
export function getMonthLabels(weeks, minGap = 3) {
|
|
107
|
+
if (weeks.length === 0)
|
|
108
|
+
return [];
|
|
109
|
+
const monthOf = (value) => toDate(value).getUTCMonth();
|
|
110
|
+
const starts = weeks.flatMap((week, column) => {
|
|
111
|
+
const first = week.days.find((day) => day.date.endsWith('-01'));
|
|
112
|
+
return first ? [{ column, month: monthOf(first.date) }] : [];
|
|
113
|
+
});
|
|
114
|
+
if (starts[0]?.column !== 0 && (starts.length === 0 || starts[0].column >= minGap)) {
|
|
115
|
+
starts.unshift({ column: 0, month: monthOf(weeks[0].days[0].date) });
|
|
116
|
+
}
|
|
117
|
+
return starts.reduce((kept, label) => {
|
|
118
|
+
const previous = kept[kept.length - 1];
|
|
119
|
+
if (!previous || label.column - previous.column >= minGap)
|
|
120
|
+
kept.push(label);
|
|
121
|
+
return kept;
|
|
122
|
+
}, []);
|
|
123
|
+
}
|
package/dist/fetch.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type Contributions } from './data.js';
|
|
2
|
+
export interface FetchContributionsOptions {
|
|
3
|
+
username: string;
|
|
4
|
+
token: string;
|
|
5
|
+
from?: string | Date;
|
|
6
|
+
to?: string | Date;
|
|
7
|
+
signal?: AbortSignal;
|
|
8
|
+
fetch?: typeof fetch;
|
|
9
|
+
}
|
|
10
|
+
export declare function fetchContributions(options: FetchContributionsOptions): Promise<Contributions>;
|
package/dist/fetch.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { normalize } from './data.js';
|
|
2
|
+
const ENDPOINT = 'https://api.github.com/graphql';
|
|
3
|
+
const USERNAME = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/i;
|
|
4
|
+
const QUERY = `
|
|
5
|
+
query($login: String!, $from: DateTime, $to: DateTime) {
|
|
6
|
+
user(login: $login) {
|
|
7
|
+
contributionsCollection(from: $from, to: $to) {
|
|
8
|
+
contributionCalendar {
|
|
9
|
+
totalContributions
|
|
10
|
+
weeks { contributionDays { date contributionCount contributionLevel weekday } }
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
`;
|
|
16
|
+
const toIso = (value) => {
|
|
17
|
+
if (value === undefined)
|
|
18
|
+
return null;
|
|
19
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
20
|
+
if (Number.isNaN(date.getTime()))
|
|
21
|
+
throw new TypeError(`github-activity: invalid date "${String(value)}"`);
|
|
22
|
+
return date.toISOString();
|
|
23
|
+
};
|
|
24
|
+
export async function fetchContributions(options) {
|
|
25
|
+
const { username, token, signal } = options;
|
|
26
|
+
const request = options.fetch ?? globalThis.fetch;
|
|
27
|
+
if (!USERNAME.test(username))
|
|
28
|
+
throw new TypeError(`github-activity: invalid GitHub username "${username}"`);
|
|
29
|
+
if (!token)
|
|
30
|
+
throw new TypeError('github-activity: a GitHub token is required');
|
|
31
|
+
const response = await request(ENDPOINT, {
|
|
32
|
+
method: 'POST',
|
|
33
|
+
headers: {
|
|
34
|
+
Authorization: `Bearer ${token}`,
|
|
35
|
+
'Content-Type': 'application/json',
|
|
36
|
+
'User-Agent': 'github-activity',
|
|
37
|
+
},
|
|
38
|
+
body: JSON.stringify({
|
|
39
|
+
query: QUERY,
|
|
40
|
+
variables: { login: username, from: toIso(options.from), to: toIso(options.to) },
|
|
41
|
+
}),
|
|
42
|
+
signal: signal ?? AbortSignal.timeout(15_000),
|
|
43
|
+
});
|
|
44
|
+
if (!response.ok)
|
|
45
|
+
throw new Error(`github-activity: GitHub API responded with HTTP ${response.status}`);
|
|
46
|
+
const json = (await response.json());
|
|
47
|
+
if (json.errors?.length) {
|
|
48
|
+
throw new Error(`github-activity: ${json.errors.map((error) => error.message).join('; ')}`);
|
|
49
|
+
}
|
|
50
|
+
if (!json.data?.user)
|
|
51
|
+
throw new Error(`github-activity: user "${username}" not found`);
|
|
52
|
+
return normalize(json);
|
|
53
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { type Contributions } from './data.js';
|
|
2
|
+
import { type Labels } from './i18n.js';
|
|
3
|
+
export type ActivityState = 'loading' | 'ready' | 'error';
|
|
4
|
+
declare const Base: typeof HTMLElement;
|
|
5
|
+
export declare class GitHubActivity extends Base {
|
|
6
|
+
#private;
|
|
7
|
+
static observedAttributes: string[];
|
|
8
|
+
constructor();
|
|
9
|
+
get data(): Contributions | null;
|
|
10
|
+
set data(value: unknown);
|
|
11
|
+
get labels(): Partial<Labels> | undefined;
|
|
12
|
+
set labels(value: Partial<Labels> | undefined);
|
|
13
|
+
connectedCallback(): void;
|
|
14
|
+
disconnectedCallback(): void;
|
|
15
|
+
attributeChangedCallback(name: string, previous: string | null, value: string | null): void;
|
|
16
|
+
reload(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
declare global {
|
|
19
|
+
interface HTMLElementTagNameMap {
|
|
20
|
+
'github-activity': GitHubActivity;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export {};
|