Merge pull request #3707 from Tanddant:main

New sample - custom form builder
This commit is contained in:
Hugo Bernier 2023-05-16 18:00:29 -04:00 committed by GitHub
commit 9c5d98c330
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
44 changed files with 63608 additions and 0 deletions

6
samples/package-lock.json generated Normal file
View File

@ -0,0 +1,6 @@
{
"name": "samples",
"lockfileVersion": 2,
"requires": true,
"packages": {}
}

View File

@ -0,0 +1,39 @@
// For more information on how to run this SPFx project in a VS Code Remote Container, please visit https://aka.ms/spfx-devcontainer
{
"name": "SPFx 1.17.1",
"image": "docker.io/m365pnp/spfx:1.17.1",
// Set *default* container specific settings.json values on container create.
"settings": {},
// Add the IDs of extensions you want installed when the container is created.
"extensions": [
"editorconfig.editorconfig",
"dbaeumer.vscode-eslint"
],
// Use 'forwardPorts' to make a list of ports inside the container available locally.
"forwardPorts": [
4321,
35729
],
"portsAttributes": {
"4321": {
"protocol": "https",
"label": "Manifest",
"onAutoForward": "silent",
"requireLocalPort": true
},
// Not needed for SPFx>= 1.12.1
// "5432": {
// "protocol": "https",
// "label": "Workbench",
// "onAutoForward": "silent"
// },
"35729": {
"protocol": "https",
"label": "LiveReload",
"onAutoForward": "silent",
"requireLocalPort": true
}
},
"postCreateCommand": "bash .devcontainer/spfx-startup.sh",
"remoteUser": "node"
}

View File

@ -0,0 +1,33 @@
echo
echo -e "\e[1;94mInstalling Node dependencies\e[0m"
npm install
## commands to create dev certificate and copy it to the root folder of the project
echo
echo -e "\e[1;94mGenerating dev certificate\e[0m"
gulp trust-dev-cert
# Convert the generated PEM certificate to a CER certificate
openssl x509 -inform PEM -in ~/.rushstack/rushstack-serve.pem -outform DER -out ./spfx-dev-cert.cer
# Copy the PEM ecrtificate for non-Windows hosts
cp ~/.rushstack/rushstack-serve.pem ./spfx-dev-cert.pem
## add *.cer to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.cer' ./.gitignore
then
echo "# .CER Certificates" >> .gitignore
echo "*.cer" >> .gitignore
fi
## add *.pem to .gitignore to prevent certificates from being saved in repo
if ! grep -Fxq '*.pem' ./.gitignore
then
echo "# .PEM Certificates" >> .gitignore
echo "*.pem" >> .gitignore
fi
echo
echo -e "\e[1;92mReady!\e[0m"
echo -e "\n\e[1;94m**********\nOptional: if you plan on using gulp serve, don't forget to add the container certificate to your local machine. Please visit https://aka.ms/spfx-devcontainer for more information\n**********"

View File

