Skip to content

Commit

Permalink
feat: Initial source code
Browse files Browse the repository at this point in the history
  • Loading branch information
sandrina-p committed May 16, 2023
1 parent f5460c6 commit 6db2f3a
Show file tree
Hide file tree
Showing 26 changed files with 8,597 additions and 40 deletions.
Binary file removed .github/media/jsf_logo.png
Binary file not shown.
Binary file added .github/media/jsf_logo_dark.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
61 changes: 61 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
name: Build
on:
pull_request:
jobs:
dependencies:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version-file: '.nvmrc'
cache: 'npm'
- name: Cache NPM dependencies
# From: https://dev.to/drakulavich/aggressive-dependency-caching-in-github-actions-3c64
uses: actions/cache@v3
id: cache-primes
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }}
- name: Install dependencies
if: steps.cache-primes.outputs.cache-hit != 'true'
run: npm ci

test:
runs-on: ubuntu-latest
needs: [dependencies]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version-file: '.nvmrc'
cache: 'npm'

- name: Get cached NPM dependencies
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} # (1)

- name: Tests
run: npm run test

lint:
runs-on: ubuntu-latest
needs: [dependencies]
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version-file: '.nvmrc'
cache: 'npm'

- name: Get cached NPM dependencies
uses: actions/cache@v3
with:
path: node_modules
key: ${{ runner.os }}-node-${{ hashFiles('package-lock.json') }} # (1)

- name: Lint
run: npm run lint
- run: npm run prettier:check
21 changes: 0 additions & 21 deletions .github/workflows/unit-tests.yml

This file was deleted.

1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v18.14.0
1 change: 0 additions & 1 deletion .tool-versions

This file was deleted.

7 changes: 3 additions & 4 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,13 @@ npm test

### Documentation

Althought the library code is open-sourced with units tests, this repo is a replica from the closed-source version. For instance, we don't have the docs website open-sourced yet.
Although the library code is open-sourced with unit tests, the docs cannot be moved yet. Our docs are still coupled to Remote's internal Design System and integration tests. The effort to decouple it at the moment is too high.

We took this decision because our docs use Remote's internal Design System and are coupled to our integration tests (thanks to `Storybook`).
The effort to decouple it at the moment is too high.
So our strategy is to at each new PR, to update the docs internally and manually copy its build to this repo.

## Pull requests (PR)

Maintainers merge PR by squashing all commits and editing the commit message using [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).
Maintainers merge PRs by squashing the commits and editing the merge commit message using [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/).

## Releases

Expand Down
22 changes: 18 additions & 4 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
Copyright 2023 Remote Technology, Inc.
MIT License

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:
Copyright (c) 2023 Remote Technology, Inc.

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
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 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.
The above copyright notice and 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.
26 changes: 17 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
# json-schema-form
<p align="center">
<img src=".github/media/jsf_logo_dark.png" width="600" alt="json-schema-form">
</p>

[logo](./github/media/jsf_logo.png)
<p align="center">
<code>json-schema-form</code> is a headless UI form library powered by <a href="https://json-schema.org/">JSON Schemas</a>.
<br/>
It transforms JSON schemas into Javascript to be consumed by your UI libraries.
</p>

