Commit b8b6de4c authored by Eric Eastwood's avatar Eric Eastwood Committed by Clement Ho

Make `gfm_auto_complete` into a module and fix up tech debt

parent dc045dab
...@@ -53,6 +53,7 @@ import BlobViewer from './blob/viewer/index'; ...@@ -53,6 +53,7 @@ import BlobViewer from './blob/viewer/index';
import AutoWidthDropdownSelect from './issuable/auto_width_dropdown_select'; import AutoWidthDropdownSelect from './issuable/auto_width_dropdown_select';
import UsersSelect from './users_select'; import UsersSelect from './users_select';
import RefSelectDropdown from './ref_select_dropdown'; import RefSelectDropdown from './ref_select_dropdown';
import GfmAutoComplete from './gfm_auto_complete';
const ShortcutsBlob = require('./shortcuts_blob'); const ShortcutsBlob = require('./shortcuts_blob');
...@@ -79,6 +80,8 @@ const ShortcutsBlob = require('./shortcuts_blob'); ...@@ -79,6 +80,8 @@ const ShortcutsBlob = require('./shortcuts_blob');
path = page.split(':'); path = page.split(':');
shortcut_handler = null; shortcut_handler = null;
new GfmAutoComplete(gl.GfmAutoComplete && gl.GfmAutoComplete.dataSources).setup();
function initBlob() { function initBlob() {
new LineHighlighter(); new LineHighlighter();
......
/* eslint-disable func-names, space-before-function-paren, no-template-curly-in-string, comma-dangle, object-shorthand, quotes, dot-notation, no-else-return, one-var, no-var, no-underscore-dangle, one-var-declaration-per-line, no-param-reassign, no-useless-escape, prefer-template, consistent-return, wrap-iife, prefer-arrow-callback, camelcase, no-unused-vars, no-useless-return, vars-on-top, max-len */
import emojiMap from 'emojis/digests.json'; import emojiMap from 'emojis/digests.json';
import emojiAliases from 'emojis/aliases.json'; import emojiAliases from 'emojis/aliases.json';
import { glEmojiTag } from '~/behaviors/gl_emoji'; import { glEmojiTag } from '~/behaviors/gl_emoji';
import glRegexp from '~/lib/utils/regexp'; import glRegexp from '~/lib/utils/regexp';
// Creates the variables for setting up GFM auto-completion
window.gl = window.gl || {};
function sanitize(str) { function sanitize(str) {
return str.replace(/<(?:.|\n)*?>/gm, ''); return str.replace(/<(?:.|\n)*?>/gm, '');
} }
window.gl.GfmAutoComplete = { class GfmAutoComplete {
dataSources: {}, constructor(dataSources) {
defaultLoadingData: ['loading'], this.dataSources = dataSources || {};
cachedData: {}, this.cachedData = {};
isLoadingData: {}, this.isLoadingData = {};
atTypeMap: { }
':': 'emojis',
'@': 'members',
'#': 'issues',
'!': 'mergeRequests',
'~': 'labels',
'%': 'milestones',
'/': 'commands'
},
// Emoji
Emoji: {
templateFunction: function(name) {
return `<li>
${name} ${glEmojiTag(name)}
</li>
`;
}
},
// Team Members
Members: {
template: '<li>${avatarTag} ${username} <small>${title}</small></li>'
},
Labels: {
template: '<li><span class="dropdown-label-box" style="background: ${color}"></span> ${title}</li>'
},
// Issues and MergeRequests
Issues: {
template: '<li><small>${id}</small> ${title}</li>'
},
// Milestones
Milestones: {
template: '<li>${title}</li>'
},
Loading: {
template: '<li style="pointer-events: none;"><i class="fa fa-spinner fa-spin"></i> Loading...</li>'
},
DefaultOptions: {
sorter: function(query, items, searchKey) {
this.setting.highlightFirst = this.setting.alwaysHighlightFirst || query.length > 0;
if (gl.GfmAutoComplete.isLoading(items)) {
this.setting.highlightFirst = false;
return items;
}
return $.fn.atwho["default"].callbacks.sorter(query, items, searchKey);
},
filter: function(query, data, searchKey) {
if (gl.GfmAutoComplete.isLoading(data)) {
gl.GfmAutoComplete.fetchData(this.$inputor, this.at);
return data;
} else {
return $.fn.atwho["default"].callbacks.filter(query, data, searchKey);
}
},
beforeInsert: function(value) {
if (value && !this.setting.skipSpecialCharacterTest) {
var withoutAt = value.substring(1);
if (withoutAt && /[^\w\d]/.test(withoutAt)) value = value.charAt() + '"' + withoutAt + '"';
}
return value;
},
matcher: function (flag, subtext) {
// The below is taken from At.js source
// Tweaked to commands to start without a space only if char before is a non-word character
// https://github.com/ichord/At.js
var _a, _y, regexp, match, atSymbolsWithBar, atSymbolsWithoutBar;
atSymbolsWithBar = Object.keys(this.app.controllers).join('|');
atSymbolsWithoutBar = Object.keys(this.app.controllers).join('');
subtext = subtext.split(/\s+/g).pop();
flag = flag.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
_a = decodeURI("%C3%80");
_y = decodeURI("%C3%BF");
regexp = new RegExp("^(?:\\B|[^a-zA-Z0-9_" + atSymbolsWithoutBar + "]|\\s)" + flag + "(?!" + atSymbolsWithBar + ")((?:[A-Za-z" + _a + "-" + _y + "0-9_\'\.\+\-]|[^\\x00-\\x7a])*)$", 'gi');
match = regexp.exec(subtext);
if (match) { setup(input, enableMap = {
return match[1];
} else {
return null;
}
}
},
setup: function(input, enableMap = {
emojis: true, emojis: true,
members: true, members: true,
issues: true, issues: true,
milestones: true, milestones: true,
mergeRequests: true, mergeRequests: true,
labels: true labels: true,
}) { }) {
// Add GFM auto-completion to all input fields, that accept GFM input. // Add GFM auto-completion to all input fields, that accept GFM input.
this.input = input || $('.js-gfm-input'); this.input = input || $('.js-gfm-input');
this.enableMap = enableMap; this.enableMap = enableMap;
this.setupLifecycle(); this.setupLifecycle();
}, }
setupLifecycle() { setupLifecycle() {
this.input.each((i, input) => { this.input.each((i, input) => {
const $input = $(input); const $input = $(input);
...@@ -122,9 +36,9 @@ window.gl.GfmAutoComplete = { ...@@ -122,9 +36,9 @@ window.gl.GfmAutoComplete = {
// Needed for slash commands with suffixes (ex: /label ~) // Needed for slash commands with suffixes (ex: /label ~)
$input.on('inserted-commands.atwho', $input.trigger.bind($input, 'keyup')); $input.on('inserted-commands.atwho', $input.trigger.bind($input, 'keyup'));
}); });
}, }
setupAtWho: function($input) { setupAtWho($input) {
if (this.enableMap.emojis) this.setupEmoji($input); if (this.enableMap.emojis) this.setupEmoji($input);
if (this.enableMap.members) this.setupMembers($input); if (this.enableMap.members) this.setupMembers($input);
if (this.enableMap.issues) this.setupIssues($input); if (this.enableMap.issues) this.setupIssues($input);
...@@ -138,10 +52,11 @@ window.gl.GfmAutoComplete = { ...@@ -138,10 +52,11 @@ window.gl.GfmAutoComplete = {
alias: 'commands', alias: 'commands',
searchKey: 'search', searchKey: 'search',
skipSpecialCharacterTest: true, skipSpecialCharacterTest: true,
data: this.defaultLoadingData, data: GfmAutoComplete.defaultLoadingData,
displayTpl: function(value) { displayTpl(value) {
if (this.isLoading(value)) return this.Loading.template; if (GfmAutoComplete.isLoading(value)) return GfmAutoComplete.Loading.template;
var tpl = '<li>/${name}'; // eslint-disable-next-line no-template-curly-in-string
let tpl = '<li>/${name}';
if (value.aliases.length > 0) { if (value.aliases.length > 0) {
tpl += ' <small>(or /<%- aliases.join(", /") %>)</small>'; tpl += ' <small>(or /<%- aliases.join(", /") %>)</small>';
} }
...@@ -153,105 +68,106 @@ window.gl.GfmAutoComplete = { ...@@ -153,105 +68,106 @@ window.gl.GfmAutoComplete = {
} }
tpl += '</li>'; tpl += '</li>';
return _.template(tpl)(value); return _.template(tpl)(value);
}.bind(this), },
insertTpl: function(value) { insertTpl(value) {
var tpl = "/${name} "; // eslint-disable-next-line no-template-curly-in-string
var reference_prefix = null; let tpl = '/${name} ';
let referencePrefix = null;
if (value.params.length > 0) { if (value.params.length > 0) {
reference_prefix = value.params[0][0]; referencePrefix = value.params[0][0];
if (/^[@%~]/.test(reference_prefix)) { if (/^[@%~]/.test(referencePrefix)) {
tpl += '<%- reference_prefix %>'; tpl += '<%- referencePrefix %>';
} }
} }
return _.template(tpl)({ reference_prefix: reference_prefix }); return _.template(tpl)({ referencePrefix });
}, },
suffix: '', suffix: '',
callbacks: { callbacks: {
sorter: this.DefaultOptions.sorter, ...this.getDefaultCallbacks(),
filter: this.DefaultOptions.filter, beforeSave(commands) {
beforeInsert: this.DefaultOptions.beforeInsert, if (GfmAutoComplete.isLoading(commands)) return commands;
beforeSave: function(commands) { return $.map(commands, (c) => {
if (gl.GfmAutoComplete.isLoading(commands)) return commands; let search = c.name;
return $.map(commands, function(c) {
var search = c.name;
if (c.aliases.length > 0) { if (c.aliases.length > 0) {
search = search + " " + c.aliases.join(" "); search = `${search} ${c.aliases.join(' ')}`;
} }
return { return {
name: c.name, name: c.name,
aliases: c.aliases, aliases: c.aliases,
params: c.params, params: c.params,
description: c.description, description: c.description,
search: search search,
}; };
}); });
}, },
matcher: function(flag, subtext, should_startWithSpace, acceptSpaceBar) { matcher(flag, subtext) {
var regexp = /(?:^|\n)\/([A-Za-z_]*)$/gi; const regexp = /(?:^|\n)\/([A-Za-z_]*)$/gi;
var match = regexp.exec(subtext); const match = regexp.exec(subtext);
if (match) { if (match) {
return match[1]; return match[1];
} else {
return null;
} }
} return null;
} },
},
}); });
return; }
},
setupEmoji($input) { setupEmoji($input) {
// Emoji // Emoji
$input.atwho({ $input.atwho({
at: ':', at: ':',
displayTpl: function(value) { displayTpl(value) {
return value && value.name ? this.Emoji.templateFunction(value.name) : this.Loading.template; let tmpl = GfmAutoComplete.Loading.template;
}.bind(this), if (value && value.name) {
tmpl = GfmAutoComplete.Emoji.templateFunction(value.name);
}
return tmpl;
},
// eslint-disable-next-line no-template-curly-in-string
insertTpl: ':${name}:', insertTpl: ':${name}:',
skipSpecialCharacterTest: true, skipSpecialCharacterTest: true,
data: this.defaultLoadingData, data: GfmAutoComplete.defaultLoadingData,
callbacks: { callbacks: {
sorter: this.DefaultOptions.sorter, ...this.getDefaultCallbacks(),
beforeInsert: this.DefaultOptions.beforeInsert, matcher(flag, subtext) {
filter: this.DefaultOptions.filter,
matcher: (flag, subtext) => {
const relevantText = subtext.trim().split(/\s/).pop(); const relevantText = subtext.trim().split(/\s/).pop();
const regexp = new RegExp(`(?:[^${glRegexp.unicodeLetters}0-9:]|\n|^):([^:]*)$`, 'gi'); const regexp = new RegExp(`(?:[^${glRegexp.unicodeLetters}0-9:]|\n|^):([^:]*)$`, 'gi');
const match = regexp.exec(relevantText); const match = regexp.exec(relevantText);
return match && match.length ? match[1] : null; return match && match.length ? match[1] : null;
} },
} },
}); });
}, }
setupMembers($input) { setupMembers($input) {
// Team Members // Team Members
$input.atwho({ $input.atwho({
at: '@', at: '@',
displayTpl: function(value) { displayTpl(value) {
return value.username != null ? this.Members.template : this.Loading.template; let tmpl = GfmAutoComplete.Loading.template;
}.bind(this), if (value.username != null) {
tmpl = GfmAutoComplete.Members.template;
}
return tmpl;
},
// eslint-disable-next-line no-template-curly-in-string
insertTpl: '${atwho-at}${username}', insertTpl: '${atwho-at}${username}',
searchKey: 'search', searchKey: 'search',
alwaysHighlightFirst: true, alwaysHighlightFirst: true,
skipSpecialCharacterTest: true, skipSpecialCharacterTest: true,
data: this.defaultLoadingData, data: GfmAutoComplete.defaultLoadingData,
callbacks: { callbacks: {
sorter: this.DefaultOptions.sorter, ...this.getDefaultCallbacks(),
filter: this.DefaultOptions.filter, beforeSave(members) {
beforeInsert: this.DefaultOptions.beforeInsert, return $.map(members, (m) => {
matcher: this.DefaultOptions.matcher,
beforeSave: function(members) {
return $.map(members, function(m) {
let title = ''; let title = '';
if (m.username == null) { if (m.username == null) {
return m; return m;
} }
title = m.name; title = m.name;
if (m.count) { if (m.count) {
title += " (" + m.count + ")"; title += ` (${m.count})`;
} }
const autoCompleteAvatar = m.avatar_url || m.username.charAt(0).toUpperCase(); const autoCompleteAvatar = m.avatar_url || m.username.charAt(0).toUpperCase();
...@@ -262,173 +178,271 @@ window.gl.GfmAutoComplete = { ...@@ -262,173 +178,271 @@ window.gl.GfmAutoComplete = {
username: m.username, username: m.username,
avatarTag: autoCompleteAvatar.length === 1 ? txtAvatar : imgAvatar, avatarTag: autoCompleteAvatar.length === 1 ? txtAvatar : imgAvatar,
title: sanitize(title), title: sanitize(title),
search: sanitize(m.username + " " + m.name) search: sanitize(`${m.username} ${m.name}`),
}; };
}); });
} },
} },
}); });
}, }
setupIssues($input) { setupIssues($input) {
$input.atwho({ $input.atwho({
at: '#', at: '#',
alias: 'issues', alias: 'issues',
searchKey: 'search', searchKey: 'search',
displayTpl: function(value) { displayTpl(value) {
return value.title != null ? this.Issues.template : this.Loading.template; let tmpl = GfmAutoComplete.Loading.template;
}.bind(this), if (value.title != null) {
data: this.defaultLoadingData, tmpl = GfmAutoComplete.Issues.template;
}
return tmpl;
},
data: GfmAutoComplete.defaultLoadingData,
// eslint-disable-next-line no-template-curly-in-string
insertTpl: '${atwho-at}${id}', insertTpl: '${atwho-at}${id}',
callbacks: { callbacks: {
sorter: this.DefaultOptions.sorter, ...this.getDefaultCallbacks(),
filter: this.DefaultOptions.filter, beforeSave(issues) {
beforeInsert: this.DefaultOptions.beforeInsert, return $.map(issues, (i) => {
matcher: this.DefaultOptions.matcher,
beforeSave: function(issues) {
return $.map(issues, function(i) {
if (i.title == null) { if (i.title == null) {
return i; return i;
} }
return { return {
id: i.iid, id: i.iid,
title: sanitize(i.title), title: sanitize(i.title),
search: i.iid + " " + i.title search: `${i.iid} ${i.title}`,
}; };
}); });
} },
} },
}); });
}, }
setupMilestones($input) { setupMilestones($input) {
$input.atwho({ $input.atwho({
at: '%', at: '%',
alias: 'milestones', alias: 'milestones',
searchKey: 'search', searchKey: 'search',
// eslint-disable-next-line no-template-curly-in-string
insertTpl: '${atwho-at}${title}', insertTpl: '${atwho-at}${title}',
displayTpl: function(value) { displayTpl(value) {
return value.title != null ? this.Milestones.template : this.Loading.template; let tmpl = GfmAutoComplete.Loading.template;
}.bind(this), if (value.title != null) {
data: this.defaultLoadingData, tmpl = GfmAutoComplete.Milestones.template;
}
return tmpl;
},
data: GfmAutoComplete.defaultLoadingData,
callbacks: { callbacks: {
matcher: this.DefaultOptions.matcher, ...this.getDefaultCallbacks(),
sorter: this.DefaultOptions.sorter, beforeSave(milestones) {
beforeInsert: this.DefaultOptions.beforeInsert, return $.map(milestones, (m) => {
filter: this.DefaultOptions.filter,
beforeSave: function(milestones) {
return $.map(milestones, function(m) {
if (m.title == null) { if (m.title == null) {
return m; return m;
} }
return { return {
id: m.iid, id: m.iid,
title: sanitize(m.title), title: sanitize(m.title),
search: "" + m.title search: m.title,
}; };
}); });
} },
} },
}); });
}, }
setupMergeRequests($input) { setupMergeRequests($input) {
$input.atwho({ $input.atwho({
at: '!', at: '!',
alias: 'mergerequests', alias: 'mergerequests',
searchKey: 'search', searchKey: 'search',
displayTpl: function(value) { displayTpl(value) {
return value.title != null ? this.Issues.template : this.Loading.template; let tmpl = GfmAutoComplete.Loading.template;
}.bind(this), if (value.title != null) {
data: this.defaultLoadingData, tmpl = GfmAutoComplete.Issues.template;
}
return tmpl;
},
data: GfmAutoComplete.defaultLoadingData,
// eslint-disable-next-line no-template-curly-in-string
insertTpl: '${atwho-at}${id}', insertTpl: '${atwho-at}${id}',
callbacks: { callbacks: {
sorter: this.DefaultOptions.sorter, ...this.getDefaultCallbacks(),
filter: this.DefaultOptions.filter, beforeSave(merges) {
beforeInsert: this.DefaultOptions.beforeInsert, return $.map(merges, (m) => {
matcher: this.DefaultOptions.matcher,
beforeSave: function(merges) {
return $.map(merges, function(m) {
if (m.title == null) { if (m.title == null) {
return m; return m;
} }
return { return {
id: m.iid, id: m.iid,
title: sanitize(m.title), title: sanitize(m.title),
search: m.iid + " " + m.title search: `${m.iid} ${m.title}`,
}; };
}); });
} },
} },
}); });
}, }
setupLabels($input) { setupLabels($input) {
$input.atwho({ $input.atwho({
at: '~', at: '~',
alias: 'labels', alias: 'labels',
searchKey: 'search', searchKey: 'search',
data: this.defaultLoadingData, data: GfmAutoComplete.defaultLoadingData,
displayTpl: function(value) { displayTpl(value) {
return this.isLoading(value) ? this.Loading.template : this.Labels.template; let tmpl = GfmAutoComplete.Labels.template;
}.bind(this), if (GfmAutoComplete.isLoading(value)) {
tmpl = GfmAutoComplete.Loading.template;
}
return tmpl;
},
// eslint-disable-next-line no-template-curly-in-string
insertTpl: '${atwho-at}${title}', insertTpl: '${atwho-at}${title}',
callbacks: { callbacks: {
matcher: this.DefaultOptions.matcher, ...this.getDefaultCallbacks(),
beforeInsert: this.DefaultOptions.beforeInsert, beforeSave(merges) {
filter: this.DefaultOptions.filter, if (GfmAutoComplete.isLoading(merges)) return merges;
sorter: this.DefaultOptions.sorter, return $.map(merges, m => ({
beforeSave: function(merges) { title: sanitize(m.title),
if (gl.GfmAutoComplete.isLoading(merges)) return merges; color: m.color,
var sanitizeLabelTitle; search: m.title,
sanitizeLabelTitle = function(title) { }));
if (/[\w\?&]+\s+[\w\?&]+/g.test(title)) { },
return "\"" + (sanitize(title)) + "\""; },
} else {
return sanitize(title);
}
};
return $.map(merges, function(m) {
return {
title: sanitize(m.title),
color: m.color,
search: "" + m.title
};
});
}
}
}); });
}, }
fetchData: function($input, at) { getDefaultCallbacks() {
const fetchData = this.fetchData.bind(this);
return {
sorter(query, items, searchKey) {
this.setting.highlightFirst = this.setting.alwaysHighlightFirst || query.length > 0;
if (GfmAutoComplete.isLoading(items)) {
this.setting.highlightFirst = false;
return items;
}
return $.fn.atwho.default.callbacks.sorter(query, items, searchKey);
},
filter(query, data, searchKey) {
if (GfmAutoComplete.isLoading(data)) {
fetchData(this.$inputor, this.at);
return data;
}
return $.fn.atwho.default.callbacks.filter(query, data, searchKey);
},
beforeInsert(value) {
let resultantValue = value;
if (value && !this.setting.skipSpecialCharacterTest) {
const withoutAt = value.substring(1);
if (withoutAt && /[^\w\d]/.test(withoutAt)) {
resultantValue = `${value.charAt()}"${withoutAt}"`;
}
}
return resultantValue;
},
matcher(flag, subtext) {
// The below is taken from At.js source
// Tweaked to commands to start without a space only if char before is a non-word character
// https://github.com/ichord/At.js
const atSymbolsWithBar = Object.keys(this.app.controllers).join('|');
const atSymbolsWithoutBar = Object.keys(this.app.controllers).join('');
const targetSubtext = subtext.split(/\s+/g).pop();
const resultantFlag = flag.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
const accentAChar = decodeURI('%C3%80');
const accentYChar = decodeURI('%C3%BF');
const regexp = new RegExp(`^(?:\\B|[^a-zA-Z0-9_${atSymbolsWithoutBar}]|\\s)${resultantFlag}(?!${atSymbolsWithBar})((?:[A-Za-z${accentAChar}-${accentYChar}0-9_'.+-]|[^\\x00-\\x7a])*)$`, 'gi');
const match = regexp.exec(targetSubtext);
if (match) {
return match[1];
}
return null;
},
};
}
fetchData($input, at) {
if (this.isLoadingData[at]) return; if (this.isLoadingData[at]) return;
this.isLoadingData[at] = true; this.isLoadingData[at] = true;
if (this.cachedData[at]) { if (this.cachedData[at]) {
this.loadData($input, at, this.cachedData[at]); this.loadData($input, at, this.cachedData[at]);
} else if (this.atTypeMap[at] === 'emojis') { } else if (GfmAutoComplete.atTypeMap[at] === 'emojis') {
this.loadData($input, at, Object.keys(emojiMap).concat(Object.keys(emojiAliases))); this.loadData($input, at, Object.keys(emojiMap).concat(Object.keys(emojiAliases)));
} else { } else {
$.getJSON(this.dataSources[this.atTypeMap[at]], (data) => { $.getJSON(this.dataSources[GfmAutoComplete.atTypeMap[at]], (data) => {
this.loadData($input, at, data); this.loadData($input, at, data);
}).fail(() => { this.isLoadingData[at] = false; }); }).fail(() => { this.isLoadingData[at] = false; });
} }
}, }
loadData: function($input, at, data) { loadData($input, at, data) {
this.isLoadingData[at] = false; this.isLoadingData[at] = false;
this.cachedData[at] = data; this.cachedData[at] = data;
$input.atwho('load', at, data); $input.atwho('load', at, data);
// This trigger at.js again // This trigger at.js again
// otherwise we would be stuck with loading until the user types // otherwise we would be stuck with loading until the user types
return $input.trigger('keyup'); return $input.trigger('keyup');
}, }
isLoading(data) {
var dataToInspect = data; static isLoading(data) {
let dataToInspect = data;
if (data && data.length > 0) { if (data && data.length > 0) {
dataToInspect = data[0]; dataToInspect = data[0];
} }
var loadingState = this.defaultLoadingData[0]; const loadingState = GfmAutoComplete.defaultLoadingData[0];
return dataToInspect && return dataToInspect &&
(dataToInspect === loadingState || dataToInspect.name === loadingState); (dataToInspect === loadingState || dataToInspect.name === loadingState);
} }
}
GfmAutoComplete.defaultLoadingData = ['loading'];
GfmAutoComplete.atTypeMap = {
':': 'emojis',
'@': 'members',
'#': 'issues',
'!': 'mergeRequests',
'~': 'labels',
'%': 'milestones',
'/': 'commands',
};
// Emoji
GfmAutoComplete.Emoji = {
templateFunction(name) {
return `<li>
${name} ${glEmojiTag(name)}
</li>
`;
},
}; };
// Team Members
GfmAutoComplete.Members = {
// eslint-disable-next-line no-template-curly-in-string
template: '<li>${avatarTag} ${username} <small>${title}</small></li>',
};
GfmAutoComplete.Labels = {
// eslint-disable-next-line no-template-curly-in-string
template: '<li><span class="dropdown-label-box" style="background: ${color}"></span> ${title}</li>',
};
// Issues and MergeRequests
GfmAutoComplete.Issues = {
// eslint-disable-next-line no-template-curly-in-string
template: '<li><small>${id}</small> ${title}</li>',
};
// Milestones
GfmAutoComplete.Milestones = {
// eslint-disable-next-line no-template-curly-in-string
template: '<li>${title}</li>',
};
GfmAutoComplete.Loading = {
template: '<li style="pointer-events: none;"><i class="fa fa-spinner fa-spin"></i> Loading...</li>',
};
export default GfmAutoComplete;
...@@ -3,6 +3,8 @@ ...@@ -3,6 +3,8 @@
/* global DropzoneInput */ /* global DropzoneInput */
/* global autosize */ /* global autosize */
import GfmAutoComplete from './gfm_auto_complete';
window.gl = window.gl || {}; window.gl = window.gl || {};
function GLForm(form) { function GLForm(form) {
...@@ -31,7 +33,7 @@ GLForm.prototype.setupForm = function() { ...@@ -31,7 +33,7 @@ GLForm.prototype.setupForm = function() {
// remove notify commit author checkbox for non-commit notes // remove notify commit author checkbox for non-commit notes
gl.utils.disableButtonIfEmptyField(this.form.find('.js-note-text'), this.form.find('.js-comment-button, .js-note-new-discussion')); gl.utils.disableButtonIfEmptyField(this.form.find('.js-note-text'), this.form.find('.js-comment-button, .js-note-new-discussion'));
gl.GfmAutoComplete.setup(this.form.find('.js-gfm-input')); new GfmAutoComplete(gl.GfmAutoComplete && gl.GfmAutoComplete.dataSources).setup(this.form.find('.js-gfm-input'));
new DropzoneInput(this.form); new DropzoneInput(this.form);
autosize(this.textarea); autosize(this.textarea);
} }
......
...@@ -6,6 +6,7 @@ ...@@ -6,6 +6,7 @@
/* global Pikaday */ /* global Pikaday */
import UsersSelect from './users_select'; import UsersSelect from './users_select';
import GfmAutoComplete from './gfm_auto_complete';
(function() { (function() {
this.IssuableForm = (function() { this.IssuableForm = (function() {
...@@ -20,7 +21,7 @@ import UsersSelect from './users_select'; ...@@ -20,7 +21,7 @@ import UsersSelect from './users_select';
this.renderWipExplanation = this.renderWipExplanation.bind(this); this.renderWipExplanation = this.renderWipExplanation.bind(this);
this.resetAutosave = this.resetAutosave.bind(this); this.resetAutosave = this.resetAutosave.bind(this);
this.handleSubmit = this.handleSubmit.bind(this); this.handleSubmit = this.handleSubmit.bind(this);
gl.GfmAutoComplete.setup(); new GfmAutoComplete(gl.GfmAutoComplete && gl.GfmAutoComplete.dataSources).setup();
new UsersSelect(); new UsersSelect();
new ZenMode(); new ZenMode();
this.titleField = this.form.find("input[name*='[title]']"); this.titleField = this.form.find("input[name*='[title]']");
......
...@@ -96,7 +96,6 @@ import './dropzone_input'; ...@@ -96,7 +96,6 @@ import './dropzone_input';
import './due_date_select'; import './due_date_select';
import './files_comment_button'; import './files_comment_button';
import './flash'; import './flash';
import './gfm_auto_complete';
import './gl_dropdown'; import './gl_dropdown';
import './gl_field_error'; import './gl_field_error';
import './gl_field_errors'; import './gl_field_errors';
......
...@@ -12,7 +12,6 @@ require('./autosave'); ...@@ -12,7 +12,6 @@ require('./autosave');
window.autosize = require('vendor/autosize'); window.autosize = require('vendor/autosize');
window.Dropzone = require('dropzone'); window.Dropzone = require('dropzone');
require('./dropzone_input'); require('./dropzone_input');
require('./gfm_auto_complete');
require('vendor/jquery.caret'); // required by jquery.atwho require('vendor/jquery.caret'); // required by jquery.atwho
require('vendor/jquery.atwho'); require('vendor/jquery.atwho');
require('./task_list'); require('./task_list');
......
...@@ -3,6 +3,7 @@ ...@@ -3,6 +3,7 @@
- if project - if project
:javascript :javascript
gl.GfmAutoComplete = gl.GfmAutoComplete || {};
gl.GfmAutoComplete.dataSources = { gl.GfmAutoComplete.dataSources = {
members: "#{members_namespace_project_autocomplete_sources_path(project.namespace, project, type: noteable_type, type_id: params[:id])}", members: "#{members_namespace_project_autocomplete_sources_path(project.namespace, project, type: noteable_type, type_id: params[:id])}",
issues: "#{issues_namespace_project_autocomplete_sources_path(project.namespace, project)}", issues: "#{issues_namespace_project_autocomplete_sources_path(project.namespace, project)}",
...@@ -11,5 +12,3 @@ ...@@ -11,5 +12,3 @@
milestones: "#{milestones_namespace_project_autocomplete_sources_path(project.namespace, project)}", milestones: "#{milestones_namespace_project_autocomplete_sources_path(project.namespace, project)}",
commands: "#{commands_namespace_project_autocomplete_sources_path(project.namespace, project, type: noteable_type, type_id: params[:id])}" commands: "#{commands_namespace_project_autocomplete_sources_path(project.namespace, project, type: noteable_type, type_id: params[:id])}"
}; };
gl.GfmAutoComplete.setup();
...@@ -2,8 +2,8 @@ ...@@ -2,8 +2,8 @@
%html{ lang: I18n.locale, class: "#{page_class}" } %html{ lang: I18n.locale, class: "#{page_class}" }
= render "layouts/head" = render "layouts/head"
%body{ class: @body_class, data: { page: body_data_page, project: "#{@project.path if @project}", group: "#{@group.path if @group}" } } %body{ class: @body_class, data: { page: body_data_page, project: "#{@project.path if @project}", group: "#{@group.path if @group}" } }
= render "layouts/init_auto_complete" if @gfm_form
= render "layouts/header/default", title: header_title = render "layouts/header/default", title: header_title
= render 'layouts/page', sidebar: sidebar, nav: nav = render 'layouts/page', sidebar: sidebar, nav: nav
= yield :scripts_body = yield :scripts_body
= render "layouts/init_auto_complete" if @gfm_form
...@@ -10,7 +10,7 @@ describe 'GFM autocomplete loading', feature: true, js: true do ...@@ -10,7 +10,7 @@ describe 'GFM autocomplete loading', feature: true, js: true do
end end
it 'does not load on project#show' do it 'does not load on project#show' do
expect(evaluate_script('gl.GfmAutoComplete.dataSources')).to eq({}) expect(evaluate_script('gl.GfmAutoComplete')).to eq(nil)
end end
it 'loads on new issue page' do it 'loads on new issue page' do
......
/* eslint no-param-reassign: "off" */ /* eslint no-param-reassign: "off" */
require('~/gfm_auto_complete'); import GfmAutoComplete from '~/gfm_auto_complete';
require('vendor/jquery.caret'); require('vendor/jquery.caret');
require('vendor/jquery.atwho'); require('vendor/jquery.atwho');
const global = window.gl || (window.gl = {});
const GfmAutoComplete = global.GfmAutoComplete;
describe('GfmAutoComplete', function () { describe('GfmAutoComplete', function () {
const gfmAutoCompleteCallbacks = GfmAutoComplete.prototype.getDefaultCallbacks.call({
fetchData: () => {},
});
describe('DefaultOptions.sorter', function () { describe('DefaultOptions.sorter', function () {
describe('assets loading', function () { describe('assets loading', function () {
beforeEach(function () { beforeEach(function () {
...@@ -16,7 +18,7 @@ describe('GfmAutoComplete', function () { ...@@ -16,7 +18,7 @@ describe('GfmAutoComplete', function () {
this.atwhoInstance = { setting: {} }; this.atwhoInstance = { setting: {} };
this.items = []; this.items = [];
this.sorterValue = GfmAutoComplete.DefaultOptions.sorter this.sorterValue = gfmAutoCompleteCallbacks.sorter
.call(this.atwhoInstance, '', this.items); .call(this.atwhoInstance, '', this.items);
}); });
...@@ -38,7 +40,7 @@ describe('GfmAutoComplete', function () { ...@@ -38,7 +40,7 @@ describe('GfmAutoComplete', function () {
it('should enable highlightFirst if alwaysHighlightFirst is set', function () { it('should enable highlightFirst if alwaysHighlightFirst is set', function () {
const atwhoInstance = { setting: { alwaysHighlightFirst: true } }; const atwhoInstance = { setting: { alwaysHighlightFirst: true } };
GfmAutoComplete.DefaultOptions.sorter.call(atwhoInstance); gfmAutoCompleteCallbacks.sorter.call(atwhoInstance);
expect(atwhoInstance.setting.highlightFirst).toBe(true); expect(atwhoInstance.setting.highlightFirst).toBe(true);
}); });
...@@ -46,7 +48,7 @@ describe('GfmAutoComplete', function () { ...@@ -46,7 +48,7 @@ describe('GfmAutoComplete', function () {
it('should enable highlightFirst if a query is present', function () { it('should enable highlightFirst if a query is present', function () {
const atwhoInstance = { setting: {} }; const atwhoInstance = { setting: {} };
GfmAutoComplete.DefaultOptions.sorter.call(atwhoInstance, 'query'); gfmAutoCompleteCallbacks.sorter.call(atwhoInstance, 'query');
expect(atwhoInstance.setting.highlightFirst).toBe(true); expect(atwhoInstance.setting.highlightFirst).toBe(true);
}); });
...@@ -58,7 +60,7 @@ describe('GfmAutoComplete', function () { ...@@ -58,7 +60,7 @@ describe('GfmAutoComplete', function () {
const items = []; const items = [];
const searchKey = 'searchKey'; const searchKey = 'searchKey';
GfmAutoComplete.DefaultOptions.sorter.call(atwhoInstance, query, items, searchKey); gfmAutoCompleteCallbacks.sorter.call(atwhoInstance, query, items, searchKey);
expect($.fn.atwho.default.callbacks.sorter).toHaveBeenCalledWith(query, items, searchKey); expect($.fn.atwho.default.callbacks.sorter).toHaveBeenCalledWith(query, items, searchKey);
}); });
...@@ -67,7 +69,7 @@ describe('GfmAutoComplete', function () { ...@@ -67,7 +69,7 @@ describe('GfmAutoComplete', function () {
describe('DefaultOptions.matcher', function () { describe('DefaultOptions.matcher', function () {
const defaultMatcher = (context, flag, subtext) => ( const defaultMatcher = (context, flag, subtext) => (
GfmAutoComplete.DefaultOptions.matcher.call(context, flag, subtext) gfmAutoCompleteCallbacks.matcher.call(context, flag, subtext)
); );
const flagsUseDefaultMatcher = ['@', '#', '!', '~', '%']; const flagsUseDefaultMatcher = ['@', '#', '!', '~', '%'];
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment