forked from CloudColonizer/gitweets
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
372 lines (361 loc) · 11 KB
/
index.html
File metadata and controls
372 lines (361 loc) · 11 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
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>gitweets</title>
<style>
body {
font-family: sans-serif;
}
.banner {
max-width: 45rem;
margin: 0 auto 1rem auto;
padding: 0.5rem 1rem;
border: 1px solid #ccc;
background-color: #f8f9fa;
display: flex;
align-items: center;
gap: 1rem;
}
.banner h1 {margin: 0;}
.banner h1 a {color: #1da1f2; font-size: 1.5rem; white-space: nowrap; text-decoration: none;}
.banner-controls {
display: flex;
justify-content: flex-end;
align-items: center;
flex-grow: 1;
}
.banner input {
flex-grow: 1;
max-width: 20em;
padding: 0.5rem;
margin-right: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
}
.banner button {
margin-right: 0.5rem;
border: 2px solid #1da1f2;
border-radius: 4px;
background-color: transparent;
color: #1da1f2;
cursor: pointer;
transition: all 0.2s ease;
font-size: 1.2rem;
line-height: 1.5;
}
.banner button:hover {
background-color: #e8f5fe;
border-color: #0c85d0;
}
#timeline {
flex-direction: column;
max-width: 45rem;
margin: 0 auto;
padding: 1rem;
border: 1px solid #ccc;
}
/* Loading indicator styles */
#divStatus {
display: flex;
justify-content: center;
align-items: center;
padding: 1rem;
border-radius: 8px;
background-color: #f8f9fa;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
margin: 1rem auto;
width: fit-content;
font-size: 1.1rem;
color: #555;
}
.tweet {
display: flex;
padding-right: 1rem;
margin-bottom: 1em;
}
.tweet .avatar {
margin-right: 1rem;
width: 48px;
height: 48px;
border-radius: 50%;
}
.tweet .username {
font-size: 16px;
font-weight: bold;
}
.tweet .verified {
color: blue;
}
.tweet .datetime {
color:grey; font-size: 0.8em;
text-decoration: none;
}
.tweet .tweet-content {
max-width: 50em;
}
.tweet .tweet-content .medias {
display: flex;
flex-wrap: wrap;
margin-collapse: collapse;
list-style-type: none;
margin: 0;
padding-inline: 0;
}
.tweet .tweet-content li {
margin-collapse: collapse;
margin: 0 0.5rem 0.5rem 0;
flex-basis: 48%;
line-height: 0;
}
.tweet .tweet-content img {
width: 100%;
}
.tweet .tweet-content pre {
font-family: inherit;
margin: 0;
overflow-wrap: break-word;
overflow-y: auto;
color: #555;
}
/* Modal styles */
.modal {display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.4);}
.modal-header {display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;}
.modal-header h2 {margin: 0; color: #1da1f2;}
.modal #btnClose {font-size: 1.5rem; cursor: pointer;}
.modal-content {background-color: #fff; margin: 10% auto; padding: 1rem; border: 1px solid #888; width: 40em; border-radius: 8px;}
.modal-body textarea {width: 100%; height: 200px; padding: 0.5rem; margin-bottom: 1rem; border: 1px solid #ccc; border-radius: 4px; resize: vertical; box-sizing: border-box;}
.modal-footer {display: flex; justify-content: flex-end; gap: 0.5rem;}
.modal-footer button {padding: 0.5rem 1rem; border: none; border-radius: 4px; cursor: pointer; background-color: #ccc; color: #333;}
.modal #btnPost {background-color: #1da1f2; color: white;}
</style>
</head>
<body onload="load_timeline()">
<div class="banner">
<h1><a href='/'>gitweets</a></h1>
<div class="banner-controls">
<input id="inputServer" list="optServers" placeholder="Select or type a server" value="">
<datalist id="optServers">
<option selected="selected" value="https://github.com/est/gitweets">
</datalist>
<button id="btnRefresh" onclick="load_timeline()">🔄</button>
<button id="btnNewPost" onclick="openModal()">✏️</button>
<button id="btnPrev" disabled>⬅️</button>
<button id="btnNext">➡️</button>
</div>
</div>
<div id="timeline">
<div id="divStatus">Loading...</div>
</div>
<!-- Modal for composing tweet -->
<div id="composeModal" class="modal">
<div class="modal-content">
<div class="modal-header">
<h2>✍️</h2>
<span id="btnClose" onclick="closeModal()">×</span>
</div>
<div class="modal-body">
<textarea id="inputTweet" placeholder="What's up?"></textarea>
</div>
<div class="modal-footer">
<button id="btnCancel" onclick="closeModal()">Cancel</button>
<button id="btnPost">Post</button>
</div>
</div>
</div>
<script><!--
// safe html
const sh=s=>s.replaceAll('&','&').replaceAll('<','<').replaceAll('>','>')
// show date
const sd=d=>new Date(d.getTime() - d.getTimezoneOffset()*60_000).toISOString().replace('T', ' ').split('.')[0]
// render timeline tweets
function render(o){
return `
<div class="tweet" id="post-${encodeURI(o.id)}">
<a href="/${encodeURI(o.author_slug)}"><img class="avatar" src="${encodeURI(o.author_avatar)}"></a>
<div>
<span class="username${o.author_verified?' verified':''}">${sh(o.author_name)}</span>
<div class="tweet-content">
<pre style="${o.message.length>1024?'font:12px monospace':''}">${sh(o.message)}</pre>
<ul class="medias"></ul>
</div>
<a class="datetime" href="/${encodeURI(o.author_slug)}/${encodeURI(o.id)}">${sh(sd(o.date))}</a>
</div>
</div>
`}
function append_images(sha1_id, urls){
const imgs = []
urls.forEach(url=>{ // 解析图片网址,并且重新拼URL,节约一次302跳转
const m = /\/([^\/]+)\/([^\/]+)\/raw\/([^\/]+)\/static%2F(.+.webp|.jpg|.jpeg|.png|.gif|.jxl|.avif)$/.exec(url)
if (m){
imgs.push(`<li><img src="https://raw.githubusercontent.com/${m[1]}/${m[2]}/${m[3]}/static/${decodeURIComponent(m[4])}"></li>`)
}})
timeline.querySelector('.tweet#post-'+sha1_id+' .tweet-content .medias').insertAdjacentHTML(
'beforeend', imgs.join('\n'))
}
// load timeline
async function load_timeline(page){
updatePaginationButtons();
divStatus.style.display = 'block'
divStatus.innerText = "Loading..."
if (!inputServer.value) {
inputServer.value = optServers.options[0].value
}
const servers = /github.com\/(\w+\/[\w\.]+)/.exec(inputServer.value)
if (!servers) {
divStatus.innerText = "bad server"
return;
}
window.REPO = servers[1]
window.API_BASE = `https://api.github.com/repos/${window.REPO}`
const params = {per_page: 10}
if(page){
params.page = page
}else {
params.page = currentPage
}
const m = /^\/(\w+)(?:\/([0-9a-fA-F]{40}))?$/.exec(location.pathname)
if (m && m.length == 3 && m[2])
params.sha = m[2]
if (m && m.length > 1)
params.author = m[1]
var data;
if (params.sha){
data = [await (await fetch(`${API_BASE}/commits/${params.sha}`)).json()]
}
else{
data = await (await fetch(`${API_BASE}/commits?${new URLSearchParams(params).toString()}`)).json()
}
timeline.querySelectorAll(':scope #divStatus ~ *').forEach(sib => sib.remove());
if(data.length){
divStatus.style.display = 'none'
} else {
divStatus.innerText='No data'
}
// format: https://docs.github.com/en/rest/commits/commits
const media_ids = []
data.forEach(item=>{
timeline.insertAdjacentHTML('beforeend', render({
id: item.sha,
author_avatar: item.author.avatar_url,
author_slug: item.author.login,
author_verified: item.commit.verification?.verified,
author_name: item.commit.author.name,
message: item.commit.message,
date: new Date(item.commit.author.date),
}))
// 消息以半角或者全角冒号结尾,表示有图片。
if(!item.files && /(:|:)/.exec(item.commit.message.trim().slice(-1))){
media_ids.push(item.sha)
} else if (item.files) {
append_images(item.sha, item.files.map(f=>f.raw_url))
}
})
media_ids.forEach(async function(id){
const r = await (await fetch(`${API_BASE}/commits/${id}`)).json()
append_images(id, r.files.map(f=>f.raw_url))
})
}
// do post
async function post_new(access_token, text) {
const r1 = await fetch(`/.new_post?repo=${window.REPO}`, {
method: 'post', 'credentials': 'include',
body: JSON.stringify({'message': text})
})
return await r1.json()
}
function getCookie(cookie_str, name) {
return decodeURIComponent(cookie_str || '')
.split(";")
.find(row => row.trim().startsWith(name + "="))
?.split("=")[1]?.trim() || '';
}
// Modal functionality
// Using element IDs directly
function openModal() {
if (getCookie(document.cookie, 'access_token')){
btnPost.innerText = 'Post'
} else {
inputTweet.value = ''
inputTweet.placeholder = `Login and make a tweet via Github REST API.
Or you can post a tweet locally, clone the repo and
git commit --alow-empty && git push
This OAuth login will save an access_token into your browser cookie
The default and minimal required scope is public_repo (no other way for now)
Other planned methods:
- Fine Grained PAT
- Github App based single-repo
- deploy keys
`;
inputTweet.disabled = true
btnPost.innerText = 'Login'
}
composeModal.style.display = 'block'
}
function closeModal() {
inputTweet.value = ''
inputTweet.placeholder = "What's up?"
composeModal.style.display = 'none'
}
// Close modal when clicking outside the modal content
window.addEventListener('click', function(event) {
if (event.target == composeModal) {
closeModal();
}
});
window.addEventListener('keydown', function(event) {
if (event.key === 'Escape') {
closeModal();
}
});
const OAUTH_URL = "https://github.com/login/oauth/authorize?scope=public_repo&client_id=Ov23lirVyDKVPnHhDOFw"
// bind post actions
btnPost.addEventListener('click', async function() {
const text = inputTweet.value.trim();
const access_token = getCookie(document.cookie, 'access_token')
if (access_token) {
if (!text){
inputTweet.placeholder = 'Type something here!'
inputTweet.value = '';
return
}
await post_new(access_token, text)
closeModal();
load_timeline(1)
} else {
location.href = OAUTH_URL
}
});
// Pagination functionality
const urlParams = new URLSearchParams(window.location.search);
let currentPage = parseInt(urlParams.get('page')) || 1;
// Update pagination buttons state
function updatePaginationButtons() {
btnPrev.disabled = currentPage === 1;
}
// Previous page button
btnPrev.addEventListener('click', function() {
if (currentPage > 1) {
currentPage--;
if (currentPage === 1) {
// Remove page parameter for first page
const url = new URL(window.location);
url.searchParams.delete('page');
history.pushState(null, '', url);
} else {
history.pushState(null, '', `?page=${currentPage}`);
}
load_timeline(currentPage);
updatePaginationButtons();
}
});
// Next page button
btnNext.addEventListener('click', function() {
currentPage++;
history.pushState(null, '', `?page=${currentPage}`);
load_timeline(currentPage);
updatePaginationButtons();
});
--></script>
</body>
</html>