';
emojify.run($('.editor-preview')[0]);
}
);
}, 0);
return "Loading...";
},
renderingConfig: {
singleLineBreaks: false
},
indentWithTabs: false,
tabSize: 4,
spellChecker: false,
toolbar: ["bold", "italic", "strikethrough", "|",
"code", "quote", "|",
"unordered-list", "ordered-list", "|",
"link", "image", "table"]
})
});
}
}
var editArea;
var editFilename;
var smdEditor;
var cmEditor;
var markdownFileExts;
var lineWrapExtensions;
// For IE
String.prototype.endsWith = function (pattern) {
var d = this.length - pattern.length;
return d >= 0 && this.lastIndexOf(pattern) === d;
};
// Adding function to get the cursor position in a text field to jquery objects
(function ($, undefined) {
$.fn.getCursorPosition = function () {
var el = $(this).get(0);
var pos = 0;
if ('selectionStart' in el) {
pos = el.selectionStart;
} else if ('selection' in document) {
el.focus();
var Sel = document.selection.createRange();
var SelLength = document.selection.createRange().text.length;
Sel.moveStart('character', -el.value.length);
pos = Sel.text.length - SelLength;
}
return pos;
}
})(jQuery);
function initEditor() {
editFilename = $("#file-name");
editFilename.keyup(function (e) {
var sections = $('.breadcrumb span.section');
var dividers = $('.breadcrumb div.divider');
if (e.keyCode == 8) {
if ($(this).getCursorPosition() == 0) {
if (sections.length > 0) {
var value = sections.last().find('a').text();
$(this).val(value + $(this).val());
$(this)[0].setSelectionRange(value.length, value.length);
sections.last().remove();
dividers.last().remove();
}
}
}
if (e.keyCode == 191) {
var parts = $(this).val().split('/');
for (var i = 0; i < parts.length; ++i) {
var value = parts[i];
if (i < parts.length - 1) {
if (value.length) {
$('' + value + '').insertBefore($(this));
$('
/
').insertBefore($(this));
}
}
else {
$(this).val(value);
}
$(this)[0].setSelectionRange(0, 0);
}
}
var parts = [];
$('.breadcrumb span.section').each(function (i, element) {
element = $(element);
if (element.find('a').length) {
parts.push(element.find('a').text());
} else {
parts.push(element.text());
}
});
if ($(this).val())
parts.push($(this).val());
$('#tree-name').val(parts.join('/'));
}).trigger('keyup');
editArea = $('.repository.editor textarea#edit_area');
if (!editArea.length)
return;
markdownFileExts = editArea.data("markdown-file-exts").split(",");
lineWrapExtensions = editArea.data("line-wrap-extensions").split(",");
editFilename.on("keyup", function (e) {
var val = editFilename.val(), m, mode, spec, extension, extWithDot, previewLink, dataUrl, apiCall;
extension = extWithDot = "";
if (m = /.+\.([^.]+)$/.exec(val)) {
extension = m[1];
extWithDot = "." + extension;
}
var info = CodeMirror.findModeByExtension(extension);
previewLink = $('a[data-tab=preview]');
if (info) {
mode = info.mode;
spec = info.mime;
apiCall = mode;
}
else {
apiCall = extension
}
if (previewLink.length && apiCall && previewFileModes && previewFileModes.length && previewFileModes.indexOf(apiCall) >= 0) {
dataUrl = previewLink.data('url');
previewLink.data('url', dataUrl.replace(/(.*)\/.*/i, '$1/' + mode));
previewLink.show();
}
else {
previewLink.hide();
}
// If this file is a Markdown extensions, we will load that editor and return
if (markdownFileExts.indexOf(extWithDot) >= 0) {
if (setSimpleMDE()) {
return;
}
}
// Else we are going to use CodeMirror
if (!cmEditor && !setCodeMirror()) {
return;
}
if (mode) {
cmEditor.setOption("mode", spec);
CodeMirror.autoLoadMode(cmEditor, mode);
}
if (lineWrapExtensions.indexOf(extWithDot) >= 0) {
cmEditor.setOption("lineWrapping", true);
}
else {
cmEditor.setOption("lineWrapping", false);
}
}).trigger('keyup');
}
function setSimpleMDE() {
if (cmEditor) {
cmEditor.toTextArea();
cmEditor = null;
}
if (smdEditor) {
return true;
}
smdEditor = new SimpleMDE({
autoDownloadFontAwesome: false,
element: editArea[0],
forceSync: true,
renderingConfig: {
singleLineBreaks: false
},
indentWithTabs: false,
tabSize: 4,
spellChecker: false,
previewRender: function (plainText, preview) { // Async method
setTimeout(function () {
// FIXME: still send render request when return back to edit mode
$.post(editArea.data('url'), {
"_csrf": csrf,
"mode": "gfm",
"context": editArea.data('context'),
"text": plainText
},
function (data) {
preview.innerHTML = '
' + data + '
';
emojify.run($('.editor-preview')[0]);
}
);
}, 0);
return "Loading...";
},
toolbar: ["bold", "italic", "strikethrough", "|",
"heading-1", "heading-2", "heading-3", "heading-bigger", "heading-smaller", "|",
"code", "quote", "|",
"unordered-list", "ordered-list", "|",
"link", "image", "table", "horizontal-rule", "|",
"clean-block", "preview", "fullscreen", "side-by-side"]
});
return true;
}
function setCodeMirror() {
if (smdEditor) {
smdEditor.toTextArea();
smdEditor = null;
}
if (cmEditor) {
return true;
}
cmEditor = CodeMirror.fromTextArea(editArea[0], {
lineNumbers: true
});
cmEditor.on("change", function (cm, change) {
editArea.val(cm.getValue());
});
return true;
}
function initQuickPull() {
$('.js-quick-pull-choice-option').change(function () {
quickPullChoiceChange();
});
quickPullChoiceChange();
}
function quickPullChoiceChange() {
var radio = $('.js-quick-pull-choice-option:checked');
if (radio.val() == 'commit-to-new-branch')
$('.quick-pull-branch-name').show();
else
$('.quick-pull-branch-name').hide();
}
function initOrganization() {
if ($('.organization').length == 0) {
return;
}
// Options
if ($('.organization.settings.options').length > 0) {
$('#org_name').keyup(function () {
var $prompt_span = $('#org-name-change-prompt');
if ($(this).val().toString().toLowerCase() != $(this).data('org-name').toString().toLowerCase()) {
$prompt_span.show();
} else {
$prompt_span.hide();
}
});
}
}
function initUserSettings() {
console.log('initUserSettings');
// Options
if ($('.user.settings.profile').length > 0) {
$('#username').keyup(function () {
var $prompt_span = $('#name-change-prompt');
if ($(this).val().toString().toLowerCase() != $(this).data('name').toString().toLowerCase()) {
$prompt_span.show();
} else {
$prompt_span.hide();
}
});
}
}
function initWebhook() {
if ($('.new.webhook').length == 0) {
return;
}
$('.events.checkbox input').change(function () {
if ($(this).is(':checked')) {
$('.events.fields').show();
}
});
$('.non-events.checkbox input').change(function () {
if ($(this).is(':checked')) {
$('.events.fields').hide();
}
});
// Test delivery
$('#test-delivery').click(function () {
var $this = $(this);
$this.addClass('loading disabled');
$.post($this.data('link'), {
"_csrf": csrf
}).done(
setTimeout(function () {
window.location.href = $this.data('redirect');
}, 5000)
)
});
}
function initAdmin() {
if ($('.admin').length == 0) {
return;
}
// New user
if ($('.admin.new.user').length > 0 ||
$('.admin.edit.user').length > 0) {
$('#login_type').change(function () {
if ($(this).val().substring(0, 1) == '0') {
$('#login_name').removeAttr('required');
$('.non-local').hide();
$('.local').show();
$('#user_name').focus();
if ($(this).data('password') == "required") {
$('#password').attr('required', 'required');
}
} else {
$('#login_name').attr('required', 'required');
$('.non-local').show();
$('.local').hide();
$('#login_name').focus();
$('#password').removeAttr('required');
}
});
}
function onSecurityProtocolChange() {
if ($('#security_protocol').val() > 0) {
$('.has-tls').show();
} else {
$('.has-tls').hide();
}
}
// New authentication
if ($('.admin.new.authentication').length > 0) {
$('#auth_type').change(function () {
$('.ldap').hide();
$('.dldap').hide();
$('.smtp').hide();
$('.pam').hide();
$('.has-tls').hide();
var auth_type = $(this).val();
switch (auth_type) {
case '2': // LDAP
$('.ldap').show();
break;
case '3': // SMTP
$('.smtp').show();
$('.has-tls').show();
break;
case '4': // PAM
$('.pam').show();
break;
case '5': // LDAP
$('.dldap').show();
break;
}
if (auth_type == '2' || auth_type == '5') {
onSecurityProtocolChange()
}
});
$('#security_protocol').change(onSecurityProtocolChange)
}
// Edit authentication
if ($('.admin.edit.authentication').length > 0) {
var auth_type = $('#auth_type').val();
if (auth_type == '2' || auth_type == '5') {
$('#security_protocol').change(onSecurityProtocolChange);
}
}
// Notice
if ($('.admin.notice')) {
var $detail_modal = $('#detail-modal');
// Attach view detail modals
$('.view-detail').click(function () {
$detail_modal.find('.content p').text($(this).data('content'));
$detail_modal.modal('show');
return false;
});
// Select actions
var $checkboxes = $('.select.table .ui.checkbox');
$('.select.action').click(function () {
switch ($(this).data('action')) {
case 'select-all':
$checkboxes.checkbox('check');
break;
case 'deselect-all':
$checkboxes.checkbox('uncheck');
break;
case 'inverse':
$checkboxes.checkbox('toggle');
break;
}
});
$('#delete-selection').click(function () {
var $this = $(this);
$this.addClass("loading disabled");
var ids = [];
$checkboxes.each(function () {
if ($(this).checkbox('is checked')) {
ids.push($(this).data('id'));
}
});
$.post($this.data('link'), {
"_csrf": csrf,
"ids": ids
}).done(function () {
window.location.href = $this.data('redirect');
});
});
}
}
function buttonsClickOnEnter() {
$('.ui.button').keypress(function (e) {
if (e.keyCode == 13 || e.keyCode == 32) // enter key or space bar
$(this).click();
});
}
function hideWhenLostFocus(body, parent) {
$(document).click(function (e) {
var target = e.target;
if (!$(target).is(body) && !$(target).parents().is(parent)) {
$(body).hide();
}
});
}
function searchUsers() {
if (!$('#search-user-box .results').length) {
return;
}
var $search_user_box = $('#search-user-box');
var $result_list = $search_user_box.find('.results');
$search_user_box.keyup(function () {
var $this = $(this);
var keyword = $this.find('input').val();
if (keyword.length < 2) {
$result_list.hide();
return;
}
$.ajax({
url: suburl + '/api/v1/users/search?q=' + keyword,
dataType: "json",
success: function (response) {
var notEmpty = function (str) {
return str && str.length > 0;
};
$result_list.html('');
if (response.ok && response.data.length) {
var html = '';
$.each(response.data, function (i, item) {
html += '
' + item.username + '';
if (notEmpty(item.full_name)) {
html += ' (' + item.full_name + ')';
}
html += '
';
});
$result_list.html(html);
$this.find('.results .item').click(function () {
$this.find('input').val($(this).find('.username').text());
$result_list.hide();
});
$result_list.show();
} else {
$result_list.hide();
}
}
});
});
$search_user_box.find('input').focus(function () {
$search_user_box.keyup();
});
hideWhenLostFocus('#search-user-box .results', '#search-user-box');
}
// FIXME: merge common parts in two functions
function searchRepositories() {
if (!$('#search-repo-box .results').length) {
return;
}
var $search_repo_box = $('#search-repo-box');
var $result_list = $search_repo_box.find('.results');
$search_repo_box.keyup(function () {
var $this = $(this);
var keyword = $this.find('input').val();
if (keyword.length < 2) {
$result_list.hide();
return;
}
$.ajax({
url: suburl + '/api/v1/repos/search?q=' + keyword + "&uid=" + $search_repo_box.data('uid'),
dataType: "json",
success: function (response) {
var notEmpty = function (str) {
return str && str.length > 0;
};
$result_list.html('');
if (response.ok && response.data.length) {
var html = '';
$.each(response.data, function (i, item) {
html += '
' + item.full_name + '
';
});
$result_list.html(html);
$this.find('.results .item').click(function () {
$this.find('input').val($(this).find('.fullname').text().split("/")[1]);
$result_list.hide();
});
$result_list.show();
} else {
$result_list.hide();
}
}
});
});
$search_repo_box.find('input').focus(function () {
$search_repo_box.keyup();
});
hideWhenLostFocus('#search-repo-box .results', '#search-repo-box');
}
function initCodeView() {
if ($('.code-view .linenums').length > 0) {
$(document).on('click', '.lines-num span', function (e) {
var $select = $(this);
var $list = $select.parent().siblings('.lines-code').find('ol.linenums > li');
selectRange($list, $list.filter('[rel=' + $select.attr('id') + ']'), (e.shiftKey ? $list.filter('.active').eq(0) : null));
deSelect();
});
$(window).on('hashchange', function (e) {
var m = window.location.hash.match(/^#(L\d+)\-(L\d+)$/);
var $list = $('.code-view ol.linenums > li');
var $first;
if (m) {
$first = $list.filter('.' + m[1]);
selectRange($list, $first, $list.filter('.' + m[2]));
$("html, body").scrollTop($first.offset().top - 200);
return;
}
m = window.location.hash.match(/^#(L\d+)$/);
if (m) {
$first = $list.filter('.' + m[1]);
selectRange($list, $first);
$("html, body").scrollTop($first.offset().top - 200);
}
}).trigger('hashchange');
}
}
var $dropz;
$(document).ready(function () {
csrf = $('meta[name=_csrf]').attr("content");
suburl = $('meta[name=_suburl]').attr("content");
// Show exact time
$('.time-since').each(function () {
$(this).addClass('poping up').attr('data-content', $(this).attr('title')).attr('data-variation', 'inverted tiny').attr('title', '');
});
// Semantic UI modules.
$('.dropdown').dropdown();
$('.jump.dropdown').dropdown({
action: 'hide',
onShow: function () {
$('.poping.up').popup('hide');
}
});
$('.slide.up.dropdown').dropdown({
transition: 'slide up'
});
$('.upward.dropdown').dropdown({
direction: 'upward'
});
$('.ui.accordion').accordion();
$('.ui.checkbox').checkbox();
$('.ui.progress').progress({
showActivity: false
});
$('.poping.up').popup();
$('.top.menu .poping.up').popup({
onShow: function () {
if ($('.top.menu .menu.transition').hasClass('visible')) {
return false;
}
}
});
$('.tabular.menu .item').tab();
$('.tabable.menu .item').tab();
$('.toggle.button').click(function () {
$($(this).data('target')).slideToggle(100);
});
// Highlight JS
if (typeof hljs != 'undefined') {
hljs.initHighlightingOnLoad();
}
// Dropzone
var $dropz = $('#dropzone');
if ($dropz.length > 0) {
// Disable auto discover for all elements:
Dropzone.autoDiscover = false;
var filenameDict = {};
$dropz.dropzone({
url: $dropz.data('upload-url'),
headers: {"X-Csrf-Token": csrf},
maxFiles: $dropz.data('max-file'),
maxFilesize: $dropz.data('max-size'),
acceptedFiles: ($dropz.data('accepts') === '*/*') ? null : $dropz.data('accepts'),
addRemoveLinks: true,
dictDefaultMessage: $dropz.data('default-message'),
dictInvalidFileType: $dropz.data('invalid-input-type'),
dictFileTooBig: $dropz.data('file-too-big'),
dictRemoveFile: $dropz.data('remove-file'),
init: function () {
this.on("success", function (file, data) {
filenameDict[file.name] = data.uuid;
var input = $('').val(data.uuid);
$('.files').append(input);
});
this.on("removedfile", function (file) {
if (file.name in filenameDict) {
$('#' + filenameDict[file.name]).remove();
}
if ($dropz.data('remove-url') && $dropz.data('csrf')) {
$.post($dropz.data('remove-url'), {file: filenameDict[file.name], _csrf: $dropz.data('csrf')});
}
})
}
});
}
// Emojify
emojify.setConfig({
img_dir: suburl + '/img/emoji',
ignore_emoticons: true
});
var hasEmoji = document.getElementsByClassName('has-emoji');
for (var i = 0; i < hasEmoji.length; i++) {
emojify.run(hasEmoji[i]);
}
// Clipboard JS
var clipboard = new Clipboard('.clipboard');
clipboard.on('success', function (e) {
e.clearSelection();
$('#' + e.trigger.getAttribute('id')).popup('destroy');
e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-success'))
$('#' + e.trigger.getAttribute('id')).popup('show');
e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
});
clipboard.on('error', function (e) {
$('#' + e.trigger.getAttribute('id')).popup('destroy');
e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-error'))
$('#' + e.trigger.getAttribute('id')).popup('show');
e.trigger.setAttribute('data-content', e.trigger.getAttribute('data-original'))
});
// Clipboard for copying filename on edit page
if ($('.clipboard-tree-name').length) {
new Clipboard(document.querySelector('.clipboard-tree-name'), {
text: function () {
return $('#tree-name').val();
}
});
}
// Helpers.
$('.delete-button').click(function () {
var $this = $(this);
$('.delete.modal').modal({
closable: false,
onApprove: function () {
if ($this.data('type') == "form") {
$($this.data('form')).submit();
return;
}
$.post($this.data('url'), {
"_csrf": csrf,
"id": $this.data("id")
}).done(function (data) {
window.location.href = data.redirect;
});
}
}).modal('show');
return false;
});
$('.show-panel.button').click(function () {
$($(this).data('panel')).show();
});
$('.show-modal.button').click(function () {
$($(this).data('modal')).modal('show');
});
$('.delete-post.button').click(function () {
var $this = $(this);
$.post($this.data('request-url'), {
"_csrf": csrf
}).done(function () {
window.location.href = $this.data('done-url');
});
});
// Set anchor.
$('.markdown').each(function () {
var headers = {};
$(this).find('h1, h2, h3, h4, h5, h6').each(function () {
var node = $(this);
var val = encodeURIComponent(node.text().toLowerCase().replace(/[^\w\- ]/g, '').replace(/[ ]/g, '-'));
var name = val;
if (headers[val] > 0) {
name = val + '-' + headers[val];
}
if (headers[val] == undefined) {
headers[val] = 1;
} else {
headers[val] += 1;
}
node = node.wrap('');
node.append('');
});
});
buttonsClickOnEnter();
searchUsers();
searchRepositories();
initCommentForm();
initInstall();
initRepository();
initWikiForm();
initIssueForm();
initEditForm();
initEditor();
initOrganization();
initWebhook();
initAdmin();
initQuickPull();
var routes = {
'div.user.settings': initUserSettings,
'div.repository.settings.collaboration': initRepositoryCollaboration
};
var selector;
for (selector in routes) {
if ($(selector).length > 0) {
routes[selector]();
break;
}
}
});
function changeHash(hash) {
if (history.pushState) {
history.pushState(null, null, hash);
}
else {
location.hash = hash;
}
}
function deSelect() {
if (window.getSelection) {
window.getSelection().removeAllRanges();
} else {
document.selection.empty();
}
}
function selectRange($list, $select, $from) {
$list.removeClass('active');
if ($from) {
var a = parseInt($select.attr('rel').substr(1));
var b = parseInt($from.attr('rel').substr(1));
var c;
if (a != b) {
if (a > b) {
c = a;
a = b;
b = c;
}
var classes = [];
for (var i = a; i <= b; i++) {
classes.push('.L' + i);
}
$list.filter(classes.join(',')).addClass('active');
changeHash('#L' + a + '-' + 'L' + b);
return
}
}
$select.addClass('active');
changeHash('#' + $select.attr('rel'));
}
$(window).load(function () {
initCodeView();
// Repo clone url.
if ($('#repo-clone-url').length > 0) {
switch (localStorage.getItem('repo-clone-protocol')) {
case 'ssh':
if ($('#repo-clone-ssh').click().length === 0) {
$('#repo-clone-https').click();
}
break;
default:
$('#repo-clone-https').click();
break;
}
}
});
$(function () {
if ($('.user.signin').length > 0) return;
$('form').areYouSure();
});