@prisma-cms/component
Version:
React component for @prisma-cms
423 lines • 14.8 kB
JavaScript
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const react_1 = __importStar(require("react"));
// import PropTypes from 'prop-types'
const Snackbar_1 = __importDefault(require("./components/Snackbar"));
const urijs_1 = __importDefault(require("urijs"));
// TODO use more actual module
const roddeh_i18n_1 = __importDefault(require("roddeh-i18n"));
const context_1 = __importDefault(require("@prisma-cms/context"));
__exportStar(require("./interfaces"), exports);
const defaultLocales = {
ru: {
values: {
Error: 'Ошибка',
Errors: 'Ошибки',
'Request error': 'Ошибка выполнения запроса',
'Check required forms fill in': 'Проверьте правильность заполнения формы',
},
},
};
// export default class PrismaCmsComponent<P extends PrismaCmsComponentProps = any, S extends PrismaCmsComponentState = any>
// extends PureComponent<P, S> {
class PrismaCmsComponent extends react_1.PureComponent {
constructor(props) {
super(props);
this.onChangeBind = (event) => this.onChange(event);
this.onFocusBind = (event) => this.onFocus(event);
this.closeErrorBind = (error) => this.closeError(error);
const { filters, locales } = this.props;
this.state = Object.assign(Object.assign({}, this.state), { locales: {}, filters, errors: [], error: null, loading: false, notifications: [] });
this.canEdit = this.canEdit.bind(this);
this.getObject = this.getObject.bind(this);
this.updateObject = this.updateObject.bind(this);
this.mutate = this.mutate.bind(this);
this.initLocales(defaultLocales);
// if (locales) {
this.initLocales(locales);
// }
}
initLocales(locales) {
if (locales) {
for (const lang in locales) {
const locale = locales[lang];
if (locale) {
this.addLexicon(lang, locale);
}
}
}
}
createLexicon(locale) {
return roddeh_i18n_1.default.create(locale);
}
addLexicon(lang, locale) {
const locales = this.state.locales;
if (!locales[lang] && locales && typeof locales === 'object') {
locales[lang] = this.createLexicon(locale);
}
else {
locales[lang].translator.add(locale);
}
return locales[lang];
}
lexicon(word, options) {
const { lang = 'en' } = this.context;
const { locales } = this.state;
return locales && locales[lang] ? locales[lang](word, options) : word;
}
/**
* @deprecated Will be remove in next major version
*/
query(params) {
const { client } = this.context;
return client.query(params);
}
mutate(params) {
return this.request('mutate', params);
}
request(method, params) {
return __awaiter(this, void 0, void 0, function* () {
if (this.state.loading) {
return;
}
this.setState({
loading: true,
});
const { client } = this.context;
const result = yield client[method](params).catch((error) => {
error.message =
(error.message && error.message.replace(/^GraphQL error: */, '')) || '';
return error;
});
this.setState({
loading: false,
});
let error = null;
let errors;
if (result instanceof Error) {
// error = result.message;
error = result;
// throw(result);
}
else {
const { response } = result.data || {};
const { success, message, errors: responseErrors,
// ...other
} = response || {};
errors = responseErrors;
if (success !== undefined) {
if (!success) {
error = this.lexicon(message || 'Request error');
}
}
}
this.setState({
errors,
});
if (error) {
this.addError(error);
throw result;
}
else {
this.setState({
error: null,
});
}
return result;
});
}
// reloadApiData() {
// const { loadApiData } = this.context
// loadApiData && loadApiData()
// }
renderField(field) {
const { errors } = this.state;
const {
// key,
type: Field, props,
// ...other,
} = field;
const { key, name, label, helperText: helperTextProp } = props,
// onFocus,
other = __rest(props, ["key", "name", "label", "helperText"]);
let helperText = helperTextProp;
// const error = errors ? errors.find((n) => n.key === name) : null;
const error = errors
? errors.find((n) => n.key !== undefined ? n.key === name : n.name === name)
: null;
// return field;
helperText = error ? error.message : helperText;
if (helperText) {
helperText = this.lexicon(helperText);
}
return (react_1.default.createElement(Field, Object.assign({ key: key, name: name, error: error ? true : false, helperText: helperText, label: label ? this.lexicon(label) : label, onFocus: this.onFocusBind, onChange: this.onChangeBind }, other)));
}
onChange(event) {
const { name, value: valueProp, type, checked } = event.target;
let value = valueProp;
switch (type) {
case 'boolean':
case 'checkbox':
value = checked;
break;
case 'number':
value = Number(value);
break;
default:
}
this.updateObject({
[name]: value,
});
}
onFocus(event) {
const { name } = event.target;
if (name) {
this.resetError(name);
}
return;
}
resetError(name) {
const { errors } = this.state;
if (errors) {
const index = errors.findIndex((error) => error.key !== undefined ? error.key === name : error.name === name);
if (index !== -1) {
const newErrors = errors.slice(0);
newErrors.splice(index, 1);
this.setState({
errors: newErrors,
});
}
}
}
updateObject(data) {
const { _dirty } = this.state;
// const { onChange } = this.props;
const newDirty = this.prepareDirty(data
? Object.assign(Object.assign({}, _dirty), data) : data);
const newState = this.prepareNewState({
_dirty: newDirty,
});
// this.setState(newState, () => {
// onChange && onChange(newDirty);
// })
this.setState(newState);
}
prepareDirty(data) {
return data;
}
prepareNewState(newState) {
return newState;
}
// getHistory() {
// const {
// router: { history },
// } = this.context
// return history
// }
getLocation() {
return global.location;
}
getLocationUri() {
const { pathname, search } = this.getLocation();
return new urijs_1.default(`${pathname}${search}`);
}
getLocationQuery(field) {
return this.getLocationUri().query(true)[field];
}
onFilterFieldChange(event) {
const { name, value } = event.target;
this.setFilters({
[name]: value ? value : undefined,
});
}
setFilters(data) {
const { filters } = this.state;
this.setState({
filters: Object.assign(Object.assign({}, filters), data),
});
}
/**
* Простая проверка выставлены ли фильтры или нет
*/
hasFilters() {
const filters = this.getFilters();
return typeof filters &&
filters === 'object' &&
Object.keys(filters).length > 0
? true
: false;
}
/**
* Получаем фильтры из адресной строки
*/
getFilters() {
const { filters } = this.state;
return filters || {};
}
addFilterCondition(where, key, value) {
return Object.assign(where, {
[key]: value,
});
}
cleanFilters() {
this.setState({
filters: undefined,
});
}
canEdit() {
var _a;
const object = (_a = this.getObject()) !== null && _a !== void 0 ? _a : null;
if (object) {
const { id: objectId, CreatedBy } = object;
const { id: currentUserId, sudo } = this.getCurrentUser() || {};
const { id: createdById } = CreatedBy || {};
if (objectId) {
if (sudo || (createdById && createdById === currentUserId)) {
return true;
}
}
else {
return true;
}
}
return false;
}
// getObject() {
// const { data, object } = this.props
// return object !== undefined ? object : (data && data.object) || null
// }
getObject() {
// const { data, object } = this.props
// return object !== undefined ? object : (data && data.object) || null
return this.props.object;
}
getCurrentUser() {
const { user: currentUser } = this.context;
return currentUser;
}
addError(error) {
let _error;
const { errorDelay } = this.props;
if (typeof error === 'string') {
_error = new Error(error);
}
else {
_error = error;
}
Object.assign(_error, {
_id: new Date().getTime(),
});
const { notifications: oldNotifications } = this.state;
const notifications = (oldNotifications || []).slice(0);
notifications.push(_error);
if (errorDelay) {
setTimeout(() => this.closeError(_error), errorDelay);
}
this.setState({
notifications,
});
return error;
}
removeError(error) {
const { notifications: oldNotifications } = this.state;
if (oldNotifications && oldNotifications.length) {
const notifications = oldNotifications.slice(0);
const index = notifications.indexOf(error);
if (index !== -1) {
notifications.splice(index, 1);
this.setState({
notifications,
});
}
}
}
closeError(error) {
Object.assign(error, {
open: false,
});
this.forceUpdate();
setTimeout(() => {
this.removeError(error);
}, 2000);
}
renderErrors() {
const { notifications } = this.state;
if (notifications && notifications.length) {
const errors = notifications.map((error, index) => {
const { _id, message, open = true } = error;
if (!message) {
return null;
}
return (react_1.default.createElement(Snackbar_1.default, { key: _id || index, opened: open, error: error, message: this.lexicon(message), close: this.closeErrorBind }));
});
return errors;
}
else {
return null;
}
}
render() {
const { children } = this.props;
return (react_1.default.createElement(react_1.default.Fragment, null,
children,
this.renderErrors()));
}
}
exports.default = PrismaCmsComponent;
PrismaCmsComponent.contextType = context_1.default;
// static proptTypes = {
// locales: PropTypes.object,
// filters: PropTypes.object,
// errorDelay: PropTypes.number.isRequired,
// data: PropTypes.object,
// object: PropTypes.object,
// }
PrismaCmsComponent.defaultProps = {
errorDelay: 5000,
};
//# sourceMappingURL=index.js.map