Merge pull request #4826 from Harsh24491/react-poll

This commit is contained in:
Hugo Bernier 2024-03-16 18:40:50 -04:00 committed by GitHub
commit 8174604ca5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
45 changed files with 38729 additions and 0 deletions

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': [
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: {}
}
]
};

35
samples/react-poll/.gitignore vendored Normal file
View File

@ -0,0 +1,35 @@
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules
# Build generated files
dist
lib
solution
temp
*.sppkg
# 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
# Folders
release

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 @@
v14.16.1

View File

@ -0,0 +1,21 @@
{
"@microsoft/generator-sharepoint": {
"plusBeta": false,
"isCreatingSolution": true,
"nodeVersion": "14.16.1",
"sdksVersions": {
"@microsoft/microsoft-graph-client": "3.0.2",
"@microsoft/teams-js": "2.9.1"
},
"version": "1.17.1",
"libraryName": "react-poll",
"libraryId": "cdbf6459-a379-48cd-9b46-1ae0440090a7",
"environment": "spo",
"packageManager": "npm",
"solutionName": "ReactPoll",
"solutionShortDescription": "ReactPoll description",
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"componentType": "webpart"
}
}

View File

@ -0,0 +1,319 @@
# React Poll
## Summary
This web part allow User to add New Poll Questions and their options. End users can submit his/her response to the poll. After Submission, user can see all responses count with Bar chart.
![React-Poll](./assets/react-poll.gif)
![Webpart - 1 ](./assets/wp1.png)
![Webpart - 2 ](./assets/wp2.png)
**Following are some of the features of this component.**
- These 2 lists will be provisioned automatically with necessary columns.
- Poll Questions : User can add New poll question and their options. Also, user can set to keep it active or not.
![Poll Questions](./assets/poll-questions.png)
- Poll Answers: This list will hold all Answers give by End users with his/her email id.
![Poll Answers](./assets/poll-answers.png)
- Poll response can be viewed via Bar chart.
- Easy to configure.
## Compatibility
| :warning: Important |
|:---------------------------|
| Every SPFx version is optimally compatible with specific versions of Node.js. In order to be able to build this sample, you need to 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.13+](https://img.shields.io/badge/Node.js-v16.13+-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://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](https://aka.ms/m365/devprogram)
## Prerequisites
- Office 365 subscription with SharePoint Online
- SharePoint Framework [development environment](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-development-environment) set up
## Contributors
- [Harsh Bhavsar](https://github.com/Harsh24491)
## Version history
| Version | Date | Comments |
| ------- | ---------------- | --------------- |
| 1.0 | March 16, 2024 | 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-poll) then unzip it)
- From your command line, change your current directory to the directory containing this sample (`react-poll`, 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](https://aka.ms/spfx-devcontainer) for further instructions.
## How to Set up Poll
- This solution will provision 2 lists "Poll Questions" and "Poll Answers"
- To set up new Poll navigate to "Poll Questions" from "Site Contents"
- Add new item with these metadata.
-- Question (Mandatory) - Question for the poll
-- Option 1 (Mandatory) - 1st Option for the poll
-- Option 2 (Mandatory) - 2nd Option for the poll
-- Option 3 (Non mandatory) - 3rd Option for the poll
-- Option 4 (Non mandatory) - 4th Option for the poll
-- Is Question Active (Mandatory) - Checkbox to Keep Poll active or not
-- Title (Mandatory) - Title of Poll
![Set up Poll](./assets/add-poll.png)
- P.S. : Only 1 poll with Active will be displayed.
## Help
We do not support samples, but we 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-pages-hierarchy%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-pages-hierarchy) and see what the community is saying.
If you encounter any issues while 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-pages-hierarchy&template=bug-report.yml&sample=react-pages-hierarchy&authors=@bogeorge&title=react-pages-hierarchy%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-pages-hierarchy&template=question.yml&sample=react-pages-hierarchy&authors=@bogeorge&title=react-pages-hierarchy%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-pages-hierarchy&template=question.yml&sample=react-pages-hierarchy&authors=@bogeorge&title=react-pages-hierarchy%20-%20).
## [](https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-pages-hierarchy#disclaimer)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.**

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.3 KiB

