Skip to content

Instantly share code, notes, and snippets.

@closer27
Created March 23, 2018 13:01
Show Gist options
  • Save closer27/c87cbf2d202c5d0d828ad224182889a8 to your computer and use it in GitHub Desktop.
Save closer27/c87cbf2d202c5d0d828ad224182889a8 to your computer and use it in GitHub Desktop.
CodeSpitz75_w2_practice2
const Github = class {
constructor(id, repo) {
this._base = `https://api.github.com/repos/${id}/${repo}/contents/`;
}
load(path) {
if (!this._parser) return;
const id = 'callback' + Github._id++;
const f = Github[id] = ({data:{content}})=>{
delete Github[id];
document.head.removeChild(s);
this._parser[0](content, ...this._parser[1]);
};
const s = document.createElement('script');
s.src = `${this._base + path}?callback=Github.${id}`;
document.head.appendChild(s);
}
setParser(f, ...arg) {
this._parser = [f, arg];}
};
Github._id = 0;
<!DOCTYPE html>
<html lang="en">
<body>
<img id="a" />
<div id="b"></div>
<img id="c" />
<div id="d"></div>
<script src="Github.js"></script>
<script src="Loader.js"></script>
<script>
const el =v=>document.querySelector(v);
const d64 =v=>decodeURIComponent(
atob(v).split('').map(c=>'%' + ('00' +c.charCodeAt(0).toString(16)).slice(-2)).join('')
);
const parseMD = (v) => {
return d64(v).split('\n').map(v=>{
let i = 3;
while(i--){
if(v.startsWith('#'.repeat(i + 1))) return `<h${i + 1}>${v.substr(i + 1)}</h${i + 1}>`;
}
return v;
}).join('<br>');
};
const img = (v, el)=>el.src = 'data:text/plain;base64,' + v;
const md =(v, el)=>el.innerHTML = parseMD(v);
const loader = new Loader();
loader.addRepo('s74', 'hikaMaeng', 'codespitz75');
loader.addRouter('s74', 'jpg,png,gif', img, el('#a'));
loader.addRouter('s74', 'md', md, el('#b'));
loader.addRepo('s75', 'hikaMaeng', 'codespitz75');
loader.addRouter('s75', 'jpg,png,gif', img, el('#c'));
loader.addRouter('s75', 'md', md, el('#d'));
loader.load('s74', 'einBig.png');
loader.load('s75', 'README.md');
</script>
</body>
</html>
const Loader = class{
constructor(){
this._router = {};
this._gitRepoDict = {};
}
add(ext, f, ...arg) {
ext.split(',').forEach(v=>this._router.set(v, [f, ...arg]));
}
addRepo(repoId, uid, repoName) {
this._gitRepoDict[repoId] = new Github(uid, repoName);
}
addRouter(repoId, ext, f, ...arg) {
if (!this._router[repoId]) this._router[repoId] = new Map;
ext.split(',').forEach(v=>this._router[repoId].set(v, [f, ...arg]));
}
load(repoId, v){
const ext = v.split('.').pop();
const routerForRepoId = this._router[repoId];
if(!routerForRepoId.has(ext)) return;
const gitForRepoId = this._gitRepoDict[repoId];
if(!gitForRepoId) return;
gitForRepoId.setParser(...routerForRepoId.get(ext));
gitForRepoId.load(v);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment