@arconit/base
v1.0.0
Published
Base components and ducks structs to arconit pages
Downloads
26
Maintainers
Readme
@arconit/base
@arconit/base contains ducks and components that are common between all arconit applications.
Summary
Ducks
Keep in mind that Ducks featured here are extensible. For more information, check extensible-ducks. If you are unfamiliar with these concepts, please check Redux first.
remoteListDuck
This duck is responsible for taking care of lists and for exportation of CSV files.
import { remoteListDuck } from @arconit/base
export default remoteListDuck({
namespace: "yourNamespace",
store: "yourStoreName",
server: "arconitServer",
path: "arconitEndpoint"
});
Then, you're able to use all remoteListDuck creators.
remoteListDuck creators:
| Name | Parameters | Description | |------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------| | count | (opts) parameters for the query. | supports pagination, must be called whenever pagination is present. | | list | (opts) parameters for the query. | lists the objects from the endpoint provided by the path field and fill the store with them. By default, only the first 20 objects will be listed. | | export | (object) object has the following fields: noObjsErrorMessage, exportedFilename | exports all objects from the endpoint, provided by "path" field on the form of a CSV file. The exported filename will be [exporteFilename] | | reset | (fields) fields specified on this object will NOT be reseted. | resets the store object specified by "store" field. | | updatePagination | (skip = 0, customPerPage = 15) skip: how many objects will be skiped from the start of the listage. customPerPage: how many objects will be listed per page. | updates how many objects will be listed from the "list" creator. | | updateWhere | (obj) query parameter | updates the fixed query parameters specified on [obj]. | | update | (fields) fields to be updated | updates the fields specified by [fields]. |
remoteObjDuck
This duck is responsible for taking care of single objects and importation of CSV files.
import { remoteObjDuck } from "@arconit/base";
export default remoteObjDuck({
namespace: "yourNamespace",
store: "yourStore",
server: "arconitServer",
path: "arconitEndpoint"
initialState: { initialState }
});
Then, you're able to use all remoteObjDuck creators.
| Name | Parameters | Description | |--------|-------------------------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------| | reset | (fields) fields specified on this object will NOT be reseted. | resets the store object specified by "store" field. | | update | (fields) fields to be updated. | updates the fields specified by [fields]. | | get | (id, pathOpts) id: id of the object that will be queried. pathOpts: additional options on the queried URL. | queries the object with the specified [id]. | | delete | (manualId) id of the object that will be deleted. | deletes the object with the specified [manualId]. If no [manualId] is specified, the object loaded into the store will be deleted. | | patch | (fields) fields to be updated | patches the [fields] of the current object on the store. | | save | (opts) query options | saves the current object loaded on the store to the API if it's id is undefined. If it's not, update it. | | import | (object) object has the following fields: targetCSV, readCSV, treatCSVRowFun, objList | imports a CSV and save all objects that don't have id's, or update those who have an id that already belongs to an object on the API. |
remoteSettingDuck
This duck is responsible for taking care of setting objects coming from the /settings endpoint from arconit api.
import { remoteSettingDuck } from "@arconit/base";
export default remoteSettingDuck({
namespace: "yourNamespace",
store: "yourStore",
server: "arconitServer",
path: "arconitEndpoint"
initialState: { initialState },
ignoreEmpty: true
});
The remoteSettingDuck creators are basically the same from the remoteObjDuck's, because remoteSettingDuck extends remoteObjDuck. The only creator that's not equal is the get creator.
Here's is the implementation of the get creator on remoteSettingDuck:
import remoteObjDuck from "./remoteObjDuck.js";
export default (opts) => remoteObjDuck({
...opts,
path: `/api/v1/settings/${opts.setting}`
}).extend({
creators: ({ store, types, options: { server, path } }) => ({
get: (pathOpts={}) => dispatch => {
dispatch({ type: types.RESET, payload: {} });
return server
.get(path, { params: pathOpts.params })
.then(resp => {
if (!opts.ignoreEmpty && resp.data === "") {
alert(`Problema ao importar configuração: ${opts.setting}`);
}
return dispatch({
type: types.FETCH_FULFILLED,
payload: { data: resp.data },
meta: { pathOpts }
})
})
.catch(error => {
alert(`Problema ao importar configuração: ${opts.setting}`);
dispatch({ type: types.FETCH_FAILED, payload: error });
});
}
})
});
Basic Example:
import { useDispatch, useSelector } from "react-redux";
import { HandicraftDuck, HandicraftsDuck } from "Ducks";
const handicrafts = useSelector(store => store.handicrafts.list);
const handicraftsStatus = useSelector(store => store.handicrafts.status);
const handicraftsError = useSelector(store => store.handicrafts.error);
const dispatch = useDispatch();
const listHandicrafts = () => dispatch(HandicraftsDuck.creators.list());
const exportHandicrafts = () => dispatch(HandicraftsDuck.creators.export());
Now you can use these callbacks/store objects wherever you want.
React Components
Loading Modal
Properties:
- None
Example:
import React, { useState, useEffect } from "react";
import { useSelector } from "react-redux";
import { LoadingModal } from "@arconit/base";
const LoadingModalExample = () => {
const [isLoading, setIsLoading] = useState(true);
const myObjStatus = useSelector(store => store.myObj.status);
useEffect(() => {
switch(myObjStatus) {
case "FETCHED":
setIsLoading(false);
break;
default:
setIsLoading(true);
break;
}
}, [myObjStatus]);
return (
<React.Fragment>
{isLoading} && <LoadingModal />}
</React.Fragment>
);
};
Delete Modal
Properties:
- deleteFunc (function): function that contains the delete logic.
- objId (integer): id of the object to be deleted.
- objName (string): name of the object that will be displayed on the modal.
- toggleFunc (function): function that controls the delete modal toggle.
- listage (function): function that lists the object list.
Example:
import React, { useState } from "react";
import { DeleteModal } from "@arconit/base";
import { MyRemoteObjDuck, MyRemoteListDuck } from "Ducks";
import { useDispatch } from "react-redux";
const DeleteModalExample = ({ myObjsList }) => {
const dispatch = useDispatch();
const listMyObjs = () => dispatch(MyRemoteListDuck.creators.list());
const deleteMyObj = id => dispatch(MyRemoteObjDuck.creators.delete(id));
const [toggleDeleteModal, setToggleDeleteModal] = useState(false);
const [myObjId, setMyObjId] = useState(undefined);
return (
<React.Fragment>
{toggleDeleteModal && (
<DeleteModal
deleteFunc={deleteMyObj}
objId={myObjId}
objName={"Handicraft"}
toggleFunc={setToggleDeleteModal}
listage={listMyObjs}
/>
)}
<table>
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Name</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{
myObjsList.map(myObj => {
return (
<tr key={myObj.id}>
<td scope="row">{myObj.id}</td>
<td>{myObj.name}</td>
<td>
<button
onClick={() => {
setMyObjId(myObj.id);
setToggleDeleteModal(true);
}}
>
Delete
</button>
</td>
</tr>
);
})
}
</tbody>
</table>
</React.Fragment>
);
};
Pagination
Properties:
- selector (object): Redux store selector.
- updatePagination (function): Function that updates the pagination (updatePagination creator, inherited from remoteListDuck)
- listFunc (function): function that lists the object list.
Example:
import React, { useEffect } from "react";
import { Pagination } from "@arconit/base";
import { ObjsTable } from "MyComponents";
import { MyRemoteListDuck } from "Ducks";
import { useSelector, useDispatch } from "react-redux";
const PaginationExample = () => {
const mySelector = useSelector(store => store.myObjs);
const listMyObjs = () => dispatch(MyRemoteListDuck.creators.list());
const updatePagination = (skip, perPage) => (
dispatch(MyRemoteListDuck.creators.updatePagination(skip, perPage))
);
const dispatch = useDispatch();
useEffect(() => {
/* must be called in order to Pagination Components to work properly */
updatePagination();
dispatch(MyRemoteListDuck.creators.count());
/* ________________________________________________________________ */
listMyObjs();
}, []);
return (
<React.Fragment>
<ObjsTable list={mySelector.list} />
<Pagination
selector={mySelector}
updatePagination={updatePagination}
listFunc={listMyObjs}
/>
</React.Fragment>
);
};
Autocomplete
Properties:
- inputClassName (string): input field class.
- renderInput (jsx/html component): input component.
- wrapperClassName (string): wrapper class.
- value (any): The value to display in the input field;
- items (array): The items to display in the dropdown menu
- getItemValue (any): Used to read the display value from each entry in items.
- onSelect (function): Arguments: value: String, item: Any. Invoked when the user selects an item from the dropdown menu.
- onChange (function): Arguments: event: Event, value: String. Invoked every time the user changes the input's value.
- renderItem (function): Arguments: item: Any, isHighlighted: Boolean, styles: Object. Invoked for each entry in items that also passes shouldItemRender to generate the render tree for each item in the dropdown menu. styles is an optional set of styles that can be applied to improve the look/feel of the items in the dropdown menu.
For more info, check react-autocomplete.
Example:
import React, { useState, useEffect } from "react";
import { Autocomplete } from "@arconit/base";
import { MyRemoteListDuck, MyRemoteObjDuck } from "Ducks";
import { useSelector, useDispatch } from "react-redux";
const AutocompleteExample = () => {
const [myObjValue, setMyObjValue] = useState("");
const targetObj = useSlector(store.targetObj.obj); // Object being worked on.
const myObjsAC = useSelector(store.myObjsAC.list);
const myObj = useSelector(store.myObj.obj); // Object that will serve as prop for targetObj
const dispatch = useDispatch();
const updateTargetObj = fields => (
dispatch(MyRemoteObjDuck.creators.update(fields))
);
const listMyObjs = value => (
dispatch(MyRemoteListDuck.creators.list({
params: { where: { obj_prop_label: { contains: value } } }
}));
);
useEffect(() => {
listMyObjs();
}, []);
<Autocomplete
inputClassName="my-input-class"
renderInput={<input type="search" placeholder="Placeholder text" {...props} />}
wrapperClassName="my-wrapper-class"
value={myObjValue || ""}
items={myObjsAC}
getItemValue={item => item.obj_prop_label}
onSelect={(value, item) => {
setMyObjValue(item.obj_prop_label);
updateTargetObj({ target_prop: item.target_prop });
}}
onChange={(evt, value) => {
setMyObjValue(value);
listMyObjs(value);
if(value === "") {
updateTargetObj({ target_prop: "" });
}
}}
renderItem={item => item.obj_prop_label}
/>
};
Autocomplete Select
Properties:
- className: class name.
- defaultOptions: check react-select async docs.
- isMulti (boolean): determines if the select will be a multi-select or a regular select.
- loadOptions: check react-select async docs.
- placeholder (string): placeholder to the select input.
- value (any): The value to be dispalyed on the select field
Example:
import React, { Fragment, useEffect, useState } from "react";
import { AutocompleteSelect } from "Components";
import { ComplianceDuck, SecuritiesDuck } from "Ducks";
import { useDispatch, useSelector } from "react-redux";
const SecurityIds = ({ compliance, complianceStatus, setWasFetched }) => {
const securities = useSelector(store => store.securities.list);
const [selectedSecurities, setSelectedSecurities] = useState([]);
const dispatch = useDispatch();
const listComplianceSecurities = securityIds => (
dispatch(SecuritiesDuck.creators.list({
params: { where: { id: securityIds } }
}))
);
const filterOptions = inputValue => (
dispatch(SecuritiesDuck.creators.listAutocomplete({ params: {
order: { symbol: "asc" },
where: { symbol: { starts_with: inputValue.toUpperCase() } }
}
}))
);
const loadOptions = async (inputValue, callback) => {
const resp = await filterOptions(inputValue)
const options = resp.map(security => ({
value: security.id,
label: security.symbol
}));
const sortedOptions = options.sort(
(a, b) => a.label.length > b.label.length
);
callback(sortedOptions);
};
const securitiesSelectOnChange = selected => {
/* necessary to multi select animation */
setSelectedSecurities(selected);
updateCompliance({
...compliance,
security_id: selected.map(security => security.value)
});
};
const updateCompliance = fields => dispatch(
ComplianceDuck.creators.update(fields)
);
useEffect(() => {
if(compliance && complianceStatus === "READY") {
(async () => {
await listComplianceSecurities(compliance.security_id);
setSelectedSecurities(securities);
setWasFetched(prevState => ({ ...prevState, securities: true }));
})();
}
}, [complianceStatus]);
return (
<Fragment>
<label htmlFor="selectedSecurities" className="text__xxs font-bold text__verde">
Tipos de ativos: *
</label>
<AutocompleteSelect
isMulti={true}
loadOptions={loadOptions}
placeholder={"Selecione os tipos de ativos."}
value={selectedSecurities}
onChange={securitiesSelectOnChange}
/>
</Fragment>
);
};
export default SecurityIds;
Masks
cnpj:
cnpjMask(value):
- value (string) -> cnpj.
date
dateMask(date, format):
- date (date) -> date object.
- format (string) -> date format, if undefined the dateMask will convert to brazilian style date. For more info on date format, please check https://day.js.org/docs/en/display/format.
Mask Components
cnpj input:
import React from "react";
import { CnpjInputMask } from "@arconit/base";
<CnpjInputMask
classname="your-class"
value={valueThatWillAppearOnInput}
updateFunc={updateFunc}
targetField={fieldOfTheObjectThatWillBeUpdated}
otherProps={otherProps}
/>
currency mask:
import React from "react";
import { CurrencyMask } from "@arconit/base";
<CurrencyMask
className="your-class"
value={value}
prefix={prefix}
otherProps={otherPorps}
/>
- Note: if prefix = undefined, "R$ " will be used.
Development
run the following command on @arconit/base root folder:
yarn link
Then, run the following command on the root folder of the project that will use @arconit/base:
yarn link @arconit/base
If you get a react related error, try the following:
cd node_modules/react
yarn link