Skip to content

Commit

Permalink
feat: add feature 4, github mate panel, refactor code of #15
Browse files Browse the repository at this point in the history
  • Loading branch information
camsong committed Apr 4, 2016
1 parent 0bea955 commit 9ddc220
Show file tree
Hide file tree
Showing 6 changed files with 174 additions and 162 deletions.
1 change: 1 addition & 0 deletions config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ var DEFAULT_CONFIG = {
'feature-2-enable': false,
'feature-2-interval': '5',
'feature-2-type': 'unread',
'feature-4-enable': true,
};

function mergeObject(destination, source) {
Expand Down
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"matches": ["https://github.com/*"],
"run_at": "document_end",
"css": ["style.css"],
"js": ["jquery-2.1.3.min.js", "page.js", "config.js", "script.js", "show-size.js", "tab-size.js"]
"js": ["jquery-2.1.3.min.js", "page.js", "config.js", "script.js", "show-size.js", "tab-size.js", "panel.js"]
}
],
"browser_action": {
Expand Down
4 changes: 4 additions & 0 deletions options.html
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,10 @@ <h3>GitHub Mate → Options</h3>
<option value='8'>8</option>
</select>
</tr>
<tr>
<th>Show panel(favorites and outline)</th>
<td><label>Enable <input type='checkbox' id='feature-4-enable'></label></td>
</tr>
</tbody>
</table>
</div>
Expand Down
2 changes: 2 additions & 0 deletions options.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ function renderOptions() {
document.querySelector('#feature-2-interval').value = config['feature-2-interval'];
document.querySelector('#feature-2-type').value = config['feature-2-type'];
document.querySelector('#feature-3-tab-size').value = config['feature-3-tab-size'] || '4'; // set to 4 by default
document.querySelector('#feature-4-enable').checked = config['feature-4-enable'];
renderOptionsStates();
}

Expand All @@ -20,6 +21,7 @@ function storeConfig() {
'feature-2-interval': document.querySelector('#feature-2-interval').value,
'feature-2-type': document.querySelector('#feature-2-type').value,
'feature-3-tab-size': document.querySelector('#feature-3-tab-size').value,
'feature-4-enable': document.querySelector('#feature-4-enable').checked,
});
}

Expand Down
161 changes: 0 additions & 161 deletions page.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,167 +3,6 @@ $(document).on('pjax:end', function () {
var e = document.createEvent('Events');
e.initEvent('_pjax:end', !'bubbles', !'cancelable');

updateOutlinesInPanel()

return document.dispatchEvent(e);
});


// Sidebar panel originaly by github.com/zbycz

var panel = $('div.gm_panel');

if (panel.length === 0) {
panel = $('<div class="gm_panel"></div>').html(
"<a href='#' class='add btn'>add this page</a>" +
"<b>Favorites</b>" +
"<ul class='favorites'></ul>" +
"<style>" +
".gm_panel { position: fixed; top:0; right: 0; z-index: 10;" +
" background:rgba(255,255,255,0.9); border-left: 3px #d26911 solid;border-radius: 3px; width: 200px; padding: 10px 5px 15px 15px;" +
" max-height:100%;overflow-y:auto}" +
"@media (max-width: 1400px){ .gm_panel { right:-185px; } .gm_panel:hover { right:0; } }" +
".gm_panel a.add.btn { font-size: 10px; float: right; padding: 2px 7px; }" +
".gm_panel b { line-height: 30px }" +
".gm_panel ul.favorites { margin-bottom: 2em; }" +
".gm_panel li { margin: .4em 0 0 1em; }" +
".gm_panel li span.edit { display: none; position: absolute; right:5px; cursor: pointer; }" +
".gm_panel li:hover span { display: inline; }" +
"</style>" +
"<div class='gm_outline'></div>"

);
$('body').append(panel);

setInterval(gm_refresh_favorites, 2000);
gm_refresh_favorites();

panel.on('click', 'a.add', function () {
var path = location.pathname.split('/'); // /winsite/iprace_fe/issues/779
var text = prompt('Edit title:', path[2] + ' ' + document.title);

if (!text) return;

var items = gm_get_favorites();
items.push({
loc: location.toString(),
title: document.title,
text: text
});
gm_set_favorites(items);
gm_refresh_favorites();

return false;
});

panel.on('click', 'span.edit', function () {
var items = gm_get_favorites();
var i = $(this).attr('data-i');

var pr = window.prompt('Set new title OR set blank to delete', items[i].text);
if (pr === null) return;
else if (pr === '') items.splice(i, 1);
else items[i].text = pr;

gm_set_favorites(items);
gm_refresh_favorites();
});
}