@ -0,0 +1,352 @@
require('@rushstack/eslint-config/patch/modern-module-resolution');
module.exports = {
extends: ['@microsoft/eslint-config-spfx/lib/profiles/react'],
parserOptions: { tsconfigRootDir: __dirname },
overrides: [
{
files: ['*.ts', '*.tsx'],
parser: '@typescript-eslint/parser',
'parserOptions': {
'project': './tsconfig.json',
'ecmaVersion': 2018,
'sourceType': 'module'
},
rules: {
// Prevent usage of the JavaScript null value, while allowing code to access existing APIs that may require null. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/no-new-null': 1,
// Require Jest module mocking APIs to be called before any other statements in their code block. https://www.npmjs.com/package/@rushstack/eslint-plugin
'@rushstack/hoist-jest-mock': 1,
// Require regular expressions to be constructed from string constants rather than dynamically building strings at runtime. https://www.npmjs.com/package/@rushstack/eslint-plugin-security
'@rushstack/security/no-unsafe-regexp': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/adjacent-overload-signatures': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// CONFIGURATION: By default, these are banned: String, Boolean, Number, Object, Symbol
'@typescript-eslint/ban-types': [
1,
{
'extendDefaults': false,
'types': {
'String': {
'message': 'Use \'string\' instead',
'fixWith': 'string'
},
'Boolean': {
'message': 'Use \'boolean\' instead',
'fixWith': 'boolean'
},
'Number': {
'message': 'Use \'number\' instead',
'fixWith': 'number'
},
'Object': {
'message': 'Use \'object\' instead, or else define a proper TypeScript type:'
},
'Symbol': {
'message': 'Use \'symbol\' instead',
'fixWith': 'symbol'
},
'Function': {
'message': 'The \'Function\' type accepts any function-like value.\nIt provides no type safety when calling the function, which can be a common source of bugs.\nIt also accepts things like class declarations, which will throw at runtime as they will not be called with \'new\'.\nIf you are expecting the function to accept certain arguments, you should explicitly define the function shape.'
}
}
}
],
// RATIONALE: Code is more readable when the type of every variable is immediately obvious.
// Even if the compiler may be able to infer a type, this inference will be unavailable
// to a person who is reviewing a GitHub diff. This rule makes writing code harder,
// but writing code is a much less important activity than reading it.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/explicit-function-return-type': [
1,
{
'allowExpressions': true,
'allowTypedFunctionExpressions': true,
'allowHigherOrderFunctions': false
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: although this is a recommended rule, it is up to dev to select coding style.
// Set to 1 (warning) or 2 (error) to enable.
'@typescript-eslint/explicit-member-accessibility': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-array-constructor': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
//
// RATIONALE: The "any" keyword disables static type checking, the main benefit of using TypeScript.
// This rule should be suppressed only in very special cases such as JSON.stringify()
// where the type really can be anything. Even if the type is flexible, another type
// may be more appropriate such as "unknown", "{}", or "Record<k,V>".
'@typescript-eslint/no-explicit-any': 1,
// RATIONALE: The #1 rule of promises is that every promise chain must be terminated by a catch()
// handler. Thus wherever a Promise arises, the code must either append a catch handler,
// or else return the object to a caller (who assumes this responsibility). Unterminated
// promise chains are a serious issue. Besides causing errors to be silently ignored,
// they can also cause a NodeJS process to terminate unexpectedly.
'@typescript-eslint/no-floating-promises': 2,
// RATIONALE: Catches a common coding mistake.
'@typescript-eslint/no-for-in-array': 2,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-misused-new': 2,
// RATIONALE: The "namespace" keyword is not recommended for organizing code because JavaScript lacks
// a "using" statement to traverse namespaces. Nested namespaces prevent certain bundler
// optimizations. If you are declaring loose functions/variables, it's better to make them
// static members of a class, since classes support property getters and their private
// members are accessible by unit tests. Also, the exercise of choosing a meaningful
// class name tends to produce more discoverable APIs: for example, search+replacing
// the function "reverse()" is likely to return many false matches, whereas if we always
// write "Text.reverse()" is more unique. For large scale organization, it's recommended
// to decompose your code into separate NPM packages, which ensures that component
// dependencies are tracked more conscientiously.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-namespace': [
1,
{
'allowDeclarations': false,
'allowDefinitionFiles': false
}
],
// RATIONALE: Parameter properties provide a shorthand such as "constructor(public title: string)"
// that avoids the effort of declaring "title" as a field. This TypeScript feature makes
// code easier to write, but arguably sacrifices readability: In the notes for
// "@typescript-eslint/member-ordering" we pointed out that fields are central to
// a class's design, so we wouldn't want to bury them in a constructor signature
// just to save some typing.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/parameter-properties': 0,
// RATIONALE: When left in shipping code, unused variables often indicate a mistake. Dead code
// may impact performance.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-unused-vars': [
0,
{
'vars': 'all',
// Unused function arguments often indicate a mistake in JavaScript code. However in TypeScript code,
// the compiler catches most of those mistakes, and unused arguments are fairly common for type signatures
// that are overriding a base class method or implementing an interface.
'args': 'none'
}
],
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/no-use-before-define': [
2,
{
'functions': false,
'classes': true,
'variables': true,
'enums': true,
'typedefs': true
}
],
// Disallows require statements except in import statements.
// In other words, the use of forms such as var foo = require("foo") are banned. Instead use ES6 style imports or import foo = require("foo") imports.
'@typescript-eslint/no-var-requires': 'error',
// RATIONALE: The "module" keyword is deprecated except when describing legacy libraries.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'@typescript-eslint/prefer-namespace-keyword': 1,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: it's up to developer to decide if he wants to add type annotations
// Set to 1 (warning) or 2 (error) to enable the rule
'@typescript-eslint/no-inferrable-types': 0,
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
// Rationale to disable: declaration of empty interfaces may be helpful for generic types scenarios
'@typescript-eslint/no-empty-interface': 0,
// RATIONALE: This rule warns if setters are defined without getters, which is probably a mistake.
'accessor-pairs': 1,
// RATIONALE: In TypeScript, if you write x["y"] instead of x.y, it disables type checking.
'dot-notation': [
1,
{
'allowPattern': '^_'
}
],
// RATIONALE: Catches code that is likely to be incorrect
'eqeqeq': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'for-direction': 1,
// RATIONALE: Catches a common coding mistake.
'guard-for-in': 2,
// RATIONALE: If you have more than 2,000 lines in a single source file, it's probably time
// to split up your code.
'max-lines': ['warn', { max: 2000 }],
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-async-promise-executor': 2,
// RATIONALE: Deprecated language feature.
'no-caller': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-compare-neg-zero': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-cond-assign': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-constant-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-control-regex': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-debugger': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-delete-var': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-duplicate-case': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-character-class': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-empty-pattern': 1,
// RATIONALE: Eval is a security concern and a performance concern.
'no-eval': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-ex-assign': 2,
// RATIONALE: System types are global and should not be tampered with in a scalable code base.
// If two different libraries (or two versions of the same library) both try to modify
// a type, only one of them can win. Polyfills are acceptable because they implement
// a standardized interoperable contract, but polyfills are generally coded in plain
// JavaScript.
'no-extend-native': 1,
// Disallow unnecessary labels
'no-extra-label': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-fallthrough': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-func-assign': 1,
// RATIONALE: Catches a common coding mistake.
'no-implied-eval': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-invalid-regexp': 2,
// RATIONALE: Catches a common coding mistake.
'no-label-var': 2,
// RATIONALE: Eliminates redundant code.
'no-lone-blocks': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-misleading-character-class': 2,
// RATIONALE: Catches a common coding mistake.
'no-multi-str': 2,
// RATIONALE: It's generally a bad practice to call "new Thing()" without assigning the result to
// a variable. Either it's part of an awkward expression like "(new Thing()).doSomething()",
// or else implies that the constructor is doing nontrivial computations, which is often
// a poor class design.
'no-new': 1,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-func': 2,
// RATIONALE: Obsolete language feature that is deprecated.
'no-new-object': 2,
// RATIONALE: Obsolete notation.
'no-new-wrappers': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-octal': 2,
// RATIONALE: Catches code that is likely to be incorrect
'no-octal-escape': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-regex-spaces': 2,
// RATIONALE: Catches a common coding mistake.
'no-return-assign': 2,
// RATIONALE: Security risk.
'no-script-url': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-self-assign': 2,
// RATIONALE: Catches a common coding mistake.
'no-self-compare': 2,
// RATIONALE: This avoids statements such as "while (a = next(), a && a.length);" that use
// commas to create compound expressions. In general code is more readable if each
// step is split onto a separate line. This also makes it easier to set breakpoints
// in the debugger.
'no-sequences': 1,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-shadow-restricted-names': 2,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-sparse-arrays': 2,
// RATIONALE: Although in theory JavaScript allows any possible data type to be thrown as an exception,
// such flexibility adds pointless complexity, by requiring every catch block to test
// the type of the object that it receives. Whereas if catch blocks can always assume
// that their object implements the "Error" contract, then the code is simpler, and
// we generally get useful additional information like a call stack.
'no-throw-literal': 2,
// RATIONALE: Catches a common coding mistake.
'no-unmodified-loop-condition': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unsafe-finally': 2,
// RATIONALE: Catches a common coding mistake.
'no-unused-expressions': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-unused-labels': 1,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-useless-catch': 1,
// RATIONALE: Avoids a potential performance problem.
'no-useless-concat': 1,
// RATIONALE: The "var" keyword is deprecated because of its confusing "hoisting" behavior.
// Always use "let" or "const" instead.
//
// STANDARDIZED BY: @typescript-eslint\eslint-plugin\dist\configs\recommended.json
'no-var': 2,
// RATIONALE: Generally not needed in modern code.
'no-void': 1,
// RATIONALE: Obsolete language feature that is deprecated.
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'no-with': 2,
// RATIONALE: Makes logic easier to understand, since constants always have a known value
// @typescript-eslint\eslint-plugin\dist\configs\eslint-recommended.js
'prefer-const': 1,
// RATIONALE: Catches a common coding mistake where "resolve" and "reject" are confused.
'promise/param-names': 2,
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-atomic-updates': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'require-yield': 1,
// "Use strict" is redundant when using the TypeScript compiler.
'strict': [
2,
'never'
],
// RATIONALE: Catches code that is likely to be incorrect
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
'use-isnan': 2,
// STANDARDIZED BY: eslint\conf\eslint-recommended.js
// Set to 1 (warning) or 2 (error) to enable.
// Rationale to disable: !!{}
'no-extra-boolean-cast': 0,
// ====================================================================
// @microsoft/eslint-plugin-spfx
// ====================================================================
'@microsoft/spfx/import-requires-chunk-name': 1,
'@microsoft/spfx/no-require-ensure': 2,
'@microsoft/spfx/pair-react-dom-render-unmount': 1
}
},
{
// For unit tests, we can be a little bit less strict. The settings below revise the
// defaults specified in the extended configurations, as well as above.
files: [
// Test files
'*.test.ts',
'*.test.tsx',
'*.spec.ts',
'*.spec.tsx',
// Facebook convention
'**/__mocks__/*.ts',
'**/__mocks__/*.tsx',
'**/__tests__/*.ts',
'**/__tests__/*.tsx',
// Microsoft convention
'**/test/*.ts',
'**/test/*.tsx'
],
rules: {}
}
]
};