Headless UI form library powered by [JSON Schema](https://json-schema.org/)s. JSF consumes JSON schemas and transforms them into data to be consumed by UI libraries.
---

## Why JSON Schemas for Forms?
### Why JSON Schemas for forms?

JSON Schemas are the SSoT (Single Source of Truth) to share the form _structure_ and _validation_ between frontend and backend, regardless of the language used.
JSON Schemas are the SSoT (Single Source of Truth) that allows you to share form's _structure_ and _validations_ between frontend and backend, regardless of the language used.

JSF (`json-schema-form`) converts a JSON Schema to an array of `fields` for you to connect to your UI Form Components.
## Documentation

### Check the [JSF website](https://json-schema-form.vercel.app/) for the extensive documentation and demos.
Check the 📚 **[JSF website](https://json-schema-form.vercel.app/)** for documentation and demos.

---
## Contributing

Read [CONTRIBUTING](CONTRIBUTING.md) to get started.

_Backed by [Remote.com](https://remote.com/)._
_Backed by [Remote.com](https://remote.com/)_
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@remoteoss/json-schema-form",
"version": "1.0.0-beta.1",
"description": "Headless UI form powered by JSON Schema",
"description": "Headless UI form powered by JSON Schemas",
"author": "Remote.com <[email protected]> (https://remote.com/)",
"license": "MIT",
"homepage": "https://json-schema-form.vercel.app/",
Expand Down
124 changes: 124 additions & 0 deletions src/calculateConditionalProperties.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import merge from 'lodash/merge';
import omit from 'lodash/omit';

import { extractParametersFromNode } from './helpers';
import { supportedTypes } from './internals/fields';
import { getFieldDescription, pickXKey } from './internals/helpers';
import { buildYupSchema } from './yupSchema';
/**
* @typedef {import('./createHeadlessForm').FieldParameters} FieldParameters
*/

/**
* Verifies if a field is required
* @param {Object} node - JSON schema parent node
* @param {String} inputName - input name
* @return {Boolean}
*/
function isFieldRequired(node, inputName) {
// For nested properties (case of fieldset) we need to check recursively
if (node?.required) {
return node.required.includes(inputName);
}

return false;
}

/**
* Loops recursively through fieldset fields and returns an copy version of them
* where the required property is updated.
*
* @param {Array} fields - list of fields of a fieldset
* @param {Object} property - property that relates with the list of fields
* @returns {Object}
*/
function rebuildInnerFieldsRequiredProperty(fields, property) {
if (property?.properties) {
return fields.map((field) => {
if (field.fields) {
return {
...field,
fields: rebuildInnerFieldsRequiredProperty(field.fields, property.properties[field.name]),
};
}
return {
...field,
required: isFieldRequired(property, field.name),
};
});
}

return fields.map((field) => ({
...field,
required: isFieldRequired(property, field.name),
}));
}

/**
* Builds a function that updates the fields properties based on the form values and the
* dependencies the field has on the current schema.
* @param {FieldParameters} fieldParams - field parameters
* @returns {Function}
*/
export function calculateConditionalProperties(fieldParams, customProperties) {
/**
* Runs dynamic property calculation on a field based on a conditional that has been calculated
* @param {Boolean} isRequired - if the field is required
* @param {Object} conditionBranch - condition branch being applied
* @returns {Object} updated field parameters
*/
return (isRequired, conditionBranch) => {
// Check if the current field is conditionally declared in the schema

const conditionalProperty = conditionBranch?.properties?.[fieldParams.name];

if (conditionalProperty) {
const presentation = pickXKey(conditionalProperty, 'presentation') ?? {};

const fieldDescription = getFieldDescription(conditionalProperty, customProperties);

const newFieldParams = extractParametersFromNode({
...conditionalProperty,
...fieldDescription,
});

let fieldSetFields;

if (fieldParams.inputType === supportedTypes.FIELDSET) {
fieldSetFields = rebuildInnerFieldsRequiredProperty(
fieldParams.fields,
conditionalProperty
);
newFieldParams.fields = fieldSetFields;
}

const base = {
isVisible: true,
required: isRequired,
...(presentation?.inputType && { type: presentation.inputType }),
schema: buildYupSchema({
...fieldParams,
...newFieldParams,
// If there are inner fields (case of fieldset) they need to be updated based on the condition
fields: fieldSetFields,
required: isRequired,
}),
};

return omit(merge(base, presentation, newFieldParams), ['inputType']);
}

// If field is not conditionally declared it should be visible if it's required
const isVisible = isRequired;

return {
isVisible,
required: isRequired,
schema: buildYupSchema({
...fieldParams,
...extractParametersFromNode(conditionBranch),
required: isRequired,
}),
};
};
}
91 changes: 91 additions & 0 deletions src/calculateCustomValidationProperties.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import inRange from 'lodash/inRange';
import isFunction from 'lodash/isFunction';
import isNil from 'lodash/isNil';
import isObject from 'lodash/isObject';
import mapValues from 'lodash/mapValues';
import pick from 'lodash/pick';

import { pickXKey } from './internals/helpers';
import { buildYupSchema } from './yupSchema';

export const SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS = ['minimum', 'maximum'];

const isCustomValidationAllowed = (fieldParams) => (customValidation, customValidationKey) => {
// don't apply custom validation in cases when the fn returns null.
if (isNil(customValidation)) {
return false;
}

const { minimum, maximum } = fieldParams;
const isAllowed = inRange(
customValidation,
minimum ?? -Infinity,
maximum ? maximum + 1 : Infinity
);

if (!isAllowed) {
const errorMessage = `Custom validation for ${fieldParams.name} is not allowed because ${customValidationKey}:${customValidation} is less strict than the original range: ${minimum} to ${maximum}`;

if (process.env.NODE_ENV === 'development') {
throw new Error(errorMessage);
} else {
// eslint-disable-next-line no-console
console.warn(errorMessage);
}
}

return isAllowed;
};

export function calculateCustomValidationProperties(fieldParams, customProperties) {
return (isRequired, conditionBranch, formValues) => {
const params = { ...fieldParams, ...conditionBranch?.properties?.[fieldParams.name] };
const presentation = pickXKey(params, 'presentation') ?? {};

const supportedParams = pick(customProperties, SUPPORTED_CUSTOM_VALIDATION_FIELD_PARAMS);

const checkIfAllowed = isCustomValidationAllowed(params);

const customErrorMessages = [];
const fieldParamsWithNewValidation = mapValues(
supportedParams,
(customValidationValue, customValidationKey) => {
const originalValidation = params[customValidationKey];

const customValidation = isFunction(customValidationValue)
? customValidationValue(formValues, params)
: customValidationValue;

if (isObject(customValidation)) {
if (checkIfAllowed(customValidation[customValidationKey], customValidationKey)) {
customErrorMessages.push(pickXKey(customValidation, 'errorMessage'));

return customValidation[customValidationKey];
}

return originalValidation;
}

return checkIfAllowed(customValidation, customValidationKey)
? customValidation
: originalValidation;
}
);

const errorMessage = Object.assign({ ...params.errorMessage }, ...customErrorMessages);

return {
...params,
...fieldParamsWithNewValidation,
type: presentation?.inputType || params.inputType,
errorMessage,
required: isRequired,
schema: buildYupSchema({
...params,
...fieldParamsWithNewValidation,
errorMessage,
required: isRequired,
}),
};
};
}
Loading

0 comments on commit 6db2f3a

Please sign in to comment.