Merge pull request #3052 from mromiszewski/react-csv-importer

New sample react-csv-importer
This commit is contained in:
Hugo Bernier 2022-11-08 10:04:41 -05:00 committed by GitHub
commit 8a817d7e3d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
36 changed files with 62651 additions and 0 deletions

View File

@ -0,0 +1,29 @@
// 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.15.0",
"image": "docker.io/m365pnp/spfx:1.15.0",
// 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": {
"label": "Manifest",
"requireLocalPort": true
},
"35729": {
"label": "LiveReload",
"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,378 @@
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/no-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': [
1,
{
'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: {
'no-new': 0,
'class-name': 0,
'export-name': 0,
forin: 0,
'label-position': 0,
'member-access': 2,
'no-arg': 0,
'no-console': 0,
'no-construct': 0,
'no-duplicate-variable': 2,
'no-eval': 0,
'no-function-expression': 2,
'no-internal-module': 2,
'no-shadowed-variable': 2,
'no-switch-case-fall-through': 2,
'no-unnecessary-semicolons': 2,
'no-unused-expression': 2,
'no-with-statement': 2,
semicolon: 2,
'trailing-comma': 0,
typedef: 0,
'typedef-whitespace': 0,
'use-named-parameter': 2,
'variable-name': 0,
whitespace: 0
}
}
]
};

View File

@ -0,0 +1 @@
*.sh text eol=lf

39
samples/react-csv-importer/.gitignore vendored Normal file
View File

