1 | import React, { useContext } from "react";
|
2 | import dataObjectContext from "./context";
|
3 | import { getLocalizedString } from "@olenbetong/utils";
|
4 |
|
5 | function objectWithoutProperties(obj, keys) {
|
6 | var target = {};
|
7 |
|
8 | for (var i in obj) {
|
9 | if (keys.indexOf(i) < 0 && Object.prototype.hasOwnProperty.call(obj, i)) {
|
10 | target[i] = obj[i];
|
11 | }
|
12 | }
|
13 |
|
14 | return target;
|
15 | }
|
16 |
|
17 | function createButton(name, onClick, ownProps = []) {
|
18 | const btnComponent = function({ as, children, onClick: onClickProp, ...other }, ref) {
|
19 | const dataObject = useContext(dataObjectContext);
|
20 | const Component = as ? as : "button";
|
21 |
|
22 | const props = objectWithoutProperties(other, ownProps);
|
23 |
|
24 | return (
|
25 | <Component
|
26 | ref={ref}
|
27 | onClick={evt => {
|
28 | if (typeof onClickProp === "function") {
|
29 | onClickProp(evt);
|
30 | }
|
31 | onClick(dataObject, other);
|
32 | }}
|
33 | {...props}
|
34 | >
|
35 | {children}
|
36 | </Component>
|
37 | );
|
38 | };
|
39 |
|
40 | return React.forwardRef(btnComponent);
|
41 | }
|
42 |
|
43 | function save(dataObject) {
|
44 | dataObject.endEdit();
|
45 | }
|
46 |
|
47 | function cancel(dataObject) {
|
48 | dataObject.cancelEdit();
|
49 | }
|
50 |
|
51 | function deleteRow(dataObject, props) {
|
52 | const { confirm = true, index, prompt = getLocalizedString("Are you sure you want to delete this record?") } = props;
|
53 |
|
54 | function doDelete() {
|
55 | if (!index && index !== 0) {
|
56 | dataObject.deleteCurrentRow();
|
57 | } else {
|
58 | dataObject.deleteRow(index);
|
59 | }
|
60 | }
|
61 |
|
62 | if (!confirm) {
|
63 | doDelete();
|
64 | } else {
|
65 | if (typeof prompt === "string" && window.confirm(getLocalizedString(prompt))) {
|
66 | doDelete();
|
67 | } else if (typeof prompt === "function") {
|
68 | const result = prompt(props);
|
69 | if (result === true) {
|
70 | doDelete();
|
71 | } else if (result instanceof Promise) {
|
72 | result.then(shouldDelete => {
|
73 | if (shouldDelete === true) {
|
74 | doDelete();
|
75 | }
|
76 | });
|
77 | }
|
78 | }
|
79 | }
|
80 | }
|
81 |
|
82 | export const SaveButton = createButton("SaveButton", save);
|
83 | export const CancelButton = createButton("CancelButton", cancel);
|
84 | export const DeleteButton = createButton("DeleteButton", deleteRow, ["confirm", "index", "prompt"]);
|