@sap-ux/ui-components
Version:
SAP UI Components Library
103 lines • 3.38 kB
JavaScript
import React from 'react';
import { UIIconButton } from '../UIButton/index.js';
import { UILoader } from '../UILoader/index.js';
import './UILoadButton.scss';
/**
* Component to render load button with spin indicator.
*/
export class UILoadButton extends React.Component {
/**
* Constructor method for load button.
*
* @param props Component properties.
*/
constructor(props) {
super(props);
this.minLoaderTimer = undefined;
this.state = this.getBusyState(props, {}) || {};
}
/**
* Method handles component update to refresh busy state.
*
* @param prevProps Component previous properties.
*/
componentDidUpdate(prevProps) {
if (prevProps.busy === this.props.busy) {
return;
}
const state = this.getBusyState(this.props, this.state);
if (state) {
this.setState(state);
}
}
componentWillUnmount() {
if (this.minLoaderTimer) {
window.clearTimeout(this.minLoaderTimer);
}
}
/**
* Method handles end of minimal waiting time.
*/
handleMinWaitingTime() {
this.minLoaderTimer = undefined;
if (!this.props.busy) {
// External busy flag is false, but we were waiting for minimal timeout
this.setState({
busy: false
});
}
}
/**
* Method returns latest busy state by checking current state and props.
*
* @param props Current props.
* @param state Current state.
* @returns Busy state.
*/
getBusyState(props, state) {
let newState;
if (props.busy !== state.busy) {
if (!props.busy && !this.minLoaderTimer) {
newState = {
busy: false
};
}
else if (props.busy) {
newState = {
busy: true
};
window.clearTimeout(this.minLoaderTimer);
if (props.useMinWaitingTime) {
this.minLoaderTimer = window.setTimeout(this.handleMinWaitingTime.bind(this), this.getMinimalWaitingTime());
}
}
}
return newState;
}
/**
* Method returns minimal waiting time for loader depending on passed 'useMinWaitingTime' property.
*
* @returns Minimal waiting time for busy loader.
*/
getMinimalWaitingTime() {
const { useMinWaitingTime } = this.props;
return !useMinWaitingTime || typeof useMinWaitingTime === 'boolean' ? 500 : useMinWaitingTime;
}
/**
* Method to render load button component.
*
* @returns Load button component.
*/
render() {
const { children } = this.props;
const { busy } = this.state;
let { className = '' } = this.props;
const content = busy ? React.createElement(UILoader, { className: 'uiLoaderXSmall', labelPosition: 'right' }) : children;
if (busy) {
const busyClassName = 'loading-button';
className = className ? `${className} ${busyClassName}` : busyClassName;
}
return (React.createElement(UIIconButton, { ...this.props, onClick: busy ? undefined : this.props.onClick, className: className }, content));
}
}
//# sourceMappingURL=UILoadButton.js.map