@ -0,0 +1,39 @@
# 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
# .CER Certificates
*.cer
# .PEM Certificates
*.pem

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,16 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"version": "1.15.2",
"libraryName": "react-csv-importer",
"libraryId": "6f431978-38c4-492e-878b-4d818caf51ee",
"environment": "spo",
"packageManager": "npm",
"solutionName": "react-csv-importer",
"solutionShortDescription": "react-csv-importer description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,89 @@
# CSV Importer
## Summary
This web part allows users to import CSV files into an existing SharePoint list.
![CSV Importer preview](assets/react-csv-importer.gif)
![CSV Importer preview](assets/react-csv-importer.png)
## Compatibility
![SPFx 1.15.2](https://img.shields.io/badge/SPFx-1.15.2-green.svg)
![Node.js v14 | v12](https://img.shields.io/badge/Node.js-v14%20%7C%20v12-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-Compatible-green.svg)
## Applies to
* [SharePoint Framework](https://docs.microsoft.com/sharepoint/dev/spfx/sharepoint-framework-overview)
* [Microsoft 365 tenant](https://docs.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/o365devprogram)
## Solution
Solution|Author(s)
--------|---------
react-csv-importer | [Michał Romiszewski](https://github.com/mromiszewski) ([@romiszewski](https://twitter.com/romiszewski))
## Version history
Version|Date|Comments
-------|----|--------
1.0|October 11, 2022|Initial release
## 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-csv-importer) then unzip it)
* From your command line, change your current directory to the directory containing this sample (`react-csv-importer`, located under `samples`)
* in the command line run:
* `npm install`
* `gulp serve`
* To package and deploy:
* Use `gulp bundle --ship` & `gulp package-solution --ship`
* Add the `.sppkg` to your SharePoint App Catalog
> 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
* Uploader and CSV parser
* Raw file preview
* User selectable column mapping (drag and drop UI)
* Automatically map fields to SharePoint list column names
This sample uses [PnP/PnPjs](https://pnp.github.io/pnpjs/) library, [@pnp/spfx-controls-react](https://pnp.github.io/sp-dev-fx-controls-react/), @pnp/[spfx-property-controls](https://pnp.github.io/sp-dev-fx-property-controls/) and [React CSV Importer](https://github.com/beamworks/react-csv-importer) component.
<!--
RESERVED FOR REPO MAINTAINERS
We'll add the video from the community call recording here
## Video
[![YouTube video title](./assets/video-thumbnail.jpg)](https://www.youtube.com/watch?v=XXXXX "YouTube video title")
-->
## 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%20YOUR-SOLUTION-NAME%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=YOUR-SOLUTION-NAME) 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%20YOUR-SOLUTION-NAME&template=bug-report.yml&sample=YOUR-SOLUTION-NAME&authors=@YOURGITHUBUSERNAME&title=YOUR-SOLUTION-NAME%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%20YOUR-SOLUTION-NAME&template=question.yml&sample=YOUR-SOLUTION-NAME&authors=@YOURGITHUBUSERNAME&title=YOUR-SOLUTION-NAME%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%20YOUR-SOLUTION-NAME&template=suggestion.yml&sample=YOUR-SOLUTION-NAME&authors=@YOURGITHUBUSERNAME&title=YOUR-SOLUTION-NAME%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://pnptelemetry.azurewebsites.net/sp-dev-fx-webparts/samples/react-csv-importer" />

Binary file not shown.

After

Width:  |  Height:  |  Size: 426 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

View File

@ -0,0 +1,20 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"csv-importer-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/csvImporter/CsvImporterWebPart.js",
"manifest": "./src/webparts/csvImporter/CsvImporterWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"CsvImporterWebPartStrings": "lib/webparts/csvImporter/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-csv-importer",
"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-csv-importer-client-side-solution",
"id": "6f431978-38c4-492e-878b-4d818caf51ee",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.15.2"
},
"metadata": {
"shortDescription": {
"default": "react-csv-importer description"
},
"longDescription": {
"default": "react-csv-importer description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-csv-importer Feature",
"description": "The feature that activates elements of the react-csv-importer solution.",
"id": "2130ba3a-4063-4ea5-89c4-cf64dbe9fea6",
"version": "1.0.0.0"
}
]
},
"paths": {
"zippedPackage": "solution/react-csv-importer.sppkg"
}
}

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://enter-your-SharePoint-site/_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-csv-importer/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'));

61274
samples/react-csv-importer/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,42 @@
{
"name": "react-csv-importer",
"version": "0.0.1",
"private": true,
"main": "lib/index.js",
"scripts": {
"build": "gulp bundle",
"clean": "gulp clean",
"test": "gulp test"
},
"dependencies": {
"@microsoft/sp-core-library": "1.15.2",
"@microsoft/sp-lodash-subset": "1.15.2",
"@microsoft/sp-office-ui-fabric-core": "1.15.2",
"@microsoft/sp-property-pane": "1.15.2",
"@microsoft/sp-webpart-base": "1.15.2",
"@pnp/logging": "^3.7.0",
"@pnp/sp": "^3.7.0",
"@pnp/spfx-controls-react": "3.10.0",
"@pnp/spfx-property-controls": "^3.10.0",
"office-ui-fabric-react": "7.185.7",
"react": "16.13.1",
"react-csv-importer": "^0.7.1",
"react-dom": "16.13.1",
"tslib": "2.3.1"
},
"devDependencies": {
"@microsoft/eslint-config-spfx": "1.15.2",
"@microsoft/eslint-plugin-spfx": "1.15.2",
"@microsoft/rush-stack-compiler-4.5": "0.2.2",
"@microsoft/sp-build-web": "1.15.2",
"@microsoft/sp-module-interfaces": "1.15.2",
"@rushstack/eslint-config": "2.5.1",
"@types/react": "16.9.51",
"@types/react-dom": "16.9.8",
"@types/webpack-env": "~1.15.2",
"ajv": "^6.12.5",
"eslint-plugin-react-hooks": "4.3.0",
"gulp": "4.0.2",
"typescript": "4.5.5"
}
}

View File

@ -0,0 +1,169 @@
@import '~office-ui-fabric-react/dist/sass/References.scss';
.csvImporter {
:global {
.CSVImporter_TextButton {
background-color: "[theme: themePrimary, default: #0078d7]";
border-color: "[theme: themePrimary, default: #0078d7]";
color: "[theme: white, default: #ffffff]";
border-radius: 2px;
font-weight: 600;
font-size: 14px;
}
.CSVImporter_TextButton:hover:not(:disabled) {
background-color: "[theme: themeDarkAlt, default: #106ebe]";
border-color: "[theme: themeDarkAlt, default: #106ebe]";
}
.CSVImporter_FileSelector {
border: .12em dashed;
border-color: "[theme: neutralPrimary, default: #323130]";
background: "[theme: neutralLight, default: #edebe9]";
color: var(--bodyText);
border-radius: 0;
padding: 5em;
}
.CSVImporter_ImporterFrame {
border: .12em solid;
border-color: "[theme: neutralQuaternary, default: #d2d0ce]";
padding: 1.2em;
border-radius: 0;
background: "[theme: neutralLighterAlt, default: #faf9f8]";
}
.CSVImporter_ColumnDragCard {
background: "[theme: white, default: #ffffff]";
}
.CSVImporter_ColumnDragCard__cardHeader>b {
background: "[theme: neutralQuaternaryAlt, default: #e1dfdd]";
}
.CSVImporter_ColumnDragCard[data-shadow=true] {
background: "[theme: neutralQuaternaryAlt, default: #e1dfdd]";
color: "[theme: neutralPrimaryAlt, default: #3b3a39]";
}
.CSVImporter_ColumnDragCard__cardHeader {
color: "[theme: neutralPrimaryAlt, default: #3b3a39]";
}
.CSVImporter_ColumnDragCard[data-shadow=true]>.CSVImporter_ColumnDragCard__cardValue[data-header=true] {
color: "[theme: neutralTertiaryAlt, default: #c8c6c4]";
}
.CSVImporter_FileStep__header {
color: "[theme: neutralTertiaryAlt, default: #c8c6c4]";
}
.CSVImporter_FormatDataRowPreview__table>thead>tr>th {
color: "[theme: neutralTertiaryAlt, default: #c8c6c4]";
}
.CSVImporter_FormatDataRowPreview {
border-color: "[theme: neutralPrimaryAlt, default: #3b3a39]";
}
.CSVImporter_FormatRawPreview__pre {
margin: 0;
padding: .25em .25em;
line-height: 1.1;
font-size: 1em;
}
.CSVImporter_FormatRawPreview__scroll {
border-radius: 0;
background: "[theme: neutralPrimaryAlt, default: #3b3a39]";
color: "[theme: neutralLight, default: #edebe9]";
}
.CSVImporter_ProgressDisplay__progressBarIndicator {
background: "[theme: neutralPrimaryAlt, default: #3b3a39]";
}
.CSVImporter_ImporterFrame__headerCrumbSeparator>span {
-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>');
mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>');
background-image: none;
background-color: var(--bodyText);
}
.CSVImporter_IconButton>span[data-type=arrowBack] {
-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>');
mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>');
background-image: none;
background-color: var(--bodyText);
}
.CSVImporter_IconButton>span[data-type=back] {
-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>');
mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/></svg>');
background-image: none;
background-color: var(--bodyText);
}
.CSVImporter_IconButton>span[data-type=forward] {
-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>');
mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>');
background-image: none;
background-color: var(--bodyText);
}
.CSVImporter_IconButton>span[data-type=replay] {
-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/></svg>');
mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 5V1L7 6l5 5V7c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z"/></svg>');
background-image: none;
background-color: var(--bodyText);
}
.CSVImporter_IconButton>span[data-type=close] {
-webkit-mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" focusable="false" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path></svg>');
mask-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" focusable="false" viewBox="0 0 24 24"><path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"></path></svg>');
background-image: none;
background-color: var(--bodyText);
}
.CSVImporter_FileStep__headerToggle {
color: var(--bodyText);
}
.CSVImporter_ImporterFrame__headerTitle {
color: var(--bodyText);
}
.CSVImporter_ImporterFrame__headerSubtitle {
color: var(--bodyText);
}
.CSVImporter_ColumnDragTargetArea__boxLabel {
color: var(--bodyText);
}
.CSVImporter_ColumnDragTargetArea__boxLabel>b {
color: "[theme: red, default: #d13438]";
}
.CSVImporter_ProgressDisplay__status {
color: var(--bodyText);
}
.CSVImporter_ProgressDisplay__count {
color: var(--bodyText);
}
}
.title {
@include ms-font-xl;
}
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}

View File

@ -0,0 +1,80 @@
import * as React from 'react';
import styles from './CsvImporter.module.scss';
import { ICsvImporterProps } from './ICsvImporterProps';
import { BaseRow, Importer, ImporterField, ImportInfo } from 'react-csv-importer';
import 'react-csv-importer/dist/index.css';
import { Logger, LogLevel } from '@pnp/logging';
import { WebPartTitle } from '@pnp/spfx-controls-react';
import { isEmpty } from '@microsoft/sp-lodash-subset';
import { Placeholder } from "@pnp/spfx-controls-react/lib/Placeholder";
import { MessageBar, MessageBarType } from 'office-ui-fabric-react';
import * as strings from 'CsvImporterWebPartStrings';
import { useList } from "../hooks";
export const CsvImporter: React.FunctionComponent<ICsvImporterProps> = (props) => {
const LOG_SOURCE: string = 'CsvImporter';
const [error, setError] = React.useState<string>("");
const [key, setKey] = React.useState(0);
const { title, listId, showListTitle, displayMode, updateProperty, onConfigure, hasTeamsContext } = props;
const { addListItems, listTitle, fields } = useList(listId);
const handleOnstart = (info: ImportInfo): void => {
const { file, fields } = info;
Logger.write(`${LOG_SOURCE} - handleOnstart - Starting import of file ${file.name} (${file.size} bytes), with fields: ${fields}`, LogLevel.Info);
}
const handleProcessChunk = async (rows: BaseRow[]): Promise<void> => {
Logger.write(`${LOG_SOURCE} - handleProcessChunk - Received batch of ${rows.length} rows`, LogLevel.Info);
const result = await addListItems(listId, rows);
if (!isEmpty(result)) setError(JSON.stringify(result));
}
const handleOnClose = (): void => {
Logger.write(`${LOG_SOURCE} - handleOnClose - Import is done and user clicked [Finish]`, LogLevel.Info);
setKey(key => key + 1);
setError(null);
}
return (
<section className={`${styles.csvImporter} ${hasTeamsContext ? styles.teams : ''}`}>
<WebPartTitle displayMode={displayMode}
title={title}
updateProperty={updateProperty} />
{showListTitle ? <div className={styles.title}>{listTitle}</div> : null}
{isEmpty(listId) ?
<Placeholder
iconName='Edit'
iconText={strings.PlaceholderIconText}
description={strings.PlaceholderDescription}
buttonLabel={strings.PlaceholderButtonLabel}
onConfigure={onConfigure}
/>
:
<>
<Importer
key={key}
assumeNoHeaders={false}
restartable={false}
onStart={handleOnstart}
processChunk={handleProcessChunk}
onClose={handleOnClose}
>
{fields?.map((field, i) => (<ImporterField key={i} name={field.InternalName} label={field.Title} optional={!field.Required} />))}
</Importer>
{!isEmpty(error) ?
<MessageBar
messageBarType={MessageBarType.error}
dismissButtonAriaLabel={strings.MessageBarDismissButtonAriaLabel}
overflowButtonAriaLabel={strings.MessageBarOverflowButtonAriaLabel}
isMultiline={false}
truncated={true}
>
<b>{strings.MessageBarDescription}</b>
<small>{error}</small>
</MessageBar> : null}
</>
}
</section>
);
}

View File

@ -0,0 +1,14 @@
import { DisplayMode } from "@microsoft/sp-core-library";
export interface ICsvImporterProps {
title: string;
listId: string;
showListTitle: boolean;
displayMode: DisplayMode;
updateProperty: (value: string) => void;
onConfigure: () => void;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
userDisplayName: string;
}

View File

@ -0,0 +1,2 @@
export * from './CsvImporter';
export * from './ICsvImporterProps';

View File

@ -0,0 +1,6 @@
export interface ISpoFiled {
InternalName: string;
Title: string;
Required: boolean;
Type: string;
}

View File

@ -0,0 +1 @@
export * from './ISpoFiled';

View File

@ -0,0 +1 @@
export * from './useList';

View File

@ -0,0 +1,107 @@
import * as React from 'react';
import { SPFI, IFieldInfo, FieldTypes, IListInfo, IListItemFormUpdateValue } from '@pnp/sp/presets/all';
import { Logger, LogLevel } from '@pnp/logging';
import { ISpoFiled } from '../entities';
import { getSp } from "../utils";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export const useList = (listId: string) => {
const LOG_SOURCE: string = 'useList';
const MAX_BATCH_OPERATIONS = 1000;
const sp: SPFI = React.useMemo(() => getSp(), []);
const [listTitle, setListTitle] = React.useState<string>("");
const [fields, setFields] = React.useState<ISpoFiled[]>([]);
const getList = React.useCallback(async (listId: string): Promise<IListInfo> => {
if (!sp) return undefined;
return await sp.web.lists
.getById(listId)
.select("Title", "ParentWebUrl")();
}, [sp]);
const getListColumns = React.useCallback(async (listId: string): Promise<ISpoFiled[]> => {
if (!sp) return undefined;
const fields: IFieldInfo[] = await sp.web
.lists
.getById(listId)
.fields();
const fieldArray: ISpoFiled[] = [];
fields.map(field => {
if (field.ReadOnlyField === false &&
field.Hidden === false &&
field.FieldTypeKind !== FieldTypes.Attachments &&
field.FieldTypeKind !== FieldTypes.Computed
) {
fieldArray.push({
InternalName: field.InternalName,
Title: field.Title,
Required: field.Required,
Type: field.TypeAsString
})
}
});
return fieldArray;
}, [sp]);
const addListItemsWithBatching = React.useCallback(async (listInfo: IListInfo, items: { [name: string]: unknown; }[]): Promise<IListItemFormUpdateValue[][]> => {
if (!sp) return;
const [batchedWeb, execute] = sp.web.batched();
const result: IListItemFormUpdateValue[][] = [];
items.map(async row => {
const formValues: IListItemFormUpdateValue[] = [];
Object.keys(row).map(async key => formValues.push({ FieldName: key, FieldValue: row[key].toString() }));
await batchedWeb.lists
.getById(listId)
.addValidateUpdateItemUsingPath(formValues,
`${listInfo.ParentWebUrl !== '/' ? listInfo.ParentWebUrl : ''}/Lists/${listInfo.Title}`)
.then(r => {
const errors = r.filter(field => field.ErrorMessage !== null);
if (errors.length > 0) {
result.push(errors);
Logger.write(`${LOG_SOURCE} - addListItemsWithBatching - ${JSON.stringify(errors)}`, LogLevel.Error);
}
})
.catch(error => {
result.push([{ ErrorMessage: error.message }]);
Logger.write(`${LOG_SOURCE} - addListItemsWithBatching - ${error.message}`, LogLevel.Error);
});
});
await execute();
return result;
}, [sp]);
const addListItems = React.useCallback(async (listId: string, items: { [name: string]: unknown; }[]): Promise<IListItemFormUpdateValue[][]> => {
const result: IListItemFormUpdateValue[][] = [];
try {
const listInfo: IListInfo = await getList(listId);
for (let i = 0; i < items.length; i += MAX_BATCH_OPERATIONS) {
const batch = items.slice(i, i + MAX_BATCH_OPERATIONS);
Logger.write(`${LOG_SOURCE} - addListItems - Processing batch: ${i} - ${i + batch.length}`, LogLevel.Info);
result.push(...await addListItemsWithBatching(listInfo, batch));
}
} catch (error) {
result.push([{ ErrorMessage: error.message }]);
Logger.write(`${LOG_SOURCE} - addListItems - ${error.message}`, LogLevel.Error);
}
return result;
}, [sp]);
React.useEffect(() => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async (): Promise<void> => {
setListTitle((await getList(listId)).Title);
setFields(await getListColumns(listId));
})();
}, [listId]);
return {
getList,
getListColumns,
addListItems,
listTitle,
fields
}
}

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 @@
export * from './pnpjsConfig';

View File

@ -0,0 +1,20 @@
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { isEmpty } from "@microsoft/sp-lodash-subset";
import { spfi, SPFI, SPFx } from "@pnp/sp";
import { LogLevel, PnPLogging } from "@pnp/logging";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/fields";
import "@pnp/sp/batching";
// eslint-disable-next-line no-var
var _sp: SPFI = null;
export const getSp = (context?: WebPartContext): SPFI => {
if (!isEmpty(context)) {
_sp = spfi().using(SPFx(context)).using(PnPLogging(LogLevel.Warning));
}
return _sp;
}

View File

@ -0,0 +1,30 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "2d356a7d-b23f-422f-b44a-27affb734807",
"alias": "CsvImporterWebPart",
"componentType": "WebPart",
// The "*" signifies that the version should be taken from the package.json
"version": "*",
"manifestVersion": 2,
// If true, the component can only be installed on sites where Custom Script is allowed.
// Components that allow authors to embed arbitrary script code should set this to true.
// https://support.office.com/en-us/article/Turn-scripting-capabilities-on-or-off-1f2c515f-5d7e-448a-9fd7-835da935584f
"requiresCustomScript": false,
"supportedHosts": ["SharePointWebPart", "TeamsPersonalApp", "TeamsTab", "SharePointFullPage"],
"supportsThemeVariants": true,
"preconfiguredEntries": [{
"groupId": "5c03119e-3074-46fd-976b-c60198311f70", // Other
"group": { "default": "Other" },
"title": { "default": "CsvImporter" },
"description": { "default": "CsvImporter description" },
"officeFabricIconFontName": "Page",
"properties": {
"title": "CSV Importer",
"listId": "",
"showListTitle": true
}
}]
}

View File

@ -0,0 +1,131 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
PropertyPaneTextField,
PropertyPaneToggle
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { ConsoleListener, Logger, LogLevel } from '@pnp/logging';
import * as strings from 'CsvImporterWebPartStrings';
import { CsvImporter, ICsvImporterProps } from '../../components';
import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldListPicker';
import { getSp } from '../../utils';
export interface ICsvImporterWebPartProps {
title: string;
listId: string;
showListTitle: boolean;
}
export default class CsvImporterWebPart extends BaseClientSideWebPart<ICsvImporterWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = '';
public render(): void {
const element: React.ReactElement<ICsvImporterProps> = React.createElement(
CsvImporter,
{
title: this.properties.title,
listId: this.properties.listId,
showListTitle: this.properties.showListTitle,
displayMode: this.displayMode,
updateProperty: (value: string) => { this.properties.title = value; },
onConfigure: () => this.context.propertyPane.open(),
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userDisplayName: this.context.pageContext.user.displayName
}
);
ReactDom.render(element, this.domElement);
}
protected async onInit(): Promise<void> {
this._environmentMessage = this._getEnvironmentMessage();
Logger.subscribe(ConsoleListener());
Logger.activeLogLevel = LogLevel.Verbose;
getSp(this.context);
await super.onInit();
}
private _getEnvironmentMessage(): string {
if (!!this.context.sdks.microsoftTeams) { // running in Teams
return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentTeams : strings.AppTeamsTabEnvironment;
}
return this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentSharePoint : strings.AppSharePointEnvironment;
}
protected onThemeChanged(currentTheme: IReadonlyTheme | undefined): void {
if (!currentTheme) {
return;
}
this._isDarkTheme = !!currentTheme.isInverted;
const {
semanticColors
} = currentTheme;
if (semanticColors) {
this.domElement.style.setProperty('--bodyText', semanticColors.bodyText || null);
this.domElement.style.setProperty('--link', semanticColors.link || null);
this.domElement.style.setProperty('--linkHovered', semanticColors.linkHovered || null);
}
}
protected onDispose(): void {
ReactDom.unmountComponentAtNode(this.domElement);
}
protected get dataVersion(): Version {
return Version.parse('1.0');
}
protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration {
return {
pages: [
{
header: {
description: strings.PropertyPaneDescription
},
groups: [
{
isGroupNameHidden: true,
groupFields: [
PropertyFieldListPicker('listId', {
label: strings.PropertyFieldListPickerLabel,
selectedList: this.properties.listId,
includeHidden: false,
orderBy: PropertyFieldListPickerOrderBy.Title,
disabled: false,
baseTemplate: 100,
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
properties: this.properties,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
context: this.context as any,
onGetErrorMessage: null,
deferredValidationTime: 0,
key: 'listPickerFieldId'
}),
PropertyPaneToggle('showListTitle', {
label: null,
onText: strings.PropertyPaneToggleShowListText,
offText: strings.PropertyPaneToggleHideListText
}),
PropertyPaneTextField('title', {
label: strings.PropertyPaneTextFieldTitleLabel
})
]
}
]
}
]
};
}
}