var lastString = '';
function gm_refresh_favorites() {
var ul = '';
var items = gm_get_favorites();
for (var i in items) {
var item = items[i];
//var text = decodeURIComponent(item.loc.replace(/https?:\/\/[^\/]+\//, '')).replace('+', ' ');
ul += '<li><span data-i="' + i + '" class="edit">&#9998;</span> <a href="' + item.loc + '" title="' + item.title + '">' + item.text + '</a></li>'
}
if (ul != lastString) {
lastString = ul;
panel.find('ul.favorites').html(ul);
}
}


function gm_get_favorites() {
return JSON.parse(localStorage.getItem('gm_panel')) || [{loc: 'https://rawgit.com/zbycz/github-events-viewer/master/github-event-viewer.html', text: 'My GH events', title:'default entry'}];
}
function gm_set_favorites(items) {
localStorage.setItem('gm_panel', JSON.stringify(items));
}




// Copyright (c) 2015 Dan Kaplun
// The MIT License (MIT)
// from https://github.com/dbkaplun/github-markdown-outline-extension/blob/master/index.js
// very hackily edited by zbycz to add it in panel

getHeaderLevel.REGEXP = /h(\d)/i
function getHeaderLevel ($h) {
var level = Number(((($h || {}).tagName || '').match(getHeaderLevel.REGEXP) || [])[1])
return isNaN(level) ? undefined : level
}

var headerSels = []
for (var l = 1; l <= 6; l++) headerSels.push('h'+l)
var headerSel = headerSels.join(', ')
var anchorSel = 'a[id]'

function updateOutlinesInPanel() {
var $container = document.createElement('div')
$container.classList.add('gm_outline')

Array.from(document.querySelectorAll('.markdown-body')).forEach($md => {
var $headers = Array.from($md.querySelectorAll(headerSel))


var $b = document.createElement('b')
$b.innerText = "Outline"
$container.appendChild($b)

var $outline = document.createElement('ul')
//$outline.classList.add('__github-markdown-outline')
$container.appendChild($outline)

// generate outline from headers
$headers.forEach($h => {
var level = getHeaderLevel($h)
if (!level) return
var $ul = $outline, $li, $child
for (var l = 1; l < level; l++) {
$li = $ul.lastChild || $ul.appendChild(document.createElement('li'))
$child = $li.lastChild || {}
$ul = $child.tagName === 'UL'
? $child
: $li.appendChild(document.createElement('ul'))
}
var $topic = $ul
.appendChild(document.createElement('li'))
.appendChild(document.createElement('a'))
$topic.innerText = $h.innerText
$topic.href = `#${$h.querySelector(anchorSel).id.replace(/^user-content-/, '')}`
})

// find all sublists with one item and replace with contents
Array.from($container.querySelectorAll('ul')).forEach($ul => {
var $parent = $ul.parentNode
var $li = $ul.firstChild
var $child = $li.firstChild
if ($li !== $ul.lastChild || $child.tagName !== 'UL') return
while ($child) {
$parent.insertBefore($child, $ul.nextSibling) // inserts to end of list if $ul.nextSibling is null
$child = $child.nextSibling
}
$parent.removeChild($ul)
})

})

//$md.insertBefore($container, $md.firstChild)
panel.find('.gm_outline').replaceWith($container);
}

updateOutlinesInPanel();
166 changes: 166 additions & 0 deletions panel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
/*
* @file Right panel of github mate, including favorites and markdown outline
* @thanks-to originaly implemented by github.com/zbycz
*/

function gm_get_favorites() {
return JSON.parse(localStorage.getItem('github-mate-panel-favorites')) || [{loc: 'https://github.com/rubyerme/chrome-github-mate', text: 'Default by OctoMate', title:'default entry'}];

This comment has been minimized.

Copy link
@zbycz

zbycz Apr 4, 2016

Contributor

Btw, i think the My events viewer could be more useful default, because it actually is very helpful. Would you mind adding it back? Possibly keeping both?

First I wanted to add it to the side panel, but i use it just sometimes. GH doesnt offer any other way to show your comments then this api, which is made accesible by this tool of mine..

This comment has been minimized.

Copy link
@camsong

camsong Apr 5, 2016

Author Owner

I prefer to only show a related link as demo, you can add any links locally as you want

This comment has been minimized.

Copy link
@zbycz

zbycz Apr 5, 2016

Contributor

Thats right, and I find this github tool much more related then link to Github-mate-repo.

I know everyone can delete it the first thing they do, I designed it so :-) But consider, that the first time it was there as a static link - because I took it as a good feature of the sidebar itself.

Then i realized that some wouldnt needed - so I added an option for deletion. But its kind of different - because then you cant add it back. .. but that it is not the point. The point is that I designed the sidebar with 3 features - Favorites, Show my events, Outline. You kind of (accidentaly) removed one of them.

We can also discuss to add more default links - since one can delete them - I am not against. Lets educate the users with "Github cheatsheet" as well. And of course why not the OctoMate Readme... Still I see a difference - that "My GH events" is used regulary (for people who masively use github, as i do), but the others are rather informatory - one time useful links.

}
function gm_set_favorites(items) {
localStorage.setItem('github-mate-panel-favorites', JSON.stringify(items));
}