34
samples/react-json-form/.gitignore vendored Normal file
View File

@ -0,0 +1,34 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
release
solution
temp
*.sppkg
.heft
# Coverage directory used by tools like istanbul
coverage
# OSX
.DS_Store
# Visual Studio files
.ntvs_analysis.dat
.vs
bin
obj
# Resx Generated Code
*.resx.ts
# Styles Generated Code
*.scss.ts

View File

@ -0,0 +1,16 @@
!dist
config
gulpfile.js
release
src
temp
tsconfig.json
tslint.json
*.log
.yo-rc.json
.vscode

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "16.20.0",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.9.1"
},
"version": "1.17.1",
"libraryName": "react-json-form",
"libraryId": "a2797e03-2117-49f4-8b08-15bdf177d07b",
"environment": "spo",
"packageManager": "npm",
"solutionName": "react-json-form",
"solutionShortDescription": "react-json-form description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,109 @@
# JSON Form builder
## Summary
Let's the user build a form and receive responses in the form
![Sample gif](./assets/Demo.gif)
## Compatibility
| :warning: Important |
|:---------------------------|
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
This sample is optimally compatible with the following environment configuration:
![SPFx 1.17.1](https://img.shields.io/badge/SPFx-1.17.1-green.svg)
![Node.js v16](https://img.shields.io/badge/Node.js-v16-green.svg)
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Not%20Tested-yellow.svg)
For more information about SPFx compatibility, please refer to https://aka.ms/spfx-matrix
## Applies to
* [SharePoint Framework](https://learn.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Microsoft 365 tenant](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment)
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/m365devprogram)
## Contributors
* [Dan Toft](https://github.com/Tanddant)
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0 | March 16, 2023 | Initial release |
## Prerequisites
You'll need a document library to store the responses
## Minimal path to awesome
* Clone this repository (or [download this solution as a .ZIP file](https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-json-form) then unzip it)
* From your command line, change your current directory to the directory containing this sample (`react-json-form`, located under `samples`)
* in the command line run:
* `npm install`
* `gulp serve`
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit <https://aka.ms/spfx-devcontainer> for further instructions.
## Features
> PLEASE DON'T ACTUALLY USE THIS IN IT'S CURRENT STATE!
>
> The way this is setup to save it to save a .json file in a document library containing both the forms config and the values, this is a very unstructured method of storing data! - you really should implement another save method!
---
You have the option to edit the raw JSON in the property pane, from here you'll also set the document library where the JSON files are stored
![property pane](assets/Raw%20JSON.png)
---
Another feature is conditional fields (only for some of the field types)
It allows you to show/hide fields based on other fields, for instance a "fill in" choice option!
![conditional fields](assets/Conditional%20field.gif)
---
Lastly of the field types I'll call out here is the "Group" field this allows you to 'group' fields in either direction (is also a way to add several fields side a conditional field)
![Group fields](assets/Group%20field.gif)
## Help
We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3A%22sample%3A%20react-json-form%22) to see if anybody else is having the same issues.
You can also try looking at [discussions related to this sample](https://github.com/pnp/sp-dev-fx-webparts/discussions?discussions_q=react-json-form) and see what the community is saying.
If you encounter any issues using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-json-form&template=bug-report.yml&sample=react-json-form&authors=@Tanddant&title=react-json-form%20-%20).
For questions regarding this sample, [create a new question](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aquestion%2Csample%3A%20react-json-form&template=question.yml&sample=react-json-form&authors=@Tanddant&title=react-json-form%20-%20).
Finally, if you have an idea for improvement, [make a suggestion](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Aenhancement%2Csample%3A%20react-json-form&template=suggestion.yml&sample=react-json-form&authors=@Tanddant&title=react-json-form%20-%20).
## Disclaimer
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
<img src="https://m365-visitor-stats.azurewebsites.net/sp-dev-fx-webparts/samples/react-json-form" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 869 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 790 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 122 KiB

View File

@ -0,0 +1,50 @@
[
{
"name": "pnp-sp-dev-spfx-web-parts-react-json-form",
"source": "pnp",
"title": "Json form builder",
"shortDescription": "Build a custom form with ease",
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-json-form",
"downloadUrl": "https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-json-form",
"longDescription": [
"Really easy way for the users to build and use a custom form without having to worry about having to setup a SharePoint list, instead stores the data directly in a document library"
],
"creationDateTime": "2023-05-16",
"updateDateTime": "2023-05-16",
"products": [
"SharePoint"
],
"metadata": [
{
"key": "CLIENT-SIDE-DEV",
"value": "React"
},
{
"key": "SPFX-VERSION",
"value": "1.17.1"
}
],
"thumbnails": [
{
"type": "image",
"order": 100,
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-caml2table/assets/Demo.gif",
"alt": "Web Part Preview"
}
],
"authors": [
{
"gitHubAccount": "Tanddant",
"pictureUrl": "https://github.com/Tanddant.png",
"name": "Dan Toft"
}
],
"references": [
{
"name": "Build your first SharePoint client-side web part",
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
"url": "https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
}
]
}
]

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"json-form-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/jsonForm/JsonFormWebPart.js",
"manifest": "./src/webparts/jsonForm/JsonFormWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"JsonFormWebPartStrings": "lib/webparts/jsonForm/loc/{locale}.js",
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/lib/loc/{locale}.js",
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js"
}
}

View File

@ -0,0 +1,7 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/deploy-azure-storage.schema.json",
"workingDir": "./release/assets/",
"account": "<!-- STORAGE ACCOUNT NAME -->",
"container": "react-json-form",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,40 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-json-form-client-side-solution",
"id": "a2797e03-2117-49f4-8b08-15bdf177d07b",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.17.1"
},
"metadata": {
"shortDescription": {
"default": "react-json-form description"
},
"longDescription": {
"default": "react-json-form description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-json-form Feature",
"description": "The feature that activates elements of the react-json-form solution.",
"id": "e7493266-8fe1-4b0e-a232-5b1454fd820d",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/react-json-form.sppkg"
}
}

View File

@ -0,0 +1,3 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
"port": 4321,
"https": true,
"initialPage": "https://{tenantDomain}/_layouts/workbench.aspx"
}

View File

@ -0,0 +1,4 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
"cdnBasePath": "<!-- PATH TO CDN -->"
}

16
samples/react-json-form/gulpfile.js vendored Normal file
View File

@ -0,0 +1,16 @@
'use strict';
const build = require('@microsoft/sp-build-web');
build.addSuppression(`Warning - [sass] The local CSS class 'ms-Grid' is not camelCase and will not be type-safe.`);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
build.initialize(require('gulp'));

61932
samples/react-json-form/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,46 @@
{
"name": "react-json-form",
"version": "0.0.1",
"private": true,
"engines": {
"node": ">=16.13.0 <17.0.0"
},
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@fluentui/react": "^8.108.2",
"@microsoft/sp-core-library": "1.17.1",
"@microsoft/sp-lodash-subset": "1.17.1",
"@microsoft/sp-office-ui-fabric-core": "1.17.1",
"@microsoft/sp-property-pane": "1.17.1",
"@microsoft/sp-webpart-base": "1.17.1",
"@pnp/graph": "^3.14.0",
"@pnp/sp": "^3.14.0",
"@pnp/spfx-controls-react": "^3.14.0",
"@pnp/spfx-property-controls": "^3.13.0",
"office-ui-fabric-react": "^7.199.1",
"react": "17.0.1",
"react-dom": "17.0.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.17.1",
"@microsoft/eslint-plugin-spfx": "1.17.1",
"@microsoft/rush-stack-compiler-4.5": "0.4.0",
"@microsoft/sp-build-web": "1.17.1",
"@microsoft/sp-module-interfaces": "1.17.1",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "17.0.45",
"@types/react-dom": "17.0.17",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint": "8.7.0",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.5.5"
}
}

View File

@ -0,0 +1,10 @@
import { useState } from 'react';
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export default function useObject<T>(InitialValue?: T) {
const [value, setValue] = useState<T>(InitialValue ?? {} as T);
const updateValue: (Updates: Partial<T>) => void = (Updates: Partial<T>) => setValue((prev) => ({ ...prev, ...Updates }))
return {
value, updateValue, overwriteData: setValue
};
}

View File

@ -0,0 +1,6 @@
import { IChoiceField, IConditionalField, IField, IGroupField } from "./FormField";
export interface IForm {
Title: string;
Fields: (IField | IChoiceField | IGroupField | IConditionalField)[];
}

View File

@ -0,0 +1,44 @@
export enum FieldType {
Text = "Text",
MultilineText = "MultilineText",
Number = "Number",
Boolean = "Boolean",
Choice = "Choice",
MultiChoice = "MultiChoice",
FieldGroup = "FieldGroup",
PlaceHolder = "PlaceHolder",
Label = "Label",
Conditional = "Conditional",
Header = "Header"
}
export interface IField {
Id: string;
DisplayName?: string;
Type: FieldType;
}
export interface IChoiceField extends IField {
Options: string[]
}
export interface IConditionalField extends IField {
LookupFieldId: string;
MatchValue: string | number | boolean;
Field: IField;
}
export enum GroupDirection {
Vertical,
Horizontal
}
export interface IGroupField extends IField {
Fields: (IField | IChoiceField | IGroupField | IConditionalField)[]
Direction: GroupDirection;
}
export interface IForm {
Title: string;
Fields: (IField | IChoiceField | IGroupField | IConditionalField)[];
}

View File

@ -0,0 +1,7 @@
import { IForm } from "./Form";
export interface SaveObject {
form: IForm;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
response: any;
}

View File

@ -0,0 +1,30 @@
import { BaseComponentContext } from "@microsoft/sp-component-base"
import { SaveObject } from "../Models/SaveObject";
import { SPFI, SPFx, spfi } from '@pnp/sp/presets/all'
export interface IDataProvider {
SaveSubmission: (Submission: SaveObject) => Promise<string>;
GetSubmission: (ServerRelativeUrl: string) => Promise<SaveObject>;
}
export class SharePointProvider implements IDataProvider {
private SP: SPFI;
private LIST_ID: string;
constructor(context: BaseComponentContext, ListID: string) {
this.SP = spfi().using(SPFx(context));
this.LIST_ID = ListID;
}
public async SaveSubmission(Submission: SaveObject): Promise<string> {
const item = await this.SP.web.lists.getById(this.LIST_ID).rootFolder.files.addUsingPath(`${new Date().getTime()}.json`, JSON.stringify(Submission, null, 2))
return item.data.ServerRelativeUrl;
}
public async GetSubmission(ServerRelativeUrl: string): Promise<SaveObject> {
const form = await this.SP.web.getFileByServerRelativePath(ServerRelativeUrl).getText();
return JSON.parse(form);
}
}

View File

@ -0,0 +1,31 @@
import { FieldType, IConditionalField, IField, IGroupField } from "../Models/FormField";
export const generateGuid: () => string = () => {
return Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);
}
export const NewField: () => IField = () => ({ Id: generateGuid(), Type: FieldType.PlaceHolder } as IField)
const UNSUPPORTED_LOOKUP_FIELDTYPES: FieldType[] = [FieldType.PlaceHolder, FieldType.MultiChoice, FieldType.PlaceHolder, FieldType.Label];
export const GetLookupFields: (Fields: IField[]) => IField[] = (Fields: IField[]) => {
const arr: IField[] = [];
for (const field of Fields) {
if (field.Type === FieldType.FieldGroup) {
arr.push(...GetLookupFields((field as IGroupField).Fields))
} else if (field.Type === FieldType.Conditional) {
if ((field as IConditionalField).Field.Type === FieldType.FieldGroup) {
arr.push(...GetLookupFields(((field as IConditionalField).Field as IGroupField).Fields))
} else {
arr.push((field as IConditionalField).Field);
}
} else {
arr.push(field);
}
}
return arr.filter(x => x.DisplayName !== null && !UNSUPPORTED_LOOKUP_FIELDTYPES.some(bannedType => bannedType === x.Type));
}

View File

@ -0,0 +1 @@
// A file is required to be in the root of the /src directory by the TypeScript compiler

View File

@ -0,0 +1,25 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "b71c2906-03f0-46a6-8efe-f7afe1cade2f",
"alias": "JsonFormWebPart",
"componentType": "WebPart",
"version": "*",
"manifestVersion": 2,
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70",
"group": { "default": "Advanced" },
"title": { "default": "JSON Form" },
"description": { "default": "JSON Form description" },
"officeFabricIconFontName": "Page",
"properties": {
"formJson": "{\"Title\":\"My Form\",\"Fields\":[]}"
}
}]
}

View File

@ -0,0 +1,98 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
} from '@microsoft/sp-property-pane';
import { BaseComponentContext } from '@microsoft/sp-component-base';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { PropertyFieldCodeEditor, PropertyFieldCodeEditorLanguages } from '@pnp/spfx-property-controls/lib/PropertyFieldCodeEditor';
import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldListPicker';
import { IJsonFormProps, JsonForm } from './components/JsonForm';
import { IForm } from '../../Models/Form';
import { IDataProvider, SharePointProvider } from '../../Providers/SharePointProvider';
export interface IJsonFormWebPartProps {
formJson: string;
listId: string;
}
export interface AppContext {
context: BaseComponentContext;
provider: IDataProvider;
}
export const SPFxContext = React.createContext<AppContext>(null);
const urlSearchParams = new URLSearchParams(window.location.search);
export const FILLED_FORM_QUERY_KEY = "FormServerRelativeUrl";
export default class JsonFormWebPart extends BaseClientSideWebPart<IJsonFormWebPartProps> {
public render(): void {
const element: React.ReactElement = React.createElement(
SPFxContext.Provider,
{
value: {
context: this.context,
provider: new SharePointProvider(this.context, this.properties.listId)
} as AppContext
},
React.createElement<IJsonFormProps>(
JsonForm,
{
Form: JSON.parse(this.properties.formJson),
// eslint-disable-next-line no-return-assign
SaveForm: (updated: IForm) => this.properties.formJson = JSON.stringify({ ...JSON.parse(this.properties.formJson), ...updated }, null, 2),
Mode: this.displayMode,
ListId: this.properties.listId,
ServerRelativeUrl: urlSearchParams.has(FILLED_FORM_QUERY_KEY) ? urlSearchParams.get(FILLED_FORM_QUERY_KEY) : null,
}
)
);
ReactDom.render(element, this.domElement);
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
groups: [
{
groupName: "Settings",
groupFields: [
PropertyFieldCodeEditor('formJson', {
key: "formJson",
label: "Raw JSON",
panelTitle: "Edit JSON",
initialValue: this.properties.formJson,
onPropertyChange: (path, old, newval) => this.onPropertyPaneFieldChanged(path, old, newval),
properties: this.properties,
language: PropertyFieldCodeEditorLanguages.JSON,
}),
PropertyFieldListPicker('listId', {
context: this.context,
label: "Select a list to store the data",
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
baseTemplate: 101,
includeHidden: false,
orderBy: PropertyFieldListPickerOrderBy.Title,
key: "listId"
})
]
}
]
}
]
};
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

View File

@ -0,0 +1,97 @@
import * as React from 'react';
import { FieldType, GroupDirection, IChoiceField, IConditionalField, IField, IGroupField } from '../../../../Models/FormField';
import { Position, SpinButton, TextField, Checkbox, Dropdown, MessageBar, MessageBarType, Text } from '@fluentui/react';
import { Label } from 'office-ui-fabric-react';
export interface IFieldProps {
onChange: (updates: object) => void;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
form: any;
field: IField;
readonly: boolean;
}
export const Field: React.FunctionComponent<IFieldProps> = (props: React.PropsWithChildren<IFieldProps>) => {
const { field, onChange, form, readonly } = props;
switch (field.Type) {
case FieldType.Label: return <Label>{field.DisplayName}</Label>;
case FieldType.Header: return <Text variant='xLarge'>{field.DisplayName}</Text>;
case FieldType.Text: return <TextField
value={form[field.Id] ?? ""}
label={field.DisplayName}
readOnly={readonly}
onChange={(_, val) => onChange({ [field.Id]: val })}
/>;
case FieldType.MultilineText: return <TextField
value={form[field.Id] ?? ""}
label={field.DisplayName}
rows={5}
multiline
readOnly={readonly}
onChange={(_, val) => onChange({ [field.Id]: val })}
/>;
case FieldType.Number: return <SpinButton
inputMode='numeric'
labelPosition={Position.top}
value={form[field.Id] ?? ""}
label={field.DisplayName}
onChange={readonly ? null : (_, val) => onChange({ [field.Id]: Number(val) })}
/>;
case FieldType.Boolean: return <Checkbox
label={field.DisplayName}
checked={form[field.Id] ?? false}
onChange={readonly ? () => null : (_, val) => onChange({ [field.Id]: val })}
styles={{ root: { alignItems: 'center', marginTop: "1.75em" } }}
/>;
case FieldType.Choice: return <Dropdown
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options={(field as any as IChoiceField).Options.map(x => ({ key: x, text: x }))}
selectedKey={form[field.Id] ?? ""}
label={field.DisplayName}
onChange={readonly ? null : (_, option) => onChange({ [field.Id]: option.key })}
/>
case FieldType.MultiChoice: return <Dropdown
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options={(field as any as IChoiceField).Options.map(x => ({ key: x, text: x }))}
selectedKeys={form[field.Id] ?? []}
label={field.DisplayName}
multiSelect
onChange={readonly ? null : (_, val) => {
let selected: string[] = form[field.Id] ?? [];
selected = val.selected ? [...selected, val.key as string] : selected.filter(x => x !== val.key);
onChange({ [field.Id]: selected })
}}
/>
case FieldType.FieldGroup: return <div>
{(field.DisplayName !== null || field.DisplayName !== "") && <Label>{field.DisplayName}</Label>}
<div
style={{
display: "grid",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
gridTemplateColumns: (field as IGroupField).Direction === GroupDirection.Horizontal ? `repeat(auto-fill,minmax(calc(${100 / (field as any as IGroupField).Fields.length}% - 10px),1fr))` : '',
gap: 10
}}>
{(field as IGroupField).Fields.map((f, index) => <Field {...props} field={f} key={index} />)}
</div>
</div>;
case FieldType.Conditional: {
const f = (field as IConditionalField);
const visible = form[f.LookupFieldId] === f.MatchValue
if (!visible) return <></>
return <Field readonly={readonly} field={f.Field} form={form} onChange={onChange} />
}
}
return <MessageBar messageBarType={MessageBarType.error} styles={{ root: { marginTop: "1.75em" } }}>Field not configured</MessageBar>
};

View File

@ -0,0 +1,189 @@
/* eslint-disable @typescript-eslint/no-use-before-define */
import * as React from 'react';
import { FieldType, GroupDirection, IChoiceField, IConditionalField, IField, IGroupField } from '../../../../Models/FormField';
import { ActionButton, ChoiceGroup, DefaultButton, Dialog, DialogFooter, Dropdown, Label, Position, PrimaryButton, SpinButton, Stack, TextField } from '@fluentui/react';
import useObject from '../../../../Hooks/UseObject';
import { NewField } from '../../../../Util/Util';
export interface IFieldEditorDialogProps {
field: IField;
update: (updates: Partial<IField | IChoiceField | IGroupField | IConditionalField>) => void;
cancel: () => void;
delete: () => void;
readonly allFieldsFlat: IField[];
}
export const FieldEditorDialog: React.FunctionComponent<IFieldEditorDialogProps> = (props: React.PropsWithChildren<IFieldEditorDialogProps>) => {
const { value: field, updateValue } = useObject<IField | IChoiceField | IGroupField | IConditionalField>(props.field);
return (
<Dialog
minWidth={500}
dialogContentProps={{ title: "Edit field" }}
hidden={false}
>
<Stack tokens={{ childrenGap: 5 }}>
<Dropdown
label='Field type'
options={[
{ key: FieldType.Header, text: "Header" },
{ key: FieldType.Text, text: "Single line of text" },
{ key: FieldType.MultilineText, text: "Multiple lines of text" },
{ key: FieldType.Number, text: "Number" },
{ key: FieldType.Boolean, text: "Checkbox (yes/no)" },
{ key: FieldType.Choice, text: "Choice" },
{ key: FieldType.MultiChoice, text: "Multi choice" },
{ key: FieldType.Label, text: "Label" },
{ key: FieldType.FieldGroup, text: "Group of fields" },
{ key: FieldType.Conditional, text: "Conditional field" },
]}
selectedKey={field.Type}
onChange={(_, val) => {
const t = val.key as FieldType;
const updates: Partial<IField | IChoiceField | IGroupField | IConditionalField> = { Type: t }
if (t === FieldType.Choice || t === FieldType.MultiChoice)
if ((field as IChoiceField).Options === null)
(updates as Partial<IChoiceField>).Options = [];
if (t === FieldType.Conditional)
if ((field as IConditionalField).Field === null)
(updates as Partial<IConditionalField>).Field = NewField();
if (t === FieldType.FieldGroup)
if ((field as IGroupField).Fields === null) {
(updates as Partial<IGroupField>).Fields = [];
(updates as Partial<IGroupField>).Direction = GroupDirection.Horizontal;
}
updateValue(updates);
}}
/>
{FieldType.Conditional !== field.Type && <TextField label='Title' value={field.DisplayName} onChange={(_, val) => updateValue({ DisplayName: val })} />}
{[FieldType.Choice, FieldType.MultiChoice].some(x => x === field.Type) && <ChoiceFieldOptions field={field as IChoiceField} updateValue={updateValue} />}
{FieldType.Conditional === field.Type && <ConditionalFieldOptions field={field as IConditionalField} updateValue={updateValue} allFieldsFlat={props.allFieldsFlat} />}
{FieldType.FieldGroup === field.Type && <GroupFieldOptions field={field as IGroupField} updateValue={updateValue} />}
<DialogFooter>
<PrimaryButton text='Delete' iconProps={{ iconName: 'delete' }} onClick={() => props.delete()} styles={{ root: { backgroundColor: "#FF0000" }, rootHovered: { backgroundColor: "#D10000" }, rootChecked: { backgroundColor: "#A30000" } }} />
<PrimaryButton text='Save' iconProps={{ iconName: 'Save' }} onClick={() => props.update(field)} />
<DefaultButton text='Cancel' onClick={() => props.cancel()} />
</DialogFooter>
</Stack>
</Dialog>
);
};
export interface IGroupFieldOptionsProps {
field: IGroupField;
updateValue: (updates: Partial<IGroupField>) => void;
}
export const GroupFieldOptions: React.FunctionComponent<IGroupFieldOptionsProps> = (props: React.PropsWithChildren<IGroupFieldOptionsProps>) => {
const { field, updateValue } = props;
return (
<>
<ChoiceGroup
label='Direction'
selectedKey={field.Direction}
options={[
// eslint-disable-next-line @typescript-eslint/no-explicit-any
{ key: GroupDirection.Horizontal as any as string, text: "Horizontal", iconProps: { iconName: "AlignVerticalCenter" } },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
{ key: GroupDirection.Vertical as any as string, text: "Vertical", iconProps: { iconName: "AlignHorizontalCenter" } }
]}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
onChange={(_, val) => updateValue({ Direction: val.key as any as GroupDirection })}
/>
</>
);
};
interface IChoiceFieldOptionsProps {
field: IChoiceField;
updateValue: (updates: Partial<IChoiceField>) => void;
}
const ChoiceFieldOptions: React.FunctionComponent<IChoiceFieldOptionsProps> = (props: React.PropsWithChildren<IChoiceFieldOptionsProps>) => {
const { field, updateValue } = props;
return (<>
<Label>Options</Label>
{(field as IChoiceField).Options.map((val, index) => {
return <div style={{ display: "flex" }} key={index}>
<TextField
styles={{ root: { flexGrow: 1 } }}
value={val} onChange={(_, val) => {
const options = [...(field as IChoiceField).Options]
options[index] = val
updateValue({ Options: options });
}} />
<ActionButton iconProps={{ iconName: "Delete" }} onClick={() => updateValue({ Options: (field as IChoiceField).Options.filter((_, i) => i !== index) })} />
</div>
})}
<PrimaryButton iconProps={{ iconName: "Add" }} text='Add option' onClick={() => {
updateValue({ Options: [...(field as IChoiceField).Options, ""] });
}} />
</>);
};
interface IConditionalFieldOptionsProps {
field: IConditionalField;
updateValue: (updates: Partial<IConditionalField>) => void;
allFieldsFlat: IField[]
}
const ConditionalFieldOptions: React.FunctionComponent<IConditionalFieldOptionsProps> = (props: React.PropsWithChildren<IConditionalFieldOptionsProps>) => {
const { allFieldsFlat, field, updateValue } = props
const targetField = allFieldsFlat.filter(x => x.Id === (field as IConditionalField).LookupFieldId)[0]
return (
<>
<Dropdown
label='Field to look at:'
options={props.allFieldsFlat.map(x => ({ text: x.DisplayName, key: x.Id }))}
selectedKey={((field as IConditionalField).LookupFieldId)}
onChange={(_, val) => updateValue({ LookupFieldId: val.key as string })}
/>
{targetField !== null &&
<>
{FieldType.Choice === targetField.Type && <Dropdown
label='Show if is equal to'
options={(targetField as IChoiceField).Options.map(x => ({ key: x, text: x }))}
selectedKey={(field as IConditionalField).MatchValue as string}
onChange={(_, val) => updateValue({ MatchValue: val.text })}
/>}
{FieldType.Boolean === targetField.Type && <Dropdown
label='Show if is equal to'
options={[{ key: true.toString(), text: "Yes" }, { key: false.toString(), text: "No" }]}
selectedKey={(field as IConditionalField).MatchValue?.toString()}
onChange={(_, val) => updateValue({ MatchValue: val.key === true.toString() })}
/>}
{FieldType.Number === targetField.Type && <SpinButton
label='Show if is equal to'
inputMode='numeric'
labelPosition={Position.top}
value={(field as IConditionalField).MatchValue as string}
onChange={(_, val) => updateValue({ MatchValue: Number(val) })}
/>
}
{[FieldType.Text, FieldType.MultilineText].some(x => x === targetField.Type) && <TextField
value={(field as IConditionalField).MatchValue as string}
label={"Value to look for"}
onChange={(_, val) => updateValue({ MatchValue: val })}
/>
}
</>
}
</>
);
};

