UNPKG

drf-react-by-schema

Version:

Components and Tools for building a React App having Django Rest Framework (DRF) as server

200 lines (199 loc) 10.3 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (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 () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); 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 __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.SelectEditInputCell = SelectEditInputCell; const react_1 = __importStar(require("react")); const x_data_grid_1 = require("@mui/x-data-grid"); const TextField_1 = __importDefault(require("@mui/material/TextField")); const IconButton_1 = __importDefault(require("@mui/material/IconButton")); const Edit_1 = __importDefault(require("@mui/icons-material/Edit")); const Autocomplete_1 = __importStar(require("@mui/material/Autocomplete")); const utils_1 = require("../../utils"); const DialogActions_1 = __importDefault(require("../DialogActions")); const filter = (0, Autocomplete_1.createFilterOptions)(); function SelectEditInputCell({ field, id, value, column, type, options, isIndexField, multiple = false, onEditModel, fieldsLayout, sx = {}, setDialog, }) { const [loadedOptions, setLoadedOptions] = (0, react_1.useState)(null); // TODO: allow edit option label, as in formautocomplete! const apiRef = (0, x_data_grid_1.useGridApiContext)(); const handleChange = (newValue) => __awaiter(this, void 0, void 0, function* () { yield apiRef.current.setEditCellValue({ id, field, value: newValue }); apiRef.current.stopCellEditMode({ id, field }); }); const labelKey = ['field', 'nested object'].includes(type) || isIndexField ? 'label' : 'display_name'; const valueKey = ['field', 'nested object'].includes(type) || isIndexField ? 'id' : 'value'; let creatableProps = {}; // if (column.creatable || isIndexField) { if (column.creatable) { creatableProps = { freesolo: 'true', filterOptions: (thisOptions, params) => { let filtered = filter(thisOptions, params); const inputValue = params.inputValue ? params.inputValue : ''; const inputValueSlug = (0, utils_1.slugify)(inputValue); const inputValueLength = inputValueSlug.length; // Suggest the creation of a new value const isExisting = thisOptions.find((option) => inputValueSlug === (0, utils_1.slugify)(option[labelKey])); if (inputValue !== '' && !isExisting) { filtered.push({ inputValue, [labelKey]: `Criar "${inputValue}"`, }); } // Show first the exact match: if (isExisting) { filtered = [isExisting, ...filtered.filter((option) => isExisting.id !== option.id)]; } // Show first the options that start with inputValue: const startsWith = filtered.filter((option) => inputValueSlug === (0, utils_1.slugify)(option.label).substring(0, inputValueLength)); if (startsWith.length > 0) { const startsWithIds = startsWith.map((option) => option.id); filtered = [ ...startsWith, ...filtered.filter((option) => !startsWithIds.includes(option.id)), ]; } return filtered; }, handleHomeEndKeys: true, getOptionLabel: (option) => { // Value selected with enter, right from the input if (typeof option === 'string') { return option; } // Criar "xxx" option created dynamically if (option.inputValue) { return option.inputValue; } // Regular option return option[labelKey]; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any renderOption: (props, option) => { return (react_1.default.createElement("li", Object.assign({ key: option[valueKey] }, props), option[labelKey])); }, }; } (0, react_1.useEffect)(() => { if (!options) { return; } if (Array.isArray(options)) { setLoadedOptions(options); return; } if (!loadedOptions) { options().then((newOptions) => setLoadedOptions(newOptions)); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [field, options]); if (!options || (Array.isArray(options) && options.length === 0) || loadedOptions === null || loadedOptions.length === 0) { return react_1.default.createElement(react_1.default.Fragment, null); } return (react_1.default.createElement(Autocomplete_1.default, Object.assign({ key: field, id: field, value: value, options: loadedOptions, selectOnFocus: true, autoHighlight: true, multiple: multiple, isOptionEqualToValue: (option, value) => { return option[labelKey] === value[labelKey]; }, getOptionLabel: (option) => { return option ? option[labelKey] : ''; }, onChange: (e, value) => { // if (!column.creatable && !isIndexField) { if (!column.creatable) { handleChange(value); return; } let newValue = value; if (typeof newValue === 'string') { const tmpId = (0, utils_1.getTmpId)(); newValue = { [valueKey]: tmpId, [labelKey]: newValue, }; } if (newValue && newValue.inputValue) { const tmpId = (0, utils_1.getTmpId)(); if (onEditModel) { // Open modal to save new item: onEditModel({ model: field, id: tmpId, labelKey, fieldsLayout, initialValuesPartial: { nome: newValue.inputValue, // TODO: make this "nome" generic! }, }); } // Define new Item as an "optimistic response" newValue = { [valueKey]: tmpId, [labelKey]: newValue.inputValue, }; } handleChange(newValue); }, fullWidth: true, renderInput: (params) => (react_1.default.createElement(react_1.default.Fragment, null, column.creatable ? (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { margin: "normal", InputProps: Object.assign(Object.assign({}, params.InputProps), { endAdornment: (react_1.default.createElement(react_1.default.Fragment, null, !multiple && onEditModel && value && (react_1.default.createElement(IconButton_1.default, { size: "small", onClick: () => { if ((0, utils_1.isTmpId)(value.id)) { setDialog({ open: true, loading: false, title: 'Linha sendo criada', Body: 'Esta linha está sendo criada agora por você. Para editar suas propriedades, salve antes, e depois você poderá editar!', Actions: react_1.default.createElement(DialogActions_1.default, { setDialog: setDialog, btnCancel: "Entendi" }), }); return; } onEditModel({ model: field, id: value[valueKey], labelKey, fieldsLayout, }); } }, react_1.default.createElement(Edit_1.default, null))), params.InputProps.endAdornment)) }) }))) : (react_1.default.createElement(TextField_1.default, Object.assign({}, params, { sx: sx }))))) }, creatableProps))); }