debian-mirror-gitlab/app/assets/javascripts/gfm_auto_complete.js

471 lines
14 KiB
JavaScript
Raw Normal View History

2017-09-10 17:25:29 +05:30
import _ from 'underscore';
import glRegexp from './lib/utils/regexp';
import AjaxCache from './lib/utils/ajax_cache';
2017-08-17 22:00:37 +05:30
function sanitize(str) {
return str.replace(/<(?:.|\n)*?>/gm, '');
}
2017-09-10 17:25:29 +05:30
class GfmAutoComplete {
constructor(dataSources) {
this.dataSources = dataSources || {};
this.cachedData = {};
this.isLoadingData = {};
}
2017-08-17 22:00:37 +05:30
2017-09-10 17:25:29 +05:30
setup(input, enableMap = {
2017-08-17 22:00:37 +05:30
emojis: true,
members: true,
issues: true,
milestones: true,
mergeRequests: true,
2017-09-10 17:25:29 +05:30
labels: true,
2017-08-17 22:00:37 +05:30
}) {
// Add GFM auto-completion to all input fields, that accept GFM input.
this.input = input || $('.js-gfm-input');
this.enableMap = enableMap;
this.setupLifecycle();
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
setupLifecycle() {
this.input.each((i, input) => {
const $input = $(input);
$input.off('focus.setupAtWho').on('focus.setupAtWho', this.setupAtWho.bind(this, $input));
2017-09-10 17:25:29 +05:30
$input.on('change.atwho', () => input.dispatchEvent(new Event('input')));
2017-08-17 22:00:37 +05:30
// This triggers at.js again
2017-09-10 17:25:29 +05:30
// Needed for quick actions with suffixes (ex: /label ~)
2017-08-17 22:00:37 +05:30
$input.on('inserted-commands.atwho', $input.trigger.bind($input, 'keyup'));
2017-09-10 17:25:29 +05:30
$input.on('clear-commands-cache.atwho', () => this.clearCache());
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
2017-09-10 17:25:29 +05:30
setupAtWho($input) {
2017-08-17 22:00:37 +05:30
if (this.enableMap.emojis) this.setupEmoji($input);
if (this.enableMap.members) this.setupMembers($input);
if (this.enableMap.issues) this.setupIssues($input);
if (this.enableMap.milestones) this.setupMilestones($input);
if (this.enableMap.mergeRequests) this.setupMergeRequests($input);
if (this.enableMap.labels) this.setupLabels($input);
2017-09-10 17:25:29 +05:30
// We don't instantiate the quick actions autocomplete for note and issue/MR edit forms
$input.filter('[data-supports-quick-actions="true"]').atwho({
2017-08-17 22:00:37 +05:30
at: '/',
alias: 'commands',
searchKey: 'search',
skipSpecialCharacterTest: true,
2017-09-10 17:25:29 +05:30
data: GfmAutoComplete.defaultLoadingData,
displayTpl(value) {
if (GfmAutoComplete.isLoading(value)) return GfmAutoComplete.Loading.template;
// eslint-disable-next-line no-template-curly-in-string
let tpl = '<li>/${name}';
2017-08-17 22:00:37 +05:30
if (value.aliases.length > 0) {
tpl += ' <small>(or /<%- aliases.join(", /") %>)</small>';
}
if (value.params.length > 0) {
tpl += ' <small><%- params.join(" ") %></small>';
}
if (value.description !== '') {
tpl += '<small class="description"><i><%- description %></i></small>';
}
tpl += '</li>';
return _.template(tpl)(value);
2017-09-10 17:25:29 +05:30
},
insertTpl(value) {
// eslint-disable-next-line no-template-curly-in-string
let tpl = '/${name} ';
let referencePrefix = null;
2017-08-17 22:00:37 +05:30
if (value.params.length > 0) {
2017-09-10 17:25:29 +05:30
referencePrefix = value.params[0][0];
if (/^[@%~]/.test(referencePrefix)) {
tpl += '<%- referencePrefix %>';
2017-08-17 22:00:37 +05:30
}
}
2017-09-10 17:25:29 +05:30
return _.template(tpl)({ referencePrefix });
2017-08-17 22:00:37 +05:30
},
suffix: '',
callbacks: {
2017-09-10 17:25:29 +05:30
...this.getDefaultCallbacks(),
beforeSave(commands) {
if (GfmAutoComplete.isLoading(commands)) return commands;
return $.map(commands, (c) => {
let search = c.name;
2017-08-17 22:00:37 +05:30
if (c.aliases.length > 0) {
2017-09-10 17:25:29 +05:30
search = `${search} ${c.aliases.join(' ')}`;
2017-08-17 22:00:37 +05:30
}
return {
name: c.name,
aliases: c.aliases,
params: c.params,
description: c.description,
2017-09-10 17:25:29 +05:30
search,
2017-08-17 22:00:37 +05:30
};
});
},
2017-09-10 17:25:29 +05:30
matcher(flag, subtext) {
const regexp = /(?:^|\n)\/([A-Za-z_]*)$/gi;
const match = regexp.exec(subtext);
2017-08-17 22:00:37 +05:30
if (match) {
return match[1];
}
2017-09-10 17:25:29 +05:30
return null;
},
},
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
setupEmoji($input) {
// Emoji
$input.atwho({
at: ':',
2017-09-10 17:25:29 +05:30
displayTpl(value) {
let tmpl = GfmAutoComplete.Loading.template;
if (value && value.name) {
tmpl = GfmAutoComplete.Emoji.templateFunction(value.name);
}
return tmpl;
},
// eslint-disable-next-line no-template-curly-in-string
2017-08-17 22:00:37 +05:30
insertTpl: ':${name}:',
skipSpecialCharacterTest: true,
2017-09-10 17:25:29 +05:30
data: GfmAutoComplete.defaultLoadingData,
2017-08-17 22:00:37 +05:30
callbacks: {
2017-09-10 17:25:29 +05:30
...this.getDefaultCallbacks(),
matcher(flag, subtext) {
2017-08-17 22:00:37 +05:30
const relevantText = subtext.trim().split(/\s/).pop();
const regexp = new RegExp(`(?:[^${glRegexp.unicodeLetters}0-9:]|\n|^):([^:]*)$`, 'gi');
const match = regexp.exec(relevantText);
return match && match.length ? match[1] : null;
2017-09-10 17:25:29 +05:30
},
},
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
setupMembers($input) {
// Team Members
$input.atwho({
at: '@',
2017-09-10 17:25:29 +05:30
displayTpl(value) {
let tmpl = GfmAutoComplete.Loading.template;
if (value.username != null) {
tmpl = GfmAutoComplete.Members.template;
}
return tmpl;
},
// eslint-disable-next-line no-template-curly-in-string
2017-08-17 22:00:37 +05:30
insertTpl: '${atwho-at}${username}',
searchKey: 'search',
alwaysHighlightFirst: true,
skipSpecialCharacterTest: true,
2017-09-10 17:25:29 +05:30
data: GfmAutoComplete.defaultLoadingData,
2017-08-17 22:00:37 +05:30
callbacks: {
2017-09-10 17:25:29 +05:30
...this.getDefaultCallbacks(),
beforeSave(members) {
return $.map(members, (m) => {
2017-08-17 22:00:37 +05:30
let title = '';
if (m.username == null) {
return m;
}
title = m.name;
if (m.count) {
2017-09-10 17:25:29 +05:30
title += ` (${m.count})`;
2017-08-17 22:00:37 +05:30
}
const autoCompleteAvatar = m.avatar_url || m.username.charAt(0).toUpperCase();
const imgAvatar = `<img src="${m.avatar_url}" alt="${m.username}" class="avatar avatar-inline center s26"/>`;
const txtAvatar = `<div class="avatar center avatar-inline s26">${autoCompleteAvatar}</div>`;
return {
username: m.username,
avatarTag: autoCompleteAvatar.length === 1 ? txtAvatar : imgAvatar,
title: sanitize(title),
2017-09-10 17:25:29 +05:30
search: sanitize(`${m.username} ${m.name}`),
2017-08-17 22:00:37 +05:30
};
});
2017-09-10 17:25:29 +05:30
},
},
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
setupIssues($input) {
$input.atwho({
at: '#',
alias: 'issues',
searchKey: 'search',
2017-09-10 17:25:29 +05:30
displayTpl(value) {
let tmpl = GfmAutoComplete.Loading.template;
if (value.title != null) {
tmpl = GfmAutoComplete.Issues.template;
}
return tmpl;
},
data: GfmAutoComplete.defaultLoadingData,
// eslint-disable-next-line no-template-curly-in-string
2017-08-17 22:00:37 +05:30
insertTpl: '${atwho-at}${id}',
callbacks: {
2017-09-10 17:25:29 +05:30
...this.getDefaultCallbacks(),
beforeSave(issues) {
return $.map(issues, (i) => {
2017-08-17 22:00:37 +05:30
if (i.title == null) {
return i;
}
return {
id: i.iid,
title: sanitize(i.title),
2017-09-10 17:25:29 +05:30
search: `${i.iid} ${i.title}`,
2017-08-17 22:00:37 +05:30
};
});
2017-09-10 17:25:29 +05:30
},
},
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
setupMilestones($input) {
$input.atwho({
at: '%',
alias: 'milestones',
searchKey: 'search',
2017-09-10 17:25:29 +05:30
// eslint-disable-next-line no-template-curly-in-string
2017-08-17 22:00:37 +05:30
insertTpl: '${atwho-at}${title}',
2017-09-10 17:25:29 +05:30
displayTpl(value) {
let tmpl = GfmAutoComplete.Loading.template;
if (value.title != null) {
tmpl = GfmAutoComplete.Milestones.template;
}
return tmpl;
},
data: GfmAutoComplete.defaultLoadingData,
2017-08-17 22:00:37 +05:30
callbacks: {
2017-09-10 17:25:29 +05:30
...this.getDefaultCallbacks(),
beforeSave(milestones) {
return $.map(milestones, (m) => {
2017-08-17 22:00:37 +05:30
if (m.title == null) {
return m;
}
return {
id: m.iid,
title: sanitize(m.title),
2017-09-10 17:25:29 +05:30
search: m.title,
2017-08-17 22:00:37 +05:30
};
});
2017-09-10 17:25:29 +05:30
},
},
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
setupMergeRequests($input) {
$input.atwho({
at: '!',
alias: 'mergerequests',
searchKey: 'search',
2017-09-10 17:25:29 +05:30
displayTpl(value) {
let tmpl = GfmAutoComplete.Loading.template;
if (value.title != null) {
tmpl = GfmAutoComplete.Issues.template;
}
return tmpl;
},
data: GfmAutoComplete.defaultLoadingData,
// eslint-disable-next-line no-template-curly-in-string
2017-08-17 22:00:37 +05:30
insertTpl: '${atwho-at}${id}',
callbacks: {
2017-09-10 17:25:29 +05:30
...this.getDefaultCallbacks(),
beforeSave(merges) {
return $.map(merges, (m) => {
2017-08-17 22:00:37 +05:30
if (m.title == null) {
return m;
}
return {
id: m.iid,
title: sanitize(m.title),
2017-09-10 17:25:29 +05:30
search: `${m.iid} ${m.title}`,
2017-08-17 22:00:37 +05:30
};
});
2017-09-10 17:25:29 +05:30
},
},
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
2017-08-17 22:00:37 +05:30
setupLabels($input) {
$input.atwho({
at: '~',
alias: 'labels',
searchKey: 'search',
2017-09-10 17:25:29 +05:30
data: GfmAutoComplete.defaultLoadingData,
displayTpl(value) {
let tmpl = GfmAutoComplete.Labels.template;
if (GfmAutoComplete.isLoading(value)) {
tmpl = GfmAutoComplete.Loading.template;
}
return tmpl;
},
// eslint-disable-next-line no-template-curly-in-string
2017-08-17 22:00:37 +05:30
insertTpl: '${atwho-at}${title}',
callbacks: {
2017-09-10 17:25:29 +05:30
...this.getDefaultCallbacks(),
beforeSave(merges) {
if (GfmAutoComplete.isLoading(merges)) return merges;
return $.map(merges, m => ({
title: sanitize(m.title),
color: m.color,
search: m.title,
}));
},
},
2017-08-17 22:00:37 +05:30
});
2017-09-10 17:25:29 +05:30
}
getDefaultCallbacks() {
const fetchData = this.fetchData.bind(this);
2017-08-17 22:00:37 +05:30
2017-09-10 17:25:29 +05:30
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) {
2017-08-17 22:00:37 +05:30
if (this.isLoadingData[at]) return;
this.isLoadingData[at] = true;
if (this.cachedData[at]) {
this.loadData($input, at, this.cachedData[at]);
2017-09-10 17:25:29 +05:30
} else if (GfmAutoComplete.atTypeMap[at] === 'emojis') {
import(/* webpackChunkName: 'emoji' */ './emoji')
.then(({ validEmojiNames, glEmojiTag }) => {
this.loadData($input, at, validEmojiNames);
GfmAutoComplete.glEmojiTag = glEmojiTag;
})
.catch(() => { this.isLoadingData[at] = false; });
2017-08-17 22:00:37 +05:30
} else {
2017-09-10 17:25:29 +05:30
AjaxCache.retrieve(this.dataSources[GfmAutoComplete.atTypeMap[at]], true)
.then((data) => {
this.loadData($input, at, data);
})
.catch(() => { this.isLoadingData[at] = false; });
2017-08-17 22:00:37 +05:30
}
2017-09-10 17:25:29 +05:30
}
loadData($input, at, data) {
2017-08-17 22:00:37 +05:30
this.isLoadingData[at] = false;
this.cachedData[at] = data;
$input.atwho('load', at, data);
// This trigger at.js again
// otherwise we would be stuck with loading until the user types
return $input.trigger('keyup');
2017-09-10 17:25:29 +05:30
}
clearCache() {
this.cachedData = {};
}
destroy() {
this.input.each((i, input) => {
const $input = $(input);
$input.atwho('destroy');
});
}
static isLoading(data) {
let dataToInspect = data;
2017-08-17 22:00:37 +05:30
if (data && data.length > 0) {
dataToInspect = data[0];
}
2017-09-10 17:25:29 +05:30
const loadingState = GfmAutoComplete.defaultLoadingData[0];
2017-08-17 22:00:37 +05:30
return dataToInspect &&
(dataToInspect === loadingState || dataToInspect.name === loadingState);
}
2017-09-10 17:25:29 +05:30
}
GfmAutoComplete.defaultLoadingData = ['loading'];
GfmAutoComplete.atTypeMap = {
':': 'emojis',
'@': 'members',
'#': 'issues',
'!': 'mergeRequests',
'~': 'labels',
'%': 'milestones',
'/': 'commands',
};
// Emoji
GfmAutoComplete.glEmojiTag = null;
GfmAutoComplete.Emoji = {
templateFunction(name) {
// glEmojiTag helper is loaded on-demand in fetchData()
if (GfmAutoComplete.glEmojiTag) {
return `<li>${name} ${GfmAutoComplete.glEmojiTag(name)}</li>`;
}
return `<li>${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>',
2017-08-17 22:00:37 +05:30
};
2017-09-10 17:25:29 +05:30
// 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;