View File

@ -0,0 +1,7 @@
.EditField {
cursor: pointer;
}
.EditField:hover {
filter: contrast(0.5);
}

View File

@ -0,0 +1,128 @@
import * as React from 'react';
import { FieldType, GroupDirection, IChoiceField, IConditionalField, IField, IGroupField } from '../../../../Models/FormField';
import { ActionButton, Checkbox, Dropdown, Label, MessageBar, MessageBarType, Position, PrimaryButton, SpinButton, Text, TextField, getTheme } from '@fluentui/react';
import { cloneDeep } from '@microsoft/sp-lodash-subset';
import { FieldEditorDialog } from './FieldEditorDialog';
import { NewField } from '../../../../Util/Util';
import styles from './FormFieldCustomizer.module.scss'
export interface IFormFieldCustomizer {
field: IField;
update: (updates: Partial<IField | IChoiceField | IGroupField | IConditionalField>) => void;
delete: () => void;
readonly allFieldsFlat: IField[];
}
const MAX_NUMBER_OF_ITEMS_IN_GROUP: number = 5;
export const FormFieldCustomizer: React.FunctionComponent<IFormFieldCustomizer> = (props: React.PropsWithChildren<IFormFieldCustomizer>) => {
const { field } = props;
const [shouldEdit, setShouldEdit] = React.useState<boolean>(false);
const editDialog = <FieldEditorDialog
allFieldsFlat={props.allFieldsFlat}
field={field}
update={(updates) => {
props.update(updates);
setShouldEdit(false)
}}
delete={() => {
props.delete();
setShouldEdit(false)
}}
cancel={() => setShouldEdit(false)}
/>
if (FieldType.FieldGroup === field.Type) {
const f = (field as IGroupField)
const AtCapacity = f.Fields.length === MAX_NUMBER_OF_ITEMS_IN_GROUP;
return <div>
{shouldEdit && editDialog}
<div style={{ display: "flex" }}>
{(f.DisplayName !== null || f.DisplayName !== "") && <Label disabled>{f.DisplayName}</Label>}
<ActionButton iconProps={{ iconName: "Edit" }} onClick={() => setShouldEdit(true)} />
<ActionButton iconProps={{ iconName: "Delete" }} onClick={() => props.delete()} />
</div>
<div
style={{
display: "grid",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
gridTemplateColumns: (field as IGroupField).Direction === GroupDirection.Horizontal ? `repeat(auto-fill,minmax(calc(${100 / ((field as any as IGroupField).Fields.length + (!AtCapacity ? 1 : 0))}% - 10px),1fr))` : '',
gap: 10
}}>
{f.Fields.map((child, index) => {
return <FormFieldCustomizer
key={child.Id}
allFieldsFlat={props.allFieldsFlat}
field={child}
delete={() => props.update({ Fields: (field as IGroupField).Fields.filter(x => x.Id !== child.Id) })}
update={(val) => {
const children = cloneDeep(f.Fields)
children[index] = { ...children[index], ...val };
props.update({ Fields: children });
}}
/>
})}
{!AtCapacity && <PrimaryButton styles={{ root: { alignSelf: "end" } }} iconProps={{ iconName: "Add" }} text='Add field' onClick={() => props.update({ Fields: [...f.Fields, NewField()] })} />}
</div>
</div>;
}
if (FieldType.Conditional === field.Type) {
const f = (field as IConditionalField);
const lookupField = props.allFieldsFlat.filter(x => x.Id === f.LookupFieldId)[0];
return <>
{shouldEdit && editDialog}
<div style={{ border: `1px solid ${getTheme().palette.themeDarkAlt}` }}>
<div style={{ display: "flex", background: getTheme().palette.themeLighter, alignItems: 'center', paddingLeft: "1em" }}>
<Label>Visible if &apos;{lookupField?.DisplayName}&apos; is equal to &apos;{f.MatchValue?.toString()}&apos;</Label>
<ActionButton iconProps={{ iconName: "Edit" }} onClick={() => setShouldEdit(true)} />
<ActionButton iconProps={{ iconName: "Delete" }} onClick={() => props.delete()} />
</div>
<div style={{ padding: 10 }}>
<FormFieldCustomizer
allFieldsFlat={props.allFieldsFlat}
field={f.Field}
delete={() => props.update({ Field: NewField() })}
update={(val) => props.update({ Field: { ...f.Field, ...val } })}
/>
</div>
</div >
</>;
}
const genericProps = {
styles: {
title: { cursor: "pointer" },
root: { cursor: "pointer" },
label: { cursor: "pointer" },
dropdown: { cursor: "pointer" },
dropdownOptionText: { cursor: "pointer" },
field: { cursor: "pointer" }
},
disabled: true,
label: field.DisplayName
}
return (
<span>
{shouldEdit && editDialog}
<div className={styles.EditField} onClick={() => setShouldEdit(true)}>
{FieldType.Label === field.Type && <Label styles={{ root: { cursor: "pointer" } }} disabled>{field.DisplayName}</Label>}
{FieldType.Header === field.Type && <Text variant='xLarge'>{field.DisplayName}</Text>}
{FieldType.Text === field.Type && <TextField {...genericProps} />}
{FieldType.MultilineText === field.Type && <TextField {...genericProps} rows={5} multiline />}
{FieldType.Number === field.Type && <SpinButton {...genericProps} inputMode='numeric' labelPosition={Position.top} />}
{FieldType.Boolean === field.Type && <Checkbox {...genericProps} styles={{ root: { marginTop: "2.5em" } }} />}
{FieldType.Choice === field.Type && <Dropdown {...genericProps} options={[]} />}
{FieldType.MultiChoice === field.Type && <Dropdown {...genericProps} options={[]} multiSelect />}
{FieldType.PlaceHolder === field.Type && <MessageBar messageBarType={MessageBarType.info} styles={{ root: { marginTop: "2.1em" } }}>Press here to setup the field!</MessageBar>}
</div>
</span>
);
};

