@limetech/lime-elements
Version:
88 lines (87 loc) • 2.79 kB
JavaScript
import React from "react";
import { findTitle } from "./common";
import { isEmpty } from "lodash-es";
export class CollapsibleItemTemplate extends React.Component {
constructor(props) {
super(props);
this.props = props;
this.state = {
isOpen: false,
};
this.handleOpen = () => {
this.setState({
isOpen: true,
});
};
this.handleAction = this.handleAction.bind(this);
this.isDeepEmpty = this.isDeepEmpty.bind(this);
this.state = {
isOpen: this.isDeepEmpty(props.data),
};
}
componentDidMount() {
const section = this.section;
section.addEventListener('action', this.handleAction);
section.addEventListener('open', this.handleOpen);
this.setActions(section);
}
componentDidUpdate() {
this.setActions(this.section);
}
componentWillUnmount() {
const section = this.section;
section.removeEventListener('action', this.handleAction);
section.removeEventListener('open', this.handleOpen);
}
render() {
const { data, schema, formSchema } = this.props;
let children;
if (this.state.isOpen) {
children = this.props.item.children;
}
const dragHandle = this.props.allowItemReorder
? React.createElement('limel-drag-handle', {
slot: 'header',
class: 'drag-handle',
})
: null;
return React.createElement('limel-collapsible-section', {
header: findTitle(data, schema, formSchema) || 'New item',
class: 'array-item limel-form-array-item--object',
ref: (section) => {
this.section = section;
},
'is-open': this.state.isOpen,
'data-reorder-id': String(this.props.index),
'data-reorderable': this.props.allowItemReorder
? 'true'
: 'false',
}, dragHandle, children);
}
setActions(element) {
const { item, index, allowItemRemoval } = this.props;
const actions = [];
if (allowItemRemoval) {
actions.push({
id: 'remove',
icon: 'trash',
disabled: !item.hasRemove,
run: item.onDropIndexClick(index),
});
}
element.actions = actions;
}
handleAction(event) {
event.stopPropagation();
event.detail.run(event);
}
isDeepEmpty(data) {
if (typeof data !== 'object') {
return false;
}
if (isEmpty(data)) {
return true;
}
return Object.values(data).every(this.isDeepEmpty);
}
}