Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(custom_row): pass default row value to custom row component #1218

Merged
merged 13 commits into from
Jun 24, 2024
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions docs/custom_ui_extensions/custom_row.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,24 @@ When a row is expanded on the Inputs table, Custom Row is utilized to incorporat

### Properties

| Property | Description |
| ----------------- | ----------- |
| globalConfig | is a hierarchical object that contains the globalConfig file's properties and values. |
| el | is used to render a customized element on the Inputs table when a row is expanded. |
| serviceName | is the name of the service/tab specified in the globalConfig file. |
| row | it the object of the record for which the CustomRowInput constructor is called. |
| Property | Description |
| ------------ | ------------------------------------------------------------------------------------- |
| globalConfig | is a hierarchical object that contains the globalConfig file's properties and values. |
| el | is used to render a customized element on the Inputs table when a row is expanded. |
| serviceName | is the name of the service/tab specified in the globalConfig file. |
| row | is the object of the record for which the CustomRowInput constructor is called. |

### Methods

| Property | Description |
| ----------------- | ----------- |
| render | is a method which should have logic for the custom row component, and it will be executed automatically when the create, edit, or clone actions are performed. |
| Property | Description |
| --------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| render | is a method which should have logic for the custom row component, and it will be executed automatically when the create, edit, or clone actions are performed. |
| getDLRows | is a method which contains the logic to update the custom row values, return a key-value pair. |

> Note

> - Atleast one method should be present
> - If both method is present then the getDLRows method have the high priority.

### Usage

