-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.html
397 lines (377 loc) · 16.5 KB
/
index.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>github explorer</title>
<style>
html,body,textarea,input{background:black; color:white; margin:0; padding:0}
a { text-decoration: none; color: white}
#gh-tbl{height:33vh; overflow:auto}
#gh-file { height: calc(66vh - 50px); width: calc(100% - 2px) }
.gh #gh-input { width: calc(100% - 2px) }
.gh table { width: 100% }
#help-div {
display: flex;
justify-content: center;
align-items: center;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 90%;
max-height: 90%;
background:black;
overflow:auto;
}
fieldset { border: 2px solid yellowgreen; }
</style>
<script src="github.js"></script>
<script src="openai.js"></script>
</head>
<body>
<div class="gh">
<table>
<tr>
<td>
<!--<input type="text" value="main" title="Branch" id="gh-branch" style="width:5em" />-->
<select id="gh-branch">
<option>main</option>
</select>
</td>
<td><button id="gh-up-btn">⇧</button></td>
<td style="width:99%">
<input type="text" value="jay23606" id="gh-input" spellcheck="false" placeholder="Enter GitHub owner name and press enter" />
</td>
<td>
<button id="gh-del">🗑️</button>
</td>
</tr>
</table>
<div id="gh-tbl">
<div id="gh-upload-div" style="display:none">
<input type="file" id="gh-upload-input" multiple />
</div>
<table></table>
</div>
<div id="gh-file-div">
<textarea id="gh-file" spellcheck="false"></textarea>
<!--<button id="gh-file-del">Delete</button>-->
<button style="float:right" id="gh-file-save">Save</button>
</div>
</div>
<div style="display:none" id="help-div">
<fieldset>
<legend><b>Help</b></legend>
<div id="inner-help-div"></div>
<button style="float:right" onclick="toggleHelp()">Close</button>
</fieldset>
</div>
<script>
//helpers
$ = id => document.getElementById(id), $el = (el, attrs = {}) => Object.assign(document.createElement(el), attrs);
$$ = sel => document.querySelectorAll(sel);
HTMLElement.prototype.on = function (e, fn) { this.addEventListener(e, fn) };
String.prototype.toPrettyDate = function(locale = 'en-US') {
const date = new Date(this);
const options = { month: 'numeric', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric', hour12: true };
return date.toLocaleString(locale, options);
};
const clearGhTbl = () => $$('#gh-tbl table tr').forEach(r => r.remove());
//vars
const ghInput = $('gh-input'), tbl = $$('#gh-tbl table')[0], ghFile = $('gh-file'), ghUpBtn = $('gh-up-btn'),
ghFileSave = $('gh-file-save'), ghDel = $('gh-del'), ghFileDiv = $('gh-file-div'), helpDiv = $('help-div'),
ghUploadDiv = $('gh-upload-div'), ghUploadInput = $('gh-upload-input'), branch = $('gh-branch'), innerHelpDiv = $('inner-help-div');
let ai = null;
//lets get the tab key working the way we might expect it to
ghFile.on('keydown', async (e) => {
if (e.key === 'Tab') {
e.preventDefault();
const start = ghFile.selectionStart;
const end = ghFile.selectionEnd;
const value = ghFile.value;
ghFile.value = value.substring(0, start) + ' ' + value.substring(end);
ghFile.selectionStart = ghFile.selectionEnd = start + 4;
} else if (e.key === 'F1' || e.key === 'Escape') {
e.preventDefault();
if (helpDiv.style.display === 'none') {
if (ghFile.selectionStart !== ghFile.selectionEnd) {
const selectedText = ghFile.value.substring(ghFile.selectionStart, ghFile.selectionEnd);
const token = localStorage.getItem('OPENAI_API_KEY') || (prompt("Please input OpenAI API key (stored in browser cache)", "") || '').trim();
ai = new OpenAI(token);
helpDiv.style.display = 'block'
helpDiv.focus();
await ai.chat(selectedText, innerHelpDiv)
} else helpDiv.style.display = 'block';
} else {
helpDiv.style.display = 'none';
if (ai) ai.stopStreaming = true;
}
} else if (e.ctrlKey && e.keyCode === 83) {
e.preventDefault();
ghFileSave.click(); //allows save using Ctrl+s
}
});
const toggleHelp = () => {
if (helpDiv.style.display !== 'none') {
helpDiv.style.display = 'none';
if (ai) ai.stopStreaming = true;
} else {
helpDiv.style.display = 'block';
}
}
document.body.on('keydown', (e) => {
if (!(e.target && (e.target.id === 'gh-file'))) {
if (e.key === 'F1' || e.key === 'Escape') {
e.preventDefault();
toggleHelp();
}
}
})
//handle enter key
ghInput.on('keydown', (e) => (e.key === 'Enter') ? handleEnter() : '');
branch.on('change', () => handleEnter());
const handleEnter = () =>{
ghFile.value = '';
ghFileDiv.style.display = 'none';
const arr = ghInput.value.split('/');
const junk = arr.length===2 && arr[1].trim()=='';
if (arr.length === 1 || junk) {
if (junk) ghInput.value = arr[0];
fetchRepos()
} else fetchDirs();
}
//handle Up button
ghUpBtn.on('click', e => {
const arr = ghInput.value.split('/');
if (arr.length < 2) return;
ghInput.value = arr.slice(0, arr.length - 1).join('/');
handleEnter();
});
ghDel.on('click', async (e) => {
const { token, owner, repo, path } = parseGitHubInput();
if (path && path !== '') {
if (!confirm(`Click OK to confirm deletion of file "${path}"`)) return;
const gh = new GitHub(token, owner, repo, branch.value);
await gh.deleteFile(path, "deleted using github-explorer");
ghUpBtn.click();
} else {
////otherwise we want to delete a repo (keep in mind this requires delete_repo permissions)
if (!confirm(`Click OK to confirm deletion of repo "${repo}"`)) return;
fetch(`https://api.github.com/repos/${owner}/${repo}`, { method: "DELETE", headers: { Authorization: `Bearer ${token}` } })
.then((response) => { console.log(response); ghUpBtn.click() })
.catch((error) => console.log(error));
}
});
//retrieve token, owner, repo, path
const parseGitHubInput = () => {
const token = localStorage.getItem('GITHUB_API_KEY') || (prompt("Please input GITHUB_API_KEY", "") || '').trim();
token && token.length >= 10 && localStorage.setItem('GITHUB_API_KEY', token);
const [owner, repo, ...pathArr] = ghInput.value.split('/');
const path = pathArr.join('/');
return { token, owner, repo, path };
};
//fetch the repos using graphql and show as a link column and last modified column
const fetchRepos = () => {
ghUploadDiv.style.display = 'none';
clearGhTbl();
const { token, owner } = parseGitHubInput();
if (!owner) return;
const query = `
query {
user(login: "${owner}") {
repositories(first: 100, orderBy: {field: NAME, direction: ASC}) {
edges {
node {
name
updatedAt
viewerCanAdminister
}
}
}
}
}
`;
fetch("https://api.github.com/graphql", {
method: "POST",
headers: {Authorization: `Bearer ${token}`,"Content-Type": "application/json"},
body: JSON.stringify({ query })
})
.then(response => response.json()).then(data => {
const repos = data.data.user.repositories.edges;
repos.forEach(repo => {
repo = repo.node;
const newRow = tbl.insertRow();
let newCell = newRow.insertCell(), newText = null;
if (!repo.viewerCanAdminister) {
newText = $el('A', { href: '#', textContent: '🔀', title: 'Fork this repo' });
newText.on('click', e => forkRepo(token, owner, repo.name));
newCell.appendChild(newText);
}
newText = $el('A', { href: '#', textContent: repo.name, style: 'color:greenyellow' });
newText.on('click', e => {
ghInput.value += `/${repo.name}`;
fetchDirs();
});
newCell.appendChild(newText);
newCell = newRow.insertCell();
newText = document.createTextNode(repo.updatedAt.toPrettyDate());
newCell.appendChild(newText);
});
}).catch(error => console.error(error));
}
const forkRepo = (token, owner, repo) => {
fetch(`https://api.github.com/repos/${owner}/${repo}/forks`, {method: "POST",headers: {Authorization: `Bearer ${token}`}})
.then(response => response.json()).then(data => {
ghInput.value = data.full_name;
fetchDirs();
})
.catch((error) => console.log(error));
}
let tryRepoCount = {};
const createRepo = (repo, token, path) => {
const repoData = { name: repo, auto_init: true };
const currentCount = (!tryRepoCount[repo]) ? 0 : tryRepoCount[repo];
tryRepoCount[repo] = currentCount + 1;
if (tryRepoCount[repo] > 1) return; //prevent flooding if we already tried to create the repo once
return fetch('https://api.github.com/user/repos', {
method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify(repoData)
}).then(response => response.json()).then(data => fetchDirs());
};
//We need to check the branch first
const fetchDirs = () => {
ghUploadDiv.style.display = 'block';
const { token, owner, repo, path } = parseGitHubInput();
//make sure the branch actually exists
fetch(`https://api.github.com/repos/${owner}/${repo}/branches`, { headers: { Authorization: `Bearer ${token}` } })
.then(response => response.json()).then(branches => {
//console.log(branches);
const val = branch.value;
//const hasBranch = branches.some(b => b.name === val);
branch.innerHTML = '';
let hasBranch = false;
branches.forEach(b => {
if (b.name === val) hasBranch = true;
const option = document.createElement('option');
option.value = b.name;
option.text = b.name;
branch.appendChild(option);
});
if (hasBranch) branch.value = val;
//if (!hasBranch) branch.value = branches[0].name;
fetchDirs2(token, owner, repo, path);
}).catch(error => {
//if we fail here generally it means the repo doesn't exist and we should create it
createRepo(repo, token, path);
});
}
//fetch files within repo and show as a link column (blob or tree) and lineCount column
//if it fails, we assume we want to create a new file based on text input provided
const fetchDirs2 = (token, owner, repo, path) => {
const query = `
query($owner: String!, $repo: String!) {
repository(owner: $owner, name: $repo) {
nameWithOwner
object(expression: "${branch.value}:${path}") { #HEAD
... on Tree {
entries {
name
path
type
lineCount
}
}
}
}
}
`;
//console.log(query);
fetch('https://api.github.com/graphql', {
method: 'POST',
headers: {'Content-Type': 'application/json','Authorization': `Bearer ${token}`},
body: JSON.stringify({
query: query,
variables: { owner, repo }
})
}).then(response => response.json()).then(data => {
//console.log(data);
const entries = data.data.repository.object.entries;
entries.sort((a, b) => a.name.localeCompare(b.name));
const nameWithOwner = data.data.repository.nameWithOwner
//console.log(entries);
clearGhTbl();
entries.forEach(entry => {
const newRow = tbl.insertRow();
let newCell = newRow.insertCell();
let newText = null;
if(entry.type === 'blob'){
newText = $el('A', { href: `https://raw.githack.com/${nameWithOwner}/${branch.value}/${entry.path}`, title:'Open content in new tab', textContent: '🌐', target: '_blank' });
newCell.appendChild(newText);
}
newText = $el('A', { href: '#', textContent: entry.name, style: (entry.type === 'tree') ? 'color:greenyellow' : '' });
newText.on('click', e=>{
ghInput.value = `${nameWithOwner}/${entry.path}`;
if (entry.type === 'blob') fetchFile();
else if(entry.type === 'tree') fetchDirs();
});
newCell.appendChild(newText);
//show line count since modified date is hard to get here
newCell = newRow.insertCell();
newText = document.createTextNode(entry.lineCount || '');
newCell.appendChild(newText);
});
}).catch(error => {
//console.log(error);
//we must be trying to create a new file if this error is caught
ghFileDiv.style.display = 'block';
ghFile.focus();
ghFileSave.onclick = async () => {
const { token, owner, repo, path } = parseGitHubInput();
const gh = new GitHub(token, owner, repo, branch.value);
await gh.createOrUpdateFile(path, ghFile.value, "added using github-explorer");
ghUpBtn.click();
};
});
}
//fetch a file that was identified as a blob by api and allow it to be modifed or deleted
const fetchFile = () => {
const { token, owner, repo, path } = parseGitHubInput();
fetch(`https://api.github.com/repos/${owner}/${repo}/contents/${path}?ref=${branch.value}`, {headers: { Authorization: `Bearer ${token}` }})
.then(response => response.json()).then(data => {
ghFile.value = atob(data.content)
ghFile.focus();
ghFileDiv.style.display = 'block';
ghFileSave.onclick = async () => {
const gh = new GitHub(token, owner, repo, branch.value);
await gh.createOrUpdateFile(path, ghFile.value, "updated using github-explorer");
ghUpBtn.click();
};
})
.catch(error => console.error(error));
}
//allow upload of files directly to github from file input (uses some delays--may be a better way)
const uploadFiles = async (input) => {
const { token, owner, repo, path } = parseGitHubInput();
const files = input.files;
for (const file of files) {
const reader = new FileReader();
reader.onload = async (e) => {
const contents = e.target.result;
const gh = new GitHub(token, owner, repo, branch.value);
//console.log((path === '') ? file.name : path + '/' + file.name)
await gh.createOrUpdateFile((path === '') ? file.name : path + '/' + file.name, contents, "uploaded using github-explorer");
};
reader.readAsBinaryString(file);
await new Promise(resolve => setTimeout(resolve, 150));
}
setTimeout(() => { input.value = ''; handleEnter() }, 150);
}
ghUploadInput.on('change', async () => await uploadFiles(ghUploadInput));
const queryString = location.search;
const urlParams = new URLSearchParams(queryString);
if (urlParams.has('owner')) ghInput.value = urlParams.get('owner');
handleEnter();
</script>
</body>
</html>