View File

@ -0,0 +1,19 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
"version": "2.0",
"bundles": {
"react-poll-web-part": {
"components": [
{
"entrypoint": "./lib/webparts/reactPoll/ReactPollWebPart.js",
"manifest": "./src/webparts/reactPoll/ReactPollWebPart.manifest.json"
}
]
}
},
"externals": {},
"localizedResources": {
"ReactPollWebPartStrings": "lib/webparts/reactPoll/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-poll",
"accessKey": "<!-- ACCESS KEY -->"
}

View File

@ -0,0 +1,49 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
"solution": {
"name": "react-poll-client-side-solution",
"id": "cdbf6459-a379-48cd-9b46-1ae0440090a7",
"version": "1.0.0.0",
"includeClientSideAssets": true,
"skipFeatureDeployment": true,
"isDomainIsolated": false,
"developer": {
"name": "",
"websiteUrl": "",
"privacyUrl": "",
"termsOfUseUrl": "",
"mpnId": "Undefined-1.17.1"
},
"metadata": {
"shortDescription": {
"default": "ReactPoll description"
},
"longDescription": {
"default": "ReactPoll description"
},
"screenshotPaths": [],
"videoUrl": "",
"categories": []
},
"features": [
{
"title": "react-poll Feature",
"description": "The feature that activates elements of the react-poll solution.",
"id": "f8f96128-e5f1-4f79-8bc1-2480bc29742d",
"version": "1.0.0.0",
"assets": {
"elementManifests": [
"elements.xml"
],
"elementFiles":[
"schema.xml",
"PollQuestionsSchema.xml"
]
}
}
]
},
"paths": {
"zippedPackage": "solution/react-poll.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 -->"
}

View File

@ -0,0 +1,6 @@
{
"$schema": "https://raw.githubusercontent.com/s-KaiNet/spfx-fast-serve/master/schema/config.latest.schema.json",
"cli": {
"isLibraryComponent": false
}
}

View File

@ -0,0 +1,24 @@
/*
* User webpack settings file. You can add your own settings here.
* Changes from this file will be merged into the base webpack configuration file.
* This file will not be overwritten by the subsequent spfx-fast-serve calls.
*/
// you can add your project related webpack configuration here, it will be merged using webpack-merge module
// i.e. plugins: [new webpack.Plugin()]
const webpackConfig = {
}
// for even more fine-grained control, you can apply custom webpack settings using below function
const transformConfig = function (initialWebpackConfig) {
// transform the initial webpack config here, i.e.
// initialWebpackConfig.plugins.push(new webpack.Plugin()); etc.
return initialWebpackConfig;
}
module.exports = {
webpackConfig,
transformConfig
}

24
samples/react-poll/gulpfile.js vendored Normal file
View File

@ -0,0 +1,24 @@
'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.`);
build.addSuppression(/Warning - \[sass\] The local CSS class/gi);
var getTasks = build.rig.getTasks;
build.rig.getTasks = function () {
var result = getTasks.call(build.rig);
result.set('serve', result.get('serve-deprecated'));
return result;
};
/* fast-serve */
const { addFastServe } = require("spfx-fast-serve-helpers");
addFastServe(build);
/* end of fast-serve */
build.initialize(require('gulp'));

33869
samples/react-poll/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,45 @@
{
"name": "react-poll",
"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",
"serve": "gulp bundle --custom-serve --max_old_space_size=4096 && fast-serve"
},
"dependencies": {
"@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/sp": "^3.1.0",
"@pnp/spfx-controls-react": "3.14.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",
"spfx-fast-serve-helpers": "~1.17.0",
"typescript": "4.5.5"
}
}

View File

@ -0,0 +1,34 @@
<List xmlns:ows="Microsoft SharePoint" Title="Poll Questions" EnableContentTypes="TRUE" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/Basic List" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
<MetaData>
<ContentTypes>
<ContentTypeRef ID="0x0100f852c6a1eafd4e488d73242654e1ecbc" />
</ContentTypes>
<Fields></Fields>
<Views>
<View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
<XslLink Default="TRUE">main.xsl</XslLink>
<JSLink>clienttemplates.js</JSLink>
<RowLimit Paged="TRUE">30</RowLimit>
<Toolbar Type="Standard" />
<ViewFields>
<FieldRef Name="Question"></FieldRef>
<FieldRef Name="Option1"></FieldRef>
<FieldRef Name="Option2"></FieldRef>
<FieldRef Name="Option3"></FieldRef>
<FieldRef Name="Option4"></FieldRef>
<FieldRef Name="IsQuestionActive"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="ID" />
</OrderBy>
</Query>
</View>
</Views>
<Forms>
<Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>
</MetaData>
</List>

View File

@ -0,0 +1,121 @@
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- Fields for Poll Answers list -->
<Field ID="{060E50AC-E9C1-4D3C-B1F9-DE0BCAC300F6}"
Name="UserEmail"
DisplayName="UserEmail"
Type="Text"
Required="TRUE"
Group="React Poll Solution Fields" />
<Field ID="{943E7530-5E2B-4C02-8259-CCD93A9ECB18}"
Name="Option"
DisplayName="Option"
Type="Choice"
Required="TRUE"
Group="React Poll Solution Fields">
<CHOICES>
<CHOICE>Option1</CHOICE>
<CHOICE>Option2</CHOICE>
<CHOICE>Option3</CHOICE>
<CHOICE>Option4</CHOICE>
</CHOICES>
</Field>
<!-- Fields for Poll Questions list -->
<Field ID="{124AA081-3F62-477C-A8A6-ECDADE7BA492}"
Name="Question"
DisplayName="Question"
Type="Note"
RichText="FALSE"
NumLines="6"
Required="TRUE"
Group="React Poll Solution Fields" />
<Field ID="{71961200-FCFB-42B6-BF0F-39826807D805}"
Name="Option1"
DisplayName="Option1"
Type="Text"
Required="TRUE"
Group="React Poll Solution Fields" />
<Field ID="{98880A02-9095-4699-8D40-7B967D5EBC77}"
Name="Option2"
DisplayName="Option2"
Type="Text"
Required="TRUE"
Group="React Poll Solution Fields" />
<Field ID="{1C2E1E97-12AB-4B60-BE32-074A2EDBBE5D}"
Name="Option3"
DisplayName="Option3"
Type="Text"
Required="FALSE"
Group="React Poll Solution Fields" />
<Field ID="{F55AEBF0-4C68-4646-975F-724E57F996B9}"
Name="Option4"
DisplayName="Option4"
Type="Text"
Required="FALSE"
Group="React Poll Solution Fields" />
<Field ID="{F1FB6A34-5CEC-495E-9B79-AB459640A59D}"
Name="IsQuestionActive"
DisplayName="Is Question Active"
Type="Boolean"
Required="TRUE"
Group="React Poll Solution Fields" >
<Default>TRUE</Default>
</Field>
<!-- Content Type for Poll Answers list -->
<ContentType ID="0x010042D0C1C200A14B6887742B6344675C8B"
Name="Poll Answers"
Group="React Poll Solution Content Types"
Description="Content Type for Poll Answers">
<FieldRefs>
<FieldRef ID="{060E50AC-E9C1-4D3C-B1F9-DE0BCAC300F6}" />
<FieldRef ID="{943E7530-5E2B-4C02-8259-CCD93A9ECB18}" />
</FieldRefs>
</ContentType>
<!-- Content Type for Poll Questions list -->
<ContentType ID="0x0100f852c6a1eafd4e488d73242654e1ecbc"
Name="Poll Questions"
Group="React Poll Solution Content Types"
Description="Content Type for Poll Questions">
<FieldRefs>
<FieldRef ID="{124AA081-3F62-477C-A8A6-ECDADE7BA492}" />
<FieldRef ID="{71961200-FCFB-42B6-BF0F-39826807D805}" />
<FieldRef ID="{98880A02-9095-4699-8D40-7B967D5EBC77}" />
<FieldRef ID="{1C2E1E97-12AB-4B60-BE32-074A2EDBBE5D}" />
<FieldRef ID="{F55AEBF0-4C68-4646-975F-724E57F996B9}" />
<FieldRef ID="{F1FB6A34-5CEC-495E-9B79-AB459640A59D}" />
</FieldRefs>
</ContentType>
<ListInstance
CustomSchema="schema.xml"
FeatureId="00bfea71-de22-43b2-a848-c05709900100"
Title="Poll Answers"
Description="List for Poll Answers"
TemplateType="100"
Url="Lists/PollAnswers">
</ListInstance>
<ListInstance
CustomSchema="PollQuestionsSchema.xml"
FeatureId="00bfea71-de22-43b2-a848-c05709900100"
Title="Poll Questions"
Description="List for Poll Answers"
TemplateType="100"
Url="Lists/PollQuestions">
</ListInstance>
</Elements>

View File

@ -0,0 +1,31 @@
<List xmlns:ows="Microsoft SharePoint" Title="Poll Answers" EnableContentTypes="TRUE" FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/Basic List" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
<MetaData>
<ContentTypes>
<ContentTypeRef ID="0x010042D0C1C200A14B6887742B6344675C8B" />
</ContentTypes>
<Fields></Fields>
<Views>
<View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
<XslLink Default="TRUE">main.xsl</XslLink>
<JSLink>clienttemplates.js</JSLink>
<RowLimit Paged="TRUE">30</RowLimit>
<Toolbar Type="Standard" />
<ViewFields>
<FieldRef Name="LinkTitle"></FieldRef>
<FieldRef Name="UserEmail"></FieldRef>
<FieldRef Name="Option"></FieldRef>
</ViewFields>
<Query>
<OrderBy>
<FieldRef Name="ID" />
</OrderBy>
</Query>
</View>
</Views>
<Forms>
<Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
<Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>
</MetaData>
</List>

View File

@ -0,0 +1,20 @@
export class Fields
{
static readonly Question= 'Question';
static readonly Option1= 'Option1';
static readonly Option2= 'Option2';
static readonly Option3= 'Option3';
static readonly Option4= 'Option4';
static readonly ID= 'ID';
static readonly IsQuestionActive= 'IsQuestionActive';
static readonly Title= 'Title';
static readonly UserEmail= 'UserEmail';
static readonly Option= 'Option';
}
export class ListsUrl
{
static readonly Questions = '/Lists/PollQuestions'
static readonly Answers = '/Lists/PollAnswers'
}

View File

