Commit 23993e8c authored by Thomas Randolph's avatar Thomas Randolph

Extract and refactor dropdown item rendering

Basic Intent: Allow all branch names without accidentally creating
layout or backstage DOM. e.g. a branch named `separator` should never
create a separator `li` element.  

Ideally, there should never be a string that could cause this kind of 
conflict.  

Implementation: All of `GitLabDropdown.renderItem` is extracted to a 
standalone module.  

To render a divider or separator, consumers must now pass in an object 
like `{ "type": "divider" }` or `{ "type": "separator" }`   

Notable choices:  
- All of the functions have a cyclomatic complexity of 3 or less
    - See: https://en.wikipedia.org/wiki/Cyclomatic_complexity
    - Note the "Correlation to number of defects" section
    - While software complexity may not have a directly causal
      relationship with defects, less complex software is generally
      easier to reason about, and **may** reduce defects.
      I personally try to maintain complexity of no higher than 3.
- Everything other than the branch names fix matches past behavior 
exactly
    - Including:
        - Unused variables
        - Class list order
parent 96313e86
......@@ -7,6 +7,7 @@ import fuzzaldrinPlus from 'fuzzaldrin-plus';
import axios from './lib/utils/axios_utils';
import { visitUrl } from './lib/utils/url_utility';
import { isObject } from './lib/utils/type_utility';
import renderItem from './gl_dropdown/render';
var GitLabDropdown, GitLabDropdownFilter, GitLabDropdownRemote, GitLabDropdownInput;
......@@ -521,8 +522,8 @@ GitLabDropdown = (function() {
html.push(
this.renderItem(
{
header: name,
// Add header for each group
content: name,
type: 'header',
},
name,
),
......@@ -542,16 +543,7 @@ GitLabDropdown = (function() {
};
GitLabDropdown.prototype.renderData = function(data, group) {
if (group == null) {
group = false;
}
return data.map(
(function(_this) {
return function(obj, index) {
return _this.renderItem(obj, group, index);
};
})(this),
);
return data.map((obj, index) => this.renderItem(obj, group || false, index));
};
GitLabDropdown.prototype.shouldPropagate = function(e) {
......@@ -688,104 +680,25 @@ GitLabDropdown = (function() {
};
GitLabDropdown.prototype.renderItem = function(data, group, index) {
var field, html, selected, text, url, value, rowHidden;
if (!this.options.renderRow) {
value = this.options.id ? this.options.id(data) : data.id;
if (value) {
value = value.toString().replace(/'/g, "\\'");
}
}
// Hide element
if (this.options.hideRow && this.options.hideRow(value)) {
rowHidden = true;
}
if (group == null) {
group = false;
}
if (index == null) {
// Render the row
index = false;
}
html = document.createElement('li');
if (rowHidden) {
html.style.display = 'none';
}
if (data === 'divider' || data === 'separator') {
html.className = data;
return html;
}
// Header
if (data.header != null) {
html.className = 'dropdown-header';
html.innerHTML = data.header;
return html;
}
if (this.options.renderRow) {
// Call the render function
html = this.options.renderRow.call(this.options, data, this);
} else {
if (!selected) {
const { fieldName } = this.options;
if (value) {
field = this.dropdown.parent().find(`input[name='${fieldName}'][value='${value}']`);
if (field.length) {
selected = true;
}
} else {
field = this.dropdown.parent().find(`input[name='${fieldName}']`);
selected = !field.length;
}
}
// Set URL
if (this.options.url != null) {
url = this.options.url(data);
} else {
url = data.url != null ? data.url : '#';
}
// Set Text
if (this.options.text != null) {
text = this.options.text(data);
} else {
text = data.text != null ? data.text : '';
}
if (this.highlight) {
text = data.template
? this.highlightTemplate(text, data.template)
: this.highlightTextMatches(text, this.filterInput.val());
}
// Create the list item & the link
var link = document.createElement('a');
link.href = url;
if (this.icon) {
text = `<span>${text}</span>`;
link.classList.add('d-flex', 'align-items-center');
link.innerHTML = data.icon ? data.icon + text : text;
} else if (this.highlight) {
link.innerHTML = text;
} else {
link.textContent = text;
}
if (selected) {
link.classList.add('is-active');
}
if (group) {
link.dataset.group = group;
link.dataset.index = index;
}
html.appendChild(link);
}
return html;
let parent;
if (this.dropdown && this.dropdown[0]) {
parent = this.dropdown[0].parentNode;
}
return renderItem({
instance: this,
options: Object.assign({}, this.options, {
icon: this.icon,
highlight: this.highlight,
highlightText: text => this.highlightTextMatches(text, this.filterInput.val()),
highlightTemplate: this.highlightTemplate.bind(this),
parent,
}),
data,
group,
index,
});
};
GitLabDropdown.prototype.highlightTemplate = function(text, template) {
......@@ -809,7 +722,6 @@ GitLabDropdown = (function() {
};
GitLabDropdown.prototype.noResults = function() {
var html;
return '<li class="dropdown-menu-empty-item"><a>No matching results</a></li>';
};
......
const renderersByType = {
divider(element) {
element.classList.add('divider');
return element;
},
separator(element) {
element.classList.add('separator');
return element;
},
header(element, data) {
element.classList.add('dropdown-header');
element.innerHTML = data.content;
return element;
},
};
function getPropertyWithDefault(data, options, property, defaultValue = '') {
let result;
if (options[property] != null) {
result = options[property](data);
} else {
result = data[property] != null ? data[property] : defaultValue;
}
return result;
}
function getHighlightTextBuilder(text, data, options) {
if (options.highlight) {
return data.template
? options.highlightTemplate(text, data.template)
: options.highlightText(text);
}
return text;
}
function getIconTextBuilder(text, data, options) {
if (options.icon) {
const wrappedText = `<span>${text}</span>`;
return data.icon ? `${data.icon}${wrappedText}` : wrappedText;
}
return text;
}
function getLinkText(data, options) {
const text = getPropertyWithDefault(data, options, 'text');
return [getHighlightTextBuilder, getIconTextBuilder].reduce(
(acc, fn) => fn(acc, data, options),
text,
);
}
function escape(text) {
return text ? String(text).replace(/'/g, "\\'") : text;
}
function getOptionValue(data, options) {
if (options.renderRow) {
return undefined;
}
return escape(options.id ? options.id(data) : data.id);
}
function shouldHide(data, { options }) {
const value = getOptionValue(data, options);
return options.hideRow && options.hideRow(value);
}
function hideElement(element) {
element.style.display = 'none';
return element;
}
function checkSelected(data, options) {
const value = getOptionValue(data, options);
if (!options.parent) {
return !data.id;
} else if (value) {
return (
options.parent.querySelector(`input[name='${options.fieldName}'][value='${value}']`) != null
);
}
return options.parent.querySelector(`input[name='${options.fieldName}']`) == null;
}
function createLink(url, selected, options) {
const link = document.createElement('a');
link.href = url;
if (options.icon) {
link.classList.add('d-flex', 'align-items-center');
}
link.classList.toggle('is-active', selected);
return link;
}
function assignTextToLink(el, data, options) {
const text = getLinkText(data, options);
if (options.icon || options.highlight) {
el.innerHTML = text;
} else {
el.textContent = text;
}
return el;
}
function renderLink(row, data, { options, group, index }) {
const selected = checkSelected(data, options);
const url = getPropertyWithDefault(data, options, 'url', '#');
const link = createLink(url, selected, options);
assignTextToLink(link, data, options);
if (group) {
link.dataset.group = group;
link.dataset.index = index;
}
row.appendChild(link);
return row;
}
function getOptionRenderer({ options, instance }) {
return options.renderRow && ((li, data) => options.renderRow(data, instance));
}
function getRenderer(data, params) {
return renderersByType[data.type] || getOptionRenderer(params) || renderLink;
}
export default function item({ data, ...params }) {
const renderer = getRenderer(data, params);
const li = document.createElement('li');
if (shouldHide(data, params)) {
hideElement(li);
}
return renderer(li, data, params);
}
......@@ -369,7 +369,7 @@ export default class AccessDropdown {
});
if (roles.length) {
consolidatedData = consolidatedData.concat([{ header: s__('AccessDropdown|Roles') }], roles);
consolidatedData = consolidatedData.concat([{ type: 'header', content: s__('AccessDropdown|Roles') }], roles);
}
if (groups.length) {
......@@ -378,15 +378,15 @@ export default class AccessDropdown {
}
consolidatedData = consolidatedData.concat(
[{ header: s__('AccessDropdown|Groups') }],
[{ type: 'header', content: s__('AccessDropdown|Groups') }],
groups,
);
}
if (users.length) {
consolidatedData = consolidatedData.concat(
['divider'],
[{ header: s__('AccessDropdown|Users') }],
[{ type: 'divider' }],
[{ type: 'header', content: s__('AccessDropdown|Users') }],
users,
);
}
......
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