Expand Down Expand Up @@ -43,7 +49,8 @@ class CustomInputRow {
* @param {Object} globalConfig - Global configuration.
* @param {string} serviceName - Input service name.
* @param {element} el - The element of the custom cell.
* @param {Object} row - custom row object.
* @param {Object} row - custom row object,
* use this.row.<field_name>, where <field_name> is a field name
*/
constructor(globalConfig, serviceName, el, row) {
this.globalConfig = globalConfig;
Expand All @@ -52,17 +59,29 @@ class CustomInputRow {
this.row = row;
}

getDLRows() {
return Object.fromEntries(
Object.entries(this.row).map(([key, value]) => [
key,
key === "interval" ? `${value} sec` : value,
])
);
}

render() {
const content_html_template = 'Custom Input Row';
this.el.innerHTML = content_html_template;
return this;
}
}

export default CustomInputRow;
```

> Note: The Javascript file for the custom control should be saved in the custom folder at `appserver/static/js/build/custom/`.
> Note:

> - The content should be included in the JavaScript file named by customRow.src property in globalConfig (see usage for details).
> - The Javascript file for the custom control should be saved in the custom folder at `appserver/static/js/build/custom/`.

### Output

Expand Down
Binary file modified docs/images/custom_ui_extensions/Custom_Row_Output.png
vtsvetkov-splunk marked this conversation as resolved.
Show resolved Hide resolved
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -1376,6 +1376,10 @@
"field": "disabled"
}
],
"customRow": {
"src": "custom_input_row",
"type": "external"
},
"moreInfo": [
{
"label": "Name",
Expand Down Expand Up @@ -1550,9 +1554,9 @@
"meta": {
"name": "Splunk_TA_UCCExample",
"restRoot": "splunk_ta_uccexample",
"version": "5.44.0R7f88cfdd",
"version": "5.45.0R08c37572",
"displayName": "Splunk UCC test Add-on",
"schemaVersion": "0.0.7",
"_uccVersion": "5.44.0"
"_uccVersion": "5.45.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
class CustomInputRow {
/**
* Custom Row Cell
* @constructor
* @param {Object} globalConfig - Global configuration.
* @param {string} serviceName - Input service name.
* @param {element} el - The element of the custom cell.
* @param {Object} row - custom row object,
* use this.row.<field_name>, where <field_name> is a field name
*/
constructor(globalConfig, serviceName, el, row) {
this.globalConfig = globalConfig;
this.serviceName = serviceName;
this.el = el;
this.row = row;
}

getDLRows() {
return Object.fromEntries(
Object.entries(this.row).map(([key, value]) => [
key,
key === "interval" ? `${value} sec` : value,
])
);
}

render() {
rohanm-crest marked this conversation as resolved.
Show resolved Hide resolved
const content_html_template = "Custom Input Row";
this.el.innerHTML = content_html_template;
return this;
}
}

export default CustomInputRow;
8 changes: 7 additions & 1 deletion tests/ui/test_input_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -293,11 +293,12 @@ def test_inputs_more_info(
):
"""Verifies the expand functionality of the inputs table"""
input_page = InputPage(ucc_smartx_selenium_helper, ucc_smartx_rest_helper)
interval = "90"
self.assert_util(
input_page.table.get_more_info,
{
"Name": "dummy_input_one",
"Interval": "90",
"Interval": f"{interval} sec",
"Index": "default",
"Status": "Enabled",
"Example Account": "test_input",
Expand All @@ -309,6 +310,11 @@ def test_inputs_more_info(
},
left_args={"name": "dummy_input_one"},
)
backend_stanza = input_page.backend_conf.get_stanza(
"example_input_one://dummy_input_one"
)
# we verify that the conf value is `interval` and only the UI has changed
assert backend_stanza.get("interval") == interval

@pytest.mark.execute_enterprise_cloud_true
@pytest.mark.forwarder
Expand Down
167 changes: 133 additions & 34 deletions ui/src/components/table/CustomTableControl.jsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import DL from '@splunk/react-ui/DefinitionList';
import { _ } from '@splunk/ui-utils/i18n';

import ExclamationTriangle from '@splunk/react-icons/ExclamationTriangle';
import { getUnifiedConfigs } from '../../util/util';
import { getBuildDirPath } from '../../util/script';
import { getExpansionRowData } from './TableExpansionRowData';

function onCustomControlError(params) {
// eslint-disable-next-line no-console
Expand All @@ -17,23 +20,63 @@ class CustomTableControl extends Component {
super(props);
this.state = {
loading: true,
row: { ...props.row },
checkMethodIsPresent: false,
methodNotPresentError: '',
};
this.shouldRender = true;
}

componentDidMount() {
const globalConfig = getUnifiedConfigs();
this.setState({ loading: true });
this.loadCustomControl().then((Control) => {
this.customControl = new Control(
globalConfig,
this.props.serviceName,
this.el,
this.props.row,
this.props.field
this.loadCustomControl()
.then(async (Control) => {
if (typeof Control !== 'function') {
this.setState({
loading: false,
methodNotPresentError: 'Loaded module is not a constructor function',
});
return;
}
this.customControl = new Control(
globalConfig,
this.props.serviceName,
this.el,
this.state.row,
this.props.field
);

const result = await this.callCustomMethod('getDLRows');
try {
// check if getDLRow is exist in the custom input row file
if (result && typeof result === 'object' && !Array.isArray(result)) {
this.setState({
row: { ...result },
checkMethodIsPresent: true,
loading: false,
});
} else if (result !== null) {
// check if getDLRow return invalid object
this.setState({
loading: false,
checkMethodIsPresent: true,
methodNotPresentError: 'getDLRows method did not return a valid object',
});
} else {
// if getDLRow is not present then check render method is present or not
this.handleNoGetDLRows();
}
} catch (error) {
onCustomControlError({ methodName: 'getDLRows', error });
this.handleNoGetDLRows();
}
})
.catch(() =>
this.setState({
loading: false,
methodNotPresentError: 'Error loading custom control',
})
);
this.setState({ loading: false });
});
}

shouldComponentUpdate(nextProps, nextState) {
Expand All @@ -48,45 +91,100 @@ class CustomTableControl extends Component {
}

loadCustomControl = () =>
new Promise((resolve) => {
if (this.props.type === 'external') {
import(
/* webpackIgnore: true */ `${getBuildDirPath()}/custom/${
this.props.fileName
}.js`
).then((external) => {
const Control = external.default;
resolve(Control);
});
new Promise((resolve, reject) => {
const { type, fileName } = this.props;
const globalConfig = getUnifiedConfigs();

if (type === 'external') {
import(/* webpackIgnore: true */ `${getBuildDirPath()}/custom/${fileName}.js`)
.then((external) => resolve(external.default))
.catch((error) => reject(error));
} else {
const globalConfig = getUnifiedConfigs();
const appName = globalConfig.meta.name;
__non_webpack_require__(
[`app/${appName}/js/build/custom/${this.props.fileName}`],
(Control) => resolve(Control)
[`app/${appName}/js/build/custom/${fileName}`],
(Control) => resolve(Control),
(error) => reject(error)
);
}
});

/**
* Calls a method on the customControl instance, if it exists, with the provided arguments.
*
* @param {string} methodName - The name of the method to call on the customControl class instance.
* @param {...unknown} args - Any arguments that should be passed to the method.
* @returns {*} - The response from the custom control method, or null if the method does not exist or an error occurs.
*/
callCustomMethod = async (methodName, ...args) => {
soleksy-splunk marked this conversation as resolved.
Show resolved Hide resolved
try {
if (typeof this.customControl[methodName] === 'function') {
return this.customControl[methodName](...args);
soleksy-splunk marked this conversation as resolved.
Show resolved Hide resolved
}
return null;
} catch (error) {
onCustomControlError({ methodName, error });
return null;
}
};

handleNoGetDLRows = () => {
if (!this.customControl || typeof this.customControl.render !== 'function') {
this.setState((prevState) => ({
...prevState,
methodNotPresentError:
'At least "render" either "getDLRows" method should be present.',
}));
}
this.setState((prevState) => ({
...prevState,
loading: false,
}));
};

render() {
if (!this.state.loading) {
const { row, loading, checkMethodIsPresent, methodNotPresentError } = this.state;
const { moreInfo } = this.props;

if (
!loading &&
!checkMethodIsPresent &&
this.customControl &&
typeof this.customControl.render === 'function'
) {
try {
this.customControl.render(this.props.row, this.props.field);
this.customControl.render(row, moreInfo);
} catch (error) {
onCustomControlError({ methodName: 'render', error });
}
}

let content;

if (methodNotPresentError) {
content = (
<span style={{ display: 'flex', alignItems: 'center' }}>
<ExclamationTriangle style={{ color: 'red', marginRight: '4px' }} />
{methodNotPresentError}
</span>
);
} else if (checkMethodIsPresent) {
content = <DL termWidth={250}>{getExpansionRowData(row, moreInfo)}</DL>;
} else {
content = (
<span
ref={(el) => {
this.el = el;
}}
style={{ visibility: loading ? 'hidden' : 'visible' }}
/>
);
}

return (
<>
{this.state.loading && _('Loading...')}
{
<span // nosemgrep: typescript.react.security.audit.react-no-refs.react-no-refs
ref={(el) => {
this.el = el;
}}
style={{ visibility: this.state.loading ? 'hidden' : 'visible' }}
/>
}
{loading && _('Loading...')}
{content}
</>
);
}
Expand All @@ -98,6 +196,7 @@ CustomTableControl.propTypes = {
field: PropTypes.string,
fileName: PropTypes.string.isRequired,
type: PropTypes.string,
moreInfo: PropTypes.array.isRequired,
};

export default CustomTableControl;
Loading
Loading