项目作者: ahmedtadde

项目描述 :
Minimal & Reactive form handling library
高级语言: TypeScript
项目地址: git://github.com/ahmedtadde/rx-form-data.git
创建时间: 2020-05-02T17:37:56Z
项目社区:https://github.com/ahmedtadde/rx-form-data

开源协议:MIT License

下载


rx-form-data

Codacy Badge
Known Vulnerabilities
@metronlabs/rx-form-data" alt="npm bundle size">
dependencies status
dev dependencies status
@metronlabs/rx-form-data" alt="npm">

Minimal, Reactive Form data handling

  • Fully written in Typescript
  • Turns form into a signal of field values (user input & some metadata)
  • Framework Agnostic
  • Easy integration with any custom validation logic
  • Super tiny with ZERO dependencies

Table of Contents

Install

  1. npm install --save @metronlabs/rx-form-data
  1. // using ES6 modules
  2. import RxFormData from "@metronlabs/rx-form-data";
  3. // using CommonJS modules
  4. const RxFormData = require("@metronlabs/rx-form-data");

The UMD build is also available on unpkg:

  1. <script src="https://unpkg.com/@metronlabs/rx-form-data/lib/index.umd.js"></script>

You can find the library on window.RxFormData.

Usage

  1. import RxFormData from "@metronlabs/rx-form-data";
  2. const { subscribe, register, dispatch, ACTION_TYPE } = RxFormData(
  3. "some-form-id",
  4. // form submission handler. This is required.
  5. (formvalues, formvalidation, formdata) => {
  6. // do some custom logic before XHR/AJAX calls... formdata is an HTML5 FormData object of the `some-form-id` form element
  7. console.log(
  8. "ON SUBMIT HANDLER CALLED",
  9. formvalues,
  10. formvalidation,
  11. formdata
  12. );
  13. return Promise.resolve([formvalues]);
  14. }
  15. );
  16. //Registers all the input fields on the `some-form-id` form element
  17. dispatch(ACTION_TYPE.REGISTER_ALL);
  18. //Alternatively, you can choose which fields to register
  19. //That can be done this way ...
  20. dispatch(ATION_TYPE.REGISTER, ["some-field-x", "some-field-y"]);
  21. // OR, this way
  22. const unregister = register(["some-field-x", "some-field-y"]);
  23. // ^ advantage of the latter is that you get the 'unregister' function;
  24. //For validation, add some decoders.
  25. //A decoder has a name/label, a bunch of predicates with formvalues as input, and (static or computed) error messages
  26. dispatch(ACTION_TYPE.ADD_DECODERS, [
  27. {
  28. name: "validation-for-some-field-x",
  29. use: [
  30. (formvalues) => {
  31. //...some logic
  32. return true; // if returned value is not 'true' <=> validation failed!
  33. }
  34. ],
  35. messages: ["Input is invalid"] // this can also be a function (context) => string | string[]
  36. }
  37. ]);
  38. const unsubscribe = subscribe((formvalues, formvalidation) => {
  39. //formvalues includes data for all the currently registered fields
  40. //formvalidation is derived from formvalues and the registered decoders...
  41. console.info("FORM DATA SUBSCRIBER", formvalues, formvalidation);
  42. });
  43. // You can have more than one subscriber (...just dont go crazy with it; all things in moderation and all)
  44. const unsubscribe2 = subscribe((formvalues, formvalidation) => {
  45. console.info("FORM DATA SUBSCRIBER II", formvalues, formvalidation);
  46. });
  47. // some time later... when y'er done
  48. setTimeout(() => {
  49. unsubscribe();
  50. unsubscribe2();
  51. }, 2 * 60 * 1000);
  52. setTimeout(() => {
  53. // clean up: unmounts all form element listners, dettaches all subscribers, clears registered fields & decoders...
  54. dispatch(ACTION_TYPE.DESTROY);
  55. }, 3 * 60 * 1000);

API

Scan the type declarations (@types folder) for some insights on implementation details:

  • RxFormData
    Main package function. Use this to create an RxFormData instance.
  1. const { subscribe, register, dispatch, ACTION_TYPE } = RxFormData(
  2. "...",
  3. // Form submission handler...
  4. // Keep in mind, you are fully responsible for how to handle this event.
  5. // All this library does is give you enough information to know what to do
  6. // The formdata parameter is the FormData object of the form element at the moment a submission is triggered
  7. (formvalues, formvalidation, formdata) => {...}
  8. );
  • subscribe
    Sets up subscriptions to form values and form validation updates. Takes a function as an argument.
  1. const unsubscribe = subscribe((formvalues, formvalidation) => {...});
  2. //when subscription is no longer needed...
  3. unsubscribe()
  • register
    Registers form field elements. Accepts a list of field names or regex expressions that are meant to match one or multiple field names.
  1. const unregister = register(["username", "email", /^password.*/]);
  2. //when you no longer care about the fields...
  3. unregister();
  4. //Or to keep these fields in the form values
  5. unregister(true);
  • dispatch & ACTION_TYPE
    Utilities to interface with the RxFormData instance
  1. //List of available actions
  2. {
  3. REGISTER: "REGISTER_FIELDS",
  4. REGISTER_ALL: "REGISTER_ALL_FIELDS",
  5. UNREGISTER: "UNREGISTER_FIELDS",
  6. UNREGISTER_ALL: "UNREGISTER_ALL_FIELDS",
  7. ADD_DECODERS: "ADD_DECODERS",
  8. REMOVE_DECODERS: "REMOVE_DECODERS",
  9. CLEAR_DECODERS: "CLEAR_DECODERS",
  10. DESTROY: "DESTROY_PROGRAM"
  11. };
  12. dispatch(ACTION_TYPE.REGISTER, payload: Array<string | RegExp>);
  13. dispatch(ACTION_TYPE.REGISTER_ALL); // registers all fields currently on the form elment
  14. dispatch(ACTION_TYPE.UNREGISTER, payload: Array<string | RegExp>); // keepvalues is set to false by default
  15. dispatch(ACTION_TYPE.UNREGISTER, payload: { use: payload: Array<string | RegExp>, keepvalues: boolean });
  16. dispatch(ACTION_TYPE.UNREGISTER_ALL, keepvalues?: boolean);
  17. dispatch(ACTION_TYPE.ADD_DECODERS, payload: Array<{
  18. /** this is used as key on the formvalidaiton object */
  19. name: string;
  20. /** predicate functions (i.e validators) */
  21. use: Array<(formvalues: Readonly<Record<string, ...>>) => boolean>;
  22. /** error messages for validation failure(s) */
  23. messages: string[] | (context: Record<string, unknown>) => string | string[];
  24. }>);
  25. dispatch(ACTION_TYPE.REMOVE_DECODERS, payload: Array<string | RegExp>);
  26. dispatch(ACTION_TYPE.CLEAR_DECODERS); // clears all registered decoders
  27. dispatch(ACTION_TYPE.DESTROY); // basically renders RxFormData inert

Contribute

First off, thanks for taking the time to contribute!
Now, take a moment to be sure your contributions make sense to everyone else.

Reporting Issues

Found a problem? Want a new feature? First of all see if your issue or idea has already been reported.
If not, just open a new clear and descriptive issue.

Submitting pull requests

Pull requests are the greatest contributions, so be sure they are focused in scope, and do avoid unrelated commits.

  • Fork it!
  • Clone your fork: git clone https://github.com/<your-username>/@metronlabs/rx-form-data
  • Navigate to the newly cloned directory: cd @metronlabs/rx-form-data
  • Create a new branch for the new feature: git checkout -b features/my-new-feature
  • Install the tools necessary for development: npm install
  • Make your changes.
  • Commit your changes: git commit -am 'Add some feature'
  • Push to the branch: git push origin features/my-new-feature
  • Submit a pull request with full remarks documenting your changes.

License

MIT License © Ahmed Tadde

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the “Software”), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice aTd this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.