View File

@ -0,0 +1,34 @@
@import '~@fluentui/react/dist/sass/References.scss';
.jsonForm {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.welcome {
text-align: center;
}
.welcomeImage {
width: 100%;
max-width: 420px;
}
.links {
a {
text-decoration: none;
color: "[theme:link, default:#03787c]";
color: var(--link); // note: CSS Custom Properties support is limited to modern browsers only
&:hover {
text-decoration: underline;
color: "[theme:linkHovered, default: #014446]";
color: var(--linkHovered); // note: CSS Custom Properties support is limited to modern browsers only
}
}
}

View File

@ -0,0 +1,98 @@
import * as React from 'react';
import useObject from '../../../Hooks/UseObject';
import { PrimaryButton, Stack, DialogFooter } from '@fluentui/react'
import { Field } from './Fields/Field';
import { DisplayMode } from '@microsoft/sp-core-library';
import { Placeholder, WebPartTitle } from '@pnp/spfx-controls-react';
import { FormFieldCustomizer } from './Fields/FormFieldCustomizer';
import { GetLookupFields, NewField } from '../../../Util/Util';
import { cloneDeep } from '@microsoft/sp-lodash-subset';
import { FILLED_FORM_QUERY_KEY, SPFxContext } from '../JsonFormWebPart';
import { IForm } from '../../../Models/Form';
export interface IJsonFormProps {
Form: IForm;
SaveForm: (updated: IForm) => void;
Mode: DisplayMode;
ServerRelativeUrl?: string;
ListId: string;
}
export const JsonForm: React.FunctionComponent<IJsonFormProps> = (props: React.PropsWithChildren<IJsonFormProps>) => {
const { Mode, ServerRelativeUrl } = props;
const { value: Form, updateValue: UpdateForm, overwriteData: __SETFORM } = useObject<IForm>(props.ServerRelativeUrl ? { Fields: [], Title: "" } : props.Form);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { value: filledForm, updateValue, overwriteData: __SETFILLEDFORM } = useObject<any>();
const { provider } = React.useContext(SPFxContext);
React.useEffect(() => {
if (ServerRelativeUrl !== null) {
const fetch = async (): Promise<void> => {
const result = await provider.GetSubmission(ServerRelativeUrl);
__SETFILLEDFORM(result.response);
__SETFORM(result.form);
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
fetch();
}
}, [])
const saveForm = async (): Promise<void> => {
const serverRelativeUrl = await provider.SaveSubmission({ form: Form, response: filledForm });
const searchParams = new URLSearchParams(window.location.search);
searchParams.set(FILLED_FORM_QUERY_KEY, serverRelativeUrl);
window.location.search = searchParams.toString();
}
if (props.ListId === null || props.ListId === "")
return <Placeholder description={'Open the property pane and select a list to store responses'} iconName={'Edit'} iconText={'Please configure web part'} />
return (
<>
<WebPartTitle displayMode={Mode} title={Form.Title} updateProperty={(val) => UpdateForm({ Title: val })} />
{Mode === DisplayMode.Read &&
<>
<Stack tokens={{ childrenGap: 5 }}>
{Form.Fields.map((field, index) => {
return <Field readonly={props.ServerRelativeUrl !== null} field={field} onChange={updateValue} form={filledForm} key={index} />
})}
</Stack>
{props.ServerRelativeUrl === null &&
<DialogFooter>
<PrimaryButton text='Submit' iconProps={{ iconName: "Accept" }} onClick={() => saveForm()} />
</DialogFooter>
}
</>
}
{Mode === DisplayMode.Edit &&
<>
<Stack tokens={{ childrenGap: 5 }}>
{Form.Fields.map((Field, index) => {
return <FormFieldCustomizer
key={index}
allFieldsFlat={GetLookupFields(Form.Fields)}
field={Field}
delete={() => {
const fields = cloneDeep(Form.Fields).filter((x, i) => index !== i);
UpdateForm({ Fields: fields });
}}
update={(val) => {
const fields = cloneDeep(Form.Fields)
fields[index] = { ...fields[index], ...val };
UpdateForm({ Fields: fields });
}}
/>
})}
<PrimaryButton iconProps={{ iconName: "Add" }} text='Add field' onClick={() => UpdateForm({ Fields: [...Form.Fields, NewField()] })} />
</Stack>
<DialogFooter>
<PrimaryButton text='Save form' iconProps={{ iconName: "save" }} onClick={() => props.SaveForm(Form)} />
</DialogFooter>
</>
}
</>
);
};

View File

@ -0,0 +1,15 @@
define([], function() {
return {
"PropertyPaneDescription": "Description",
"BasicGroupName": "Group Name",
"DescriptionFieldLabel": "Description Field",
"AppLocalEnvironmentSharePoint": "The app is running on your local environment as SharePoint web part",
"AppLocalEnvironmentTeams": "The app is running on your local environment as Microsoft Teams app",
"AppLocalEnvironmentOffice": "The app is running on your local environment in office.com",
"AppLocalEnvironmentOutlook": "The app is running on your local environment in Outlook",
"AppSharePointEnvironment": "The app is running on SharePoint page",
"AppTeamsTabEnvironment": "The app is running in Microsoft Teams",
"AppOfficeEnvironment": "The app is running in office.com",
"AppOutlookEnvironment": "The app is running in Outlook"
}
});

View File

@ -0,0 +1,18 @@
declare interface IJsonFormWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
}
declare module 'JsonFormWebPartStrings' {
const strings: IJsonFormWebPartStrings;
export = strings;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 542 B

View File

@ -0,0 +1,36 @@
{
"extends": "./node_modules/@microsoft/rush-stack-compiler-4.5/includes/tsconfig-web.json",
"compilerOptions": {
"target": "es5",
"forceConsistentCasingInFileNames": true,
"module": "esnext",
"moduleResolution": "node",
"jsx": "react",
"declaration": true,
"sourceMap": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"outDir": "lib",
"inlineSources": false,
"strictNullChecks": false,
"noImplicitAny": false,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}