Merge branch 'develop' into feature

This commit is contained in:
jeremystretch
2022-02-10 15:05:54 -05:00
25 changed files with 197 additions and 78 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -8,11 +8,12 @@ import { DynamicParamsMap } from './dynamicParams';
import { isStaticParams, isOption } from './types';
import {
hasMore,
isTruthy,
hasError,
getElement,
isTruthy,
getApiData,
getElement,
isApiError,
replaceAll,
createElement,
uniqueByProperty,
findFirstAdjacent,
@@ -461,7 +462,7 @@ export class APISelect {
// Set any primitive k/v pairs as data attributes on each option.
for (const [k, v] of Object.entries(result)) {
if (!['id', 'slug'].includes(k) && ['string', 'number', 'boolean'].includes(typeof v)) {
const key = k.replaceAll('_', '-');
const key = replaceAll(k, '_', '-');
data[key] = String(v);
}
// Set option to disabled if the result contains a matching key and is truthy.
@@ -659,7 +660,7 @@ export class APISelect {
for (const [key, value] of this.pathValues.entries()) {
for (const result of this.url.matchAll(new RegExp(`({{${key}}})`, 'g'))) {
if (isTruthy(value)) {
url = url.replaceAll(result[1], value.toString());
url = replaceAll(url, result[1], value.toString());
}
}
}
@@ -741,7 +742,7 @@ export class APISelect {
* @param id DOM ID of the other element.
*/
private updatePathValues(id: string): void {
const key = id.replaceAll(/^id_/gi, '');
const key = replaceAll(id, /^id_/i, '');
const element = getElement<HTMLSelectElement>(`id_${key}`);
if (element !== null) {
// If this element's URL contains Django template tags ({{), replace the template tag
@@ -919,16 +920,18 @@ export class APISelect {
style.setAttribute('data-netbox', id);
// Scope the CSS to apply both the list item and the selected item.
style.innerHTML = `
style.innerHTML = replaceAll(
`
div.ss-values div.ss-value[data-id="${id}"],
div.ss-list div.ss-option:not(.ss-disabled)[data-id="${id}"]
{
background-color: ${bg} !important;
color: ${fg} !important;
}
`
.replaceAll('\n', '')
.trim();
`,
'\n',
'',
).trim();
// Add the style element to the DOM.
document.head.appendChild(style);

View File

@@ -11,15 +11,6 @@ function saveTableConfig(): void {
}
}
/**
* Delete all selected columns, which reverts the user's preferences to the default column set.
*/
function resetTableConfig(): void {
for (const element of getElements<HTMLSelectElement>('select[name="columns"]')) {
element.value = '';
}
}
/**
* Add columns to the table config select element.
*/
@@ -53,7 +44,10 @@ function removeColumns(event: Event): void {
/**
* Submit form configuration to the NetBox API.
*/
async function submitFormConfig(url: string, formConfig: Dict<Dict>): Promise<APIResponse<APIUserConfig>> {
async function submitFormConfig(
url: string,
formConfig: Dict<Dict>,
): Promise<APIResponse<APIUserConfig>> {
return await apiPatch<APIUserConfig>(url, formConfig);
}
@@ -70,25 +64,46 @@ function handleSubmit(event: Event): void {
const url = element.getAttribute('data-url');
if (url == null) {
const toast = createToast(
'danger',
'Error Updating Table Configuration',
'No API path defined for configuration form.'
'danger',
'Error Updating Table Configuration',
'No API path defined for configuration form.',
);
toast.show();
return;
}
// Determine if the form action is to reset the table config.
const reset = document.activeElement?.getAttribute('value') === 'Reset';
// Create an array from the dot-separated config path. E.g. tables.DevicePowerOutletTable becomes
// ['tables', 'DevicePowerOutletTable']
const path = element.getAttribute('data-config-root')?.split('.') ?? [];
if (reset) {
// If we're resetting the table config, create an empty object for this table. E.g.
// tables.PlatformTable becomes {tables: PlatformTable: {}}
const data = path.reduceRight<Dict<Dict>>((value, key) => ({ [key]: value }), {});
// Submit the reset for configuration to the API.
submitFormConfig(url, data).then(res => {
if (hasError(res)) {
const toast = createToast('danger', 'Error Resetting Table Configuration', res.error);
toast.show();
} else {
location.reload();
}
});
return;
}
// Get all the selected options from any select element in the form.
const options = getSelectedOptions(element);
const options = getSelectedOptions(element, 'select[name=columns]');
// Create an object mapping the select element's name to all selected options for that element.
const formData: Dict<Dict<string>> = Object.assign(
{},
...options.map(opt => ({ [opt.name]: opt.options })),
);
// Create an array from the dot-separated config path. E.g. tables.DevicePowerOutletTable becomes
// ['tables', 'DevicePowerOutletTable']
const path = element.getAttribute('data-config-root')?.split('.') ?? [];
// Create an object mapping the configuration path to the select element names, which contain the
// selection options. E.g. {tables: {DevicePowerOutletTable: {columns: ['label', 'type']}}}
@@ -112,9 +127,6 @@ export function initTableConfig(): void {
for (const element of getElements<HTMLButtonElement>('#save_tableconfig')) {
element.addEventListener('click', saveTableConfig);
}
for (const element of getElements<HTMLButtonElement>('#reset_tableconfig')) {
element.addEventListener('click', resetTableConfig);
}
for (const element of getElements<HTMLButtonElement>('#add_columns')) {
element.addEventListener('click', addColumns);
}

View File

@@ -1,4 +1,4 @@
import { getElements, findFirstAdjacent } from '../util';
import { getElements, replaceAll, findFirstAdjacent } from '../util';
type InterfaceState = 'enabled' | 'disabled';
type ShowHide = 'show' | 'hide';
@@ -105,9 +105,9 @@ class ButtonState {
*/
private toggleButton(): void {
if (this.buttonState === 'show') {
this.button.innerText = this.button.innerText.replaceAll('Show', 'Hide');
this.button.innerText = replaceAll(this.button.innerText, 'Show', 'Hide');
} else if (this.buttonState === 'hide') {
this.button.innerText = this.button.innerText.replaceAll('Hide', 'Show');
this.button.innerText = replaceAll(this.button.innerHTML, 'Hide', 'Show');
}
}

View File

@@ -231,11 +231,15 @@ export function scrollTo(element: Element, offset: number = 0): void {
* Iterate through a select element's options and return an array of options that are selected.
*
* @param base Select element.
* @param selector Optionally specify a selector. 'select' by default.
* @returns Array of selected options.
*/
export function getSelectedOptions<E extends HTMLElement>(base: E): SelectedOption[] {
export function getSelectedOptions<E extends HTMLElement>(
base: E,
selector: string = 'select',
): SelectedOption[] {
let selected = [] as SelectedOption[];
for (const element of base.querySelectorAll<HTMLSelectElement>('select')) {
for (const element of base.querySelectorAll<HTMLSelectElement>(selector)) {
if (element !== null) {
const select = { name: element.name, options: [] } as SelectedOption;
for (const option of element.options) {
@@ -315,7 +319,7 @@ export function* getRowValues(table: HTMLTableRowElement): Generator<string> {
for (const element of table.querySelectorAll<HTMLTableCellElement>('td')) {
if (element !== null) {
if (isTruthy(element.innerText) && element.innerText !== '—') {
yield element.innerText.replaceAll(/[\n\r]/g, '').trim();
yield replaceAll(element.innerText, '[\n\r]', '').trim();
}
}
}
@@ -436,3 +440,49 @@ export function uniqueByProperty<T extends unknown, P extends keyof T>(arr: T[],
}
return Array.from(baseMap.values());
}
/**
* Replace all occurrences of a pattern with a replacement string.
*
* This is a browser-compatibility-focused drop-in replacement for `String.prototype.replaceAll()`,
* introduced in ES2021.
*
* @param input string to be processed.
* @param pattern regex pattern string or RegExp object to search for.
* @param replacement replacement substring with which `pattern` matches will be replaced.
* @returns processed version of `input`.
*/
export function replaceAll(input: string, pattern: string | RegExp, replacement: string): string {
// Ensure input is a string.
if (typeof input !== 'string') {
throw new TypeError("replaceAll 'input' argument must be a string");
}
// Ensure pattern is a string or RegExp.
if (typeof pattern !== 'string' && !(pattern instanceof RegExp)) {
throw new TypeError("replaceAll 'pattern' argument must be a string or RegExp instance");
}
// Ensure replacement is able to be stringified.
switch (typeof replacement) {
case 'boolean':
replacement = String(replacement);
break;
case 'number':
replacement = String(replacement);
break;
case 'string':
break;
default:
throw new TypeError("replaceAll 'replacement' argument must be stringifyable");
}
if (pattern instanceof RegExp) {
// Add global flag to existing RegExp object and deduplicate
const flags = Array.from(new Set([...pattern.flags.split(''), 'g'])).join('');
pattern = new RegExp(pattern.source, flags);
} else {
// Create a RegExp object with the global flag set.
pattern = new RegExp(pattern, 'g');
}
return input.replace(pattern, replacement);
}