-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
f5460c6
commit 6db2f3a
Showing
26 changed files
with
8,597 additions
and
40 deletions.
There are no files selected for viewing
Binary file not shown.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
v18.14.0 |
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/)_ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/", | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}), | ||
}; | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | ||
}), | ||
}; | ||
}; | ||
} |
Oops, something went wrong.