-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
74 lines (70 loc) · 2.57 KB
/
index.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
const {render} = require('tree-from-paths');
chrome.runtime.onMessage.addListener(({action}, sender, sendRes)=>{
if(action ==='run_main'){
modalShown()
.then(addListeners)
.then(getName)
.then(getTree)
.then(createTree)
.catch(err=>{
//TODO - Maybe do some clean up here
console.log(err);
})
.then(()=>sendRes({status:'done'}))
}
return true
})
//Make a directory tree and inject it into HTML
const createTree = async ({paths, name, tree}) => {
document.querySelector('#hubtree-modal-inner').innerHTML = render( paths, '',(parent, file, explicit) => {
const type = (tree.find(item=>{
//Account for extra slash the package adds to file name
if(file[file.length-1] === '/') return item.path===(parent+file.slice(0, file.length-1))
return item.path===(parent+file)
})).type
return `<a target="_blank" class="link" href=" https://github.com/${name}/${type}/master/${parent}${file}" > ${file}</a> <br>`
})
};
//Add modal to webpage
const addModal = async () =>{
const modalDiv = document.createElement('div');
modalDiv.id = 'hubtree-modal';
modalDiv.classList.add('hubtree-modal');
const modalInnerHtml = `<div id="hubtree-modal-inner" class="hubtree-modal-inner"> </div>`
modalDiv.innerHTML = modalInnerHtml;
document.body.appendChild(modalDiv);
}
//Check if modal is shown
const modalShown = async () =>{
const modal = document.querySelector('#hubtree-modal');
//If shown remove modal, if not shown create
if (modal) {
modal.parentNode.removeChild(modal)
throw new Error('Closed Modal');
}
await addModal()
return true
}
//Get the name of the repository
const getName = async () => {
const name = document.querySelector('meta[property="og:title"]').content;
console.log(name)
//TODO - There is probably a better way to validate being in a repository
if(name && name.includes('/')) return name;
throw new Error('Name does not exist')
}
const getTree = async (name) =>{
const endpoint = `https://api.github.com/repos/${name}/git/trees/master?recursive=1`
const treeData = await fetch(endpoint).then(res=>{
if(res.ok) return res.json();
throw new Error('Problem with request')
})
const paths = treeData.tree.map(item=>item.path);
if(paths.length > 0) return {paths, name, tree: treeData.tree};
throw new Error('No paths');
}
const addListeners = async () =>{
document.querySelector('#hubtree-modal').addEventListener('click', (e)=>{
if(e.target === e.currentTarget) modalShown().catch(err=>console.log(err));
})
}