// use lastString to avoid rerendering
var lastString = '';
function gm_refresh_favorites() {
var ul = '';
var items = gm_get_favorites();
for (var i in items) {
var item = items[i];
//var text = decodeURIComponent(item.loc.replace(/https?:\/\/[^\/]+\//, '')).replace('+', ' ');
ul += '<li><span data-i="' + i + '" class="edit">&#9998;</span> <a href="' + item.loc + '" title="' + item.title + '">' + item.text + '</a></li>'
}
if (ul != lastString) {
lastString = ul;
panelNode.find('ul.github-mate-favorites').html(ul);
}
}

// put panelNode in global
var panelNode = $('div.github-mate-panel');
function initPanelNode() {
if (panelNode.length === 0) {
panelNode = $('<div class="github-mate-panel"></div>').html(
"<a href='#' class='add btn'>Add this page</a>" +
"<b>Favorites</b>" +
"<ul class='github-mate-favorites'></ul>" +
"<div class='github-mate-outline'></div>"
);
$('body').append(panelNode);

setInterval(gm_refresh_favorites, 5000);
gm_refresh_favorites();

panelNode.on('click', 'a.add', function (e) {
var path = location.pathname.split('/'); // /winsite/iprace_fe/issues/779
var text = prompt('Edit title:', path[2] + ' ' + document.title);

if (!text) return;

var items = gm_get_favorites();
items.push({
loc: location.toString(),
title: document.title,
text: text
});
gm_set_favorites(items);
gm_refresh_favorites();
e.preventDefault();
});

panelNode.on('click', 'span.edit', function () {
var items = gm_get_favorites();
var i = $(this).attr('data-i');

var pr = window.prompt('Set new title OR set blank to delete', items[i].text);
if (pr === null) return;
else if (pr === '') items.splice(i, 1);
else items[i].text = pr;

gm_set_favorites(items);
gm_refresh_favorites();
});
}
}

function updateOutlinesInPanel() {
var $container = document.createElement('div')
$container.classList.add('github-mate-outline')

Array.from(document.querySelectorAll('.markdown-body')).forEach($md => {
var $headers = Array.from($md.querySelectorAll(headerSel))


var $b = document.createElement('b')
$b.innerText = "Outline"
$container.appendChild($b)

var $outline = document.createElement('ul')
$container.appendChild($outline)

// generate outline from headers
$headers.forEach($h => {
var level = getHeaderLevel($h)
if (!level) return
var $ul = $outline, $li, $child
for (var l = 1; l < level; l++) {
$li = $ul.lastChild || $ul.appendChild(document.createElement('li'))
$child = $li.lastChild || {}
$ul = $child.tagName === 'UL'
? $child
: $li.appendChild(document.createElement('ul'))
}
var $topic = $ul
.appendChild(document.createElement('li'))
.appendChild(document.createElement('a'))
$topic.innerText = $h.innerText
$topic.href = `#${$h.querySelector(anchorSel).id.replace(/^user-content-/, '')}`
})

// find all sublists with one item and replace with contents
Array.from($container.querySelectorAll('ul')).forEach($ul => {
var $parent = $ul.parentNode
var $li = $ul.firstChild
var $child = $li.firstChild
if ($li !== $ul.lastChild || $child.tagName !== 'UL') return
while ($child) {
$parent.insertBefore($child, $ul.nextSibling) // inserts to end of list if $ul.nextSibling is null
$child = $child.nextSibling
}
$parent.removeChild($ul)
})
})

panelNode.find('.github-mate-outline').replaceWith($container);
}


// Copyright (c) 2015 Dan Kaplun
// The MIT License (MIT)
// from https://github.com/dbkaplun/github-markdown-outline-extension/blob/master/index.js
// very hackily edited by zbycz to add it in panel
getHeaderLevel.REGEXP = /h(\d)/i
function getHeaderLevel ($h) {
var level = Number(((($h || {}).tagName || '').match(getHeaderLevel.REGEXP) || [])[1])
return isNaN(level) ? undefined : level
}

var headerSels = []
for (var l = 1; l <= 6; l++) headerSels.push('h'+l)
var headerSel = headerSels.join(', ')
var anchorSel = 'a[id]'


var Panel = {
init: function() {
chrome.runtime.sendMessage({key: "feature-4-enable"}, function(response) {
if(typeof(response.result) === 'undefined' || response.result === true) {
Panel.constructor();
} else {
console.log('GitHub Mate Panel is disabled, you can enable it in options page.');
}
});
},

constructor: function() {
// update after changed page with pjax
$(document).on('pjax:end', function () {
updateOutlinesInPanel();
});
initPanelNode();
updateOutlinesInPanel();
},

};

Panel.init();

0 comments on commit 9ddc220

Please sign in to comment.