@ -0,0 +1,121 @@
import { useState } from "react";
import { SPFI, spfi, SPFx } from "@pnp/sp";
import "@pnp/sp/webs";
import "@pnp/sp/lists";
import "@pnp/sp/items";
import "@pnp/sp/items/get-all";
import { WebPartContext } from "@microsoft/sp-webpart-base";
import { IQuestion, IAnswer } from "../models/models";
import { Fields, ListsUrl } from "../Constants/Constants";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function useGetData(
context: WebPartContext,
userEmail: string,
webServerRelativeUrl: string
) {
//Declare States
const [isLoading, setIsLoading] = useState<boolean>(true);
const [isSubmitting, setIsSubmitting] = useState<boolean>(false);
const [questions, setQuestions] = useState<IQuestion[]>([]);
const sp: SPFI = spfi().using(SPFx(context));
//Get Answer of Question from Question ID
const getAnswer = async (questionId: number): Promise<IAnswer | null> => {
let retVal: IAnswer | null = null;
const answers = await sp.web
.getList(`${webServerRelativeUrl}${ListsUrl.Answers}`)
.select(`${Fields.Title},${Fields.UserEmail},${Fields.Option}`)
.items.filter(`${Fields.Title} eq '${questionId}'`)
.getAll();
//Get Count of answers
retVal = {
allAnswers: [
answers.filter((x) => x.Option === Fields.Option1).length,
answers.filter((x) => x.Option === Fields.Option2).length,
answers.filter((x) => x.Option === Fields.Option3).length,
answers.filter((x) => x.Option === Fields.Option4).length,
],
//Check if Current User gave Answer already
isCurrentUserAnswered:
answers.filter((ans) => ans.UserEmail === userEmail).length > 0,
};
return retVal;
};
//Map Question with Options and Answer
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mapQuestion = async (item: any): Promise<IQuestion> => {
const question: IQuestion = {
id: item.ID,
question: item.Question,
options: [
{ key: Fields.Option1, text: item.Option1 },
{ key: Fields.Option2, text: item.Option2 },
item.Option3 ? { key: Fields.Option3, text: item.Option3 } : null,
item.Option4 ? { key: Fields.Option4, text: item.Option4 } : null,
],
answer: await getAnswer(item.ID),
};
return question;
};
//Get Question
const getQuestion = async (): Promise<void> => {
const questions: IQuestion[] = [];
const items = await sp.web
.getList(`${webServerRelativeUrl}${ListsUrl.Questions}`)
.items.select(
`${Fields.Question},${Fields.Option1},${Fields.Option2},${Fields.Option3},${Fields.Option4},${Fields.ID}`
)
.top(1)
.filter(`${Fields.IsQuestionActive} eq 1`)
.orderBy(Fields.ID, true)()
.catch((e) => {
console.log(e);
});
if (items) {
for (const item of items) {
questions.push(await mapQuestion(item));
}
}
setQuestions(questions);
setIsLoading(false);
};
//Submit Answer
const submitAnswer = async (
questionId: number,
answer: string,
userEmail: string
): Promise<void> => {
setIsSubmitting(true);
await sp.web
.getList(`${webServerRelativeUrl}${ListsUrl.Answers}`)
.items.add({
Title: questionId.toString(),
Option: answer,
UserEmail: userEmail,
})
.catch((e) => {
console.log(e);
});
await getQuestion();
setIsSubmitting(false);
};
return {
isLoading,
isSubmitting,
questions,
getQuestion,
submitAnswer,
setQuestions,
};
}

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,23 @@
export interface IQuestion {
id: number;
question: string;
options:IOption[];
answer?:IAnswer;
selectedOption?:string;
}
export interface IOption {
key: string;
text: string;
}
export interface IAnswer{
allAnswers:number[];
isCurrentUserAnswered:boolean;
}
export interface ISelectedOption{
selectedQuestionId:number;
selectedOption:string;
}

View File

@ -0,0 +1,28 @@
{
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
"id": "20c51803-5c7b-42fb-9017-a85cdfc5890c",
"alias": "ReactPollWebPart",
"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", // Advanced
"group": { "default": "Advanced" },
"title": { "default": "ReactPoll" },
"description": { "default": "ReactPoll description" },
"officeFabricIconFontName": "Page",
"properties": {
"description": "ReactPoll"
}
}]
}

View File