View File

@ -0,0 +1,19 @@
define([], function() {
return {
"PropertyPaneDescription": "Web Part Configuration",
"PropertyPaneTextFieldTitleLabel": "Web Part Title",
"PropertyFieldListPickerLabel": "Select a list",
"PropertyPaneToggleShowListText": "Show list title",
"PropertyPaneToggleHideListText": "Hide list tile",
"PlaceholderIconText": "Configure your web part",
"PlaceholderDescription": "Please configure the web part.",
"PlaceholderButtonLabel": "Configure",
"MessageBarOverflowButtonAriaLabel": "See more",
"MessageBarDismissButtonAriaLabel": "Close",
"MessageBarDescription": "Error while creating list items: ",
"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",
"AppSharePointEnvironment": "The app is running on SharePoint page",
"AppTeamsTabEnvironment": "The app is running in Microsoft Teams"
}
});

View File

@ -0,0 +1,22 @@
declare interface ICsvImporterWebPartStrings {
PropertyPaneDescription: string;
PropertyPaneTextFieldTitleLabel: string;
PropertyFieldListPickerLabel: string;
PropertyPaneToggleShowListText: string;
PropertyPaneToggleHideListText: string;
PlaceholderIconText: string;
PlaceholderDescription: string;
PlaceholderButtonLabel: string;
MessageBarOverflowButtonAriaLabel: string;
MessageBarDismissButtonAriaLabel: string;
MessageBarDescription: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
}
declare module 'CsvImporterWebPartStrings' {
const strings: ICsvImporterWebPartStrings;
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,37 @@
{
"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,
"noUnusedLocals": false,
"noImplicitAny": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}