@ -0,0 +1,122 @@
import * as React from 'react';
import * as ReactDom from 'react-dom';
import { Version } from '@microsoft/sp-core-library';
import {
IPropertyPaneConfiguration,
//PropertyPaneTextField
} from '@microsoft/sp-property-pane';
import { BaseClientSideWebPart } from '@microsoft/sp-webpart-base';
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import * as strings from 'ReactPollWebPartStrings';
import ReactPoll from './components/ReactPoll';
import { IReactPollProps } from './components/IReactPollProps';
export interface IReactPollWebPartProps {
description: string;
}
export default class ReactPollWebPart extends BaseClientSideWebPart<IReactPollWebPartProps> {
private _isDarkTheme: boolean = false;
private _environmentMessage: string = '';
public render(): void {
const element: React.ReactElement<IReactPollProps> = React.createElement(
ReactPoll,
{
description: this.properties.description,
isDarkTheme: this._isDarkTheme,
environmentMessage: this._environmentMessage,
hasTeamsContext: !!this.context.sdks.microsoftTeams,
userEmail: this.context.pageContext.user.email,
context: this.context,
webServerRelativeUrl:this.context.pageContext.web.serverRelativeUrl
}
);
ReactDom.render(element, this.domElement);
}
protected onInit(): Promise<void> {
return this._getEnvironmentMessage().then(message => {
this._environmentMessage = message;
});
}
private _getEnvironmentMessage(): Promise<string> {
if (!!this.context.sdks.microsoftTeams) { // running in Teams, office.com or Outlook
return this.context.sdks.microsoftTeams.teamsJs.app.getContext()
.then(context => {
let environmentMessage: string = '';
switch (context.app.host.name) {
case 'Office': // running in Office
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentOffice : strings.AppOfficeEnvironment;
break;
case 'Outlook': // running in Outlook
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentOutlook : strings.AppOutlookEnvironment;
break;
case 'Teams': // running in Teams
environmentMessage = this.context.isServedFromLocalhost ? strings.AppLocalEnvironmentTeams : strings.AppTeamsTabEnvironment;
break;
default:
throw new Error('Unknown host');
}
return environmentMessage;
});
}
return Promise.resolve(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: [
// {
// groupName: strings.BasicGroupName,
// groupFields: [
// PropertyPaneTextField('description', {
// label: strings.DescriptionFieldLabel
// })
// ]
// }
// ]
// }
]
};
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 27 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 MiB

View File

@ -0,0 +1,12 @@
import { WebPartContext } from '@microsoft/sp-webpart-base';
export interface IReactPollProps {
description: string;
isDarkTheme: boolean;
environmentMessage: string;
hasTeamsContext: boolean;
userEmail: string;
context: WebPartContext;
webServerRelativeUrl:string;
}

View File

@ -0,0 +1,40 @@
import * as React from "react";
import {
Shimmer,
ShimmerElementType,
mergeStyles,
} from "@fluentui/react";
const ShimmerLoadder: React.FunctionComponent = () => {
const wrapperClass = mergeStyles({
padding: 2,
selectors: {
"& > .ms-Shimmer-container": {
margin: "10px 0",
},
},
});
const shimmerWithElements = [
{ type: ShimmerElementType.circle },
{ type: ShimmerElementType.gap, width: "2%" },
{ type: ShimmerElementType.line },
];
return (
<div className={wrapperClass}>
<Shimmer shimmerElements={shimmerWithElements} />
<Shimmer width="80%" shimmerElements={shimmerWithElements} />
<Shimmer width="60%" shimmerElements={shimmerWithElements} />
<Shimmer shimmerElements={shimmerWithElements} />
<Shimmer width="80%" shimmerElements={shimmerWithElements} />
<Shimmer width="60%" shimmerElements={shimmerWithElements} />
<Shimmer shimmerElements={shimmerWithElements} />
<Shimmer width="80%" shimmerElements={shimmerWithElements} />
<Shimmer width="60%" shimmerElements={shimmerWithElements} />
</div>
);
};
export { ShimmerLoadder };

View File

@ -0,0 +1,40 @@
@import '~office-ui-fabric-react/dist/sass/fabric.scss';
.reactPoll {
overflow: hidden;
padding: 1em;
color: "[theme:bodyText, default: #323130]";
color: var(--bodyText);
&.teams {
font-family: $ms-font-family-fallbacks;
}
}
.submitButtonRow{
text-align: center;
margin-top: 3rem ;
}
.chartRow{
text-align: center;
margin-top: 2rem ;
}
.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
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,162 @@
import * as React from "react";
import styles from "./ReactPoll.module.scss";
import { IReactPollProps } from "./IReactPollProps";
import { useGetData } from "../../../apiHooks/useGetData";
import { useEffect } from "react";
import {
ChoiceGroup,
IChoiceGroupOption,
} from "@fluentui/react/lib/ChoiceGroup";
import { PrimaryButton } from "office-ui-fabric-react/lib/components/Button/PrimaryButton/PrimaryButton";
import { IQuestion } from "../../../models/models";
import {
ChartControl,
ChartType,
} from "@pnp/spfx-controls-react/lib/ChartControl";
import { ShimmerLoadder } from "./Loader";
const ReactPoll: React.FunctionComponent<IReactPollProps> = (props) => {
const {
isLoading,
isSubmitting,
questions,
getQuestion,
submitAnswer,
setQuestions,
} = useGetData(props.context, props.userEmail, props.webServerRelativeUrl);
useEffect(() => {
//Get Question
getQuestion()
.then(() => {
return;
})
.catch((e) => {
console.log(e);
});
}, []);
//Submit Answer
const handleSubmitClick = (question: IQuestion): void => {
submitAnswer(question.id, question.selectedOption, props.userEmail)
.then(() => {
return;
})
.catch((e) => {
console.log(e);
});
};
//Change Selection
const chnageSelectidOption = (
ev: React.FormEvent<HTMLElement | HTMLInputElement>,
option: IChoiceGroupOption,
questionId: number
): void => {
const updatedQuestions = questions.map((question: IQuestion) => {
if (question.id === questionId) {
return { ...question, selectedOption: option.key };
}
return question;
});
setQuestions(updatedQuestions);
};
return (
<>
{/* Show Loadder while Loading Question */}
{isLoading && <ShimmerLoadder />}
{/* Show Chart if Current User already gave answer */}
{questions &&
questions.length > 0 &&
questions.map((question) => (
<div key={question.id}>
{question.answer.isCurrentUserAnswered && (
<React.Fragment key={question.id}>
<div className={styles["ms-Grid"]} dir="ltr">
<div className={styles["ms-Grid-row"]}>
<div
className={` ${styles["ms-Grid-col"]} ${styles["ms-sm12"]} ${styles["ms-font-m-plus"]} ${styles["ms-fontWeight-bold"]} `}
>
{question.question}
</div>
</div>
<div
className={`${styles["ms-Grid-row"]} ${styles.chartRow}`}
>
<div
className={` ${styles["ms-Grid-col"]} ${styles["ms-sm12"]} ${styles["ms-md12"]} ${styles["ms-lg6"]} `}
>
<ChartControl
type={ChartType.Pie}
data={{
labels: question.options
.filter((i) => i !== null)
.map((i) => i?.text),
datasets: [
{
label: question.question,
data: question.answer.allAnswers,
},
],
}}
options={{
Animation: false,
legend: {
display: true,
position: "right",
},
title: {
display: false,
},
}}
/>
</div>
</div>
</div>
</React.Fragment>
)}
{/* Show Question with Options if Current User already didn't give answer */}
{!question.answer.isCurrentUserAnswered && (
<React.Fragment key={question.id}>
<div className={styles["ms-Grid"]} dir="ltr">
<div className={styles["ms-Grid-row"]}>
<div
className={` ${styles["ms-Grid-col"]} ${styles["ms-sm12"]} `}
>
<ChoiceGroup
options={question.options.filter((i) => i !== null)}
label={question.question}
onChange={(e, selectedOption) =>
chnageSelectidOption(e, selectedOption, question.id)
}
/>
</div>
</div>
<div
className={` ${styles["ms-Grid-row"]} ${styles.submitButtonRow}`}
>
<div
className={` ${styles["ms-Grid-col"]} ${styles["ms-sm12"]} `}
>
<PrimaryButton
text="Submit"
disabled={
question.selectedOption === undefined || isSubmitting
}
onClick={() => handleSubmitClick(question)}
/>
</div>
</div>
</div>
</React.Fragment>
)}
</div>
))}
</>
);
};
export default ReactPoll;

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 IReactPollWebPartStrings {
PropertyPaneDescription: string;
BasicGroupName: string;
DescriptionFieldLabel: string;
AppLocalEnvironmentSharePoint: string;
AppLocalEnvironmentTeams: string;
AppLocalEnvironmentOffice: string;
AppLocalEnvironmentOutlook: string;
AppSharePointEnvironment: string;
AppTeamsTabEnvironment: string;
AppOfficeEnvironment: string;
AppOutlookEnvironment: string;
}
declare module 'ReactPollWebPartStrings' {
const strings: IReactPollWebPartStrings;
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": true,
"typeRoots": [
"./node_modules/@types",
"./node_modules/@microsoft"
],
"types": [
"webpack-env"
],
"lib": [
"es5",
"dom",
"es2015.collection",
"es2015.promise"
]
},
"include": [
"src/**/*.ts",
"src/**/*.tsx"
]
}