🎉 - Added sample [react-modern-version-history-extension]
This commit is contained in:
parent
5459dd34de
commit
f373ad28a3
|
@ -0,0 +1,39 @@
|
|||
// For more information on how to run this SPFx project in a VS Code Remote Container, please visit https://aka.ms/spfx-devcontainer
|
||||
{
|
||||
"name": "SPFx 1.17.4",
|
||||
"image": "docker.io/m365pnp/spfx:1.17.4",
|
||||
// Set *default* container specific settings.json values on container create.
|
||||
"settings": {},
|
||||
// Add the IDs of extensions you want installed when the container is created.
|
||||
"extensions": [
|
||||
"editorconfig.editorconfig",
|
||||
"dbaeumer.vscode-eslint"
|
||||
],
|
||||
// Use 'forwardPorts' to make a list of ports inside the container available locally.
|
||||
"forwardPorts": [
|
||||
4321,
|
||||
35729
|
||||
],
|
||||
"portsAttributes": {
|
||||
"4321": {
|
||||
"protocol": "https",
|
||||
"label": "Manifest",
|
||||
"onAutoForward": "silent",
|
||||
"requireLocalPort": true
|
||||
},
|
||||
// Not needed for SPFx>= 1.12.1
|
||||
// "5432": {
|
||||
// "protocol": "https",
|
||||
// "label": "Workbench",
|
||||
// "onAutoForward": "silent"
|
||||
// },
|
||||
"35729": {
|
||||
"protocol": "https",
|
||||
"label": "LiveReload",
|
||||
"onAutoForward": "silent",
|
||||
"requireLocalPort": true
|
||||
}
|
||||
},
|
||||
"postCreateCommand": "bash .devcontainer/spfx-startup.sh",
|
||||
"remoteUser": "node"
|
||||
}
|
|
@ -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**********"
|
|
@ -0,0 +1,352 @@
|
|||
require('@rushstack/eslint-config/patch/modern-module-resolution');
|
||||
module.exports = {
|
||||
extends: ['@microsoft/eslint-config-spfx/lib/profiles/default'],
|
||||
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: {}
|
||||
}
|
||||
]
|
||||
};
|
|
@ -0,0 +1,34 @@
|
|||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
|
||||
# Dependency directories
|
||||
node_modules
|
||||
|
||||
# Build generated files
|
||||
dist
|
||||
lib
|
||||
release
|
||||
solution
|
||||
temp
|
||||
*.sppkg
|
||||
.heft
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# OSX
|
||||
.DS_Store
|
||||
|
||||
# Visual Studio files
|
||||
.ntvs_analysis.dat
|
||||
.vs
|
||||
bin
|
||||
obj
|
||||
|
||||
# Resx Generated Code
|
||||
*.resx.ts
|
||||
|
||||
# Styles Generated Code
|
||||
*.scss.ts
|
|
@ -0,0 +1,16 @@
|
|||
!dist
|
||||
config
|
||||
|
||||
gulpfile.js
|
||||
|
||||
release
|
||||
src
|
||||
temp
|
||||
|
||||
tsconfig.json
|
||||
tslint.json
|
||||
|
||||
*.log
|
||||
|
||||
.yo-rc.json
|
||||
.vscode
|
|
@ -0,0 +1,22 @@
|
|||
{
|
||||
"@microsoft/generator-sharepoint": {
|
||||
"plusBeta": false,
|
||||
"isCreatingSolution": true,
|
||||
"nodeVersion": "16.20.0",
|
||||
"sdksVersions": {
|
||||
"@microsoft/microsoft-graph-client": "3.0.2",
|
||||
"@microsoft/teams-js": "2.9.1"
|
||||
},
|
||||
"version": "1.17.4",
|
||||
"libraryName": "better-version-history",
|
||||
"libraryId": "fb423a64-9c98-42de-b873-e2fe1231e30a",
|
||||
"environment": "spo",
|
||||
"packageManager": "npm",
|
||||
"solutionName": "Better-version-history",
|
||||
"solutionShortDescription": "Better-version-history description",
|
||||
"skipFeatureDeployment": true,
|
||||
"isDomainIsolated": false,
|
||||
"componentType": "extension",
|
||||
"extensionType": "ListViewCommandSet"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,99 @@
|
|||
# Modern Version History for SharePoint
|
||||
|
||||
## Summary
|
||||
|
||||
A modern UI version of the traditional version history page for SharePoint lists and libraries. The web part is built using React and PnPjs.
|
||||
|
||||
![moderversionhistory](./assets//Demo.gif)
|
||||
|
||||
## Features
|
||||
|
||||
- [x] Modern UI of the traditional version history
|
||||
- [x] See who changed what, and when
|
||||
- [x] Filter by date range
|
||||
- [x] Filter by user
|
||||
- [x] Compare two different versions
|
||||
- [x] Restore a previous version
|
||||
- [x] Delete a previous version
|
||||
- [x] View the full version
|
||||
- [x] Approver (and comments)
|
||||
|
||||
Uses 'react-vertical-timeline-component' for an awesome timeline view.
|
||||
|
||||
## Compatibility
|
||||
|
||||
| :warning: Important |
|
||||
| :-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node. |
|
||||
| Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
|
||||
|
||||
This sample is optimally compatible with the following environment configuration:
|
||||
|
||||
![SPFx 1.17.4](https://img.shields.io/badge/SPFx-1.17.4-green.svg)
|
||||
![Node.js v16](https://img.shields.io/badge/Node.js-v16-green.svg)
|
||||
![Compatible with SharePoint Online](https://img.shields.io/badge/SharePoint%20Online-Compatible-green.svg)
|
||||
![Does not work with SharePoint 2019](https://img.shields.io/badge/SharePoint%20Server%202019-Incompatible-red.svg "SharePoint Server 2019 requires SPFx 1.4.1 or lower")
|
||||
![Does not work with SharePoint 2016 (Feature Pack 2)](https://img.shields.io/badge/SharePoint%20Server%202016%20(Feature%20Pack%202)-Incompatible-red.svg "SharePoint Server 2016 Feature Pack 2 requires SPFx 1.1")
|
||||
![Local Workbench Unsupported](https://img.shields.io/badge/Local%20Workbench-Unsupported-red.svg "Local workbench is no longer available as of SPFx 1.13 and above")
|
||||
![Hosted Workbench Compatible](https://img.shields.io/badge/Hosted%20Workbench-Compatible-green.svg)
|
||||
![Compatible with Remote Containers](https://img.shields.io/badge/Remote%20Containers-Not%20Tested-yellow.svg)
|
||||
|
||||
For more information about SPFx compatibility, please refer to https://aka.ms/spfx-matrix
|
||||
|
||||
## Contributors
|
||||
|
||||
* [Dan Toft](https://github.com/Tanddant)
|
||||
* [Emanuele Bartolesi](https://github.com/kasuken)
|
||||
* [Tobias Maestrini](https://twitter.com/tmaestrini)
|
||||
|
||||
|
||||
## Version history
|
||||
|
||||
| Version | Date | Comments |
|
||||
| ------- | --------------- | --------------- |
|
||||
| 1.0 | September 1, 2023 | Initial release |
|
||||
|
||||
## Prerequisites
|
||||
|
||||
A SharePoint Tenant with list or library with versioning enabled.
|
||||
|
||||
## 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-modern-version-history) then unzip it)
|
||||
* From your command line, change your current directory to the directory containing this sample (`react-modern-version-history`, located under `samples`)
|
||||
* in the command line run:
|
||||
* `npm install`
|
||||
* `gulp serve`
|
||||
|
||||
> This sample can also be opened with [VS Code Remote Development](https://code.visualstudio.com/docs/remote/remote-overview). Visit <https://aka.ms/spfx-devcontainer> for further instructions.
|
||||
**
|
||||
|
||||
## How to run the solution locally
|
||||
|
||||
- Clone this repository
|
||||
- Ensure that you are in the solution folder
|
||||
- in the command-line run:
|
||||
- **npm install**
|
||||
- **gulp serve**
|
||||
|
||||
## Help
|
||||
|
||||
We do not support samples, but this community is always willing to help, and we want to improve these samples. We use GitHub to track issues, which makes it easy for community members to volunteer their time and help resolve issues.
|
||||
|
||||
If you're having issues building the solution, please run [spfx doctor](https://pnp.github.io/cli-microsoft365/cmd/spfx/spfx-doctor/) from within the solution folder to diagnose incompatibility issues with your environment.
|
||||
|
||||
You can try looking at [issues related to this sample](https://github.com/pnp/sp-dev-fx-webparts/issues?q=label%3A%22sample%3A%20react-modern-version-history%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-modern-version-history) and see what the community is saying.
|
||||
|
||||
If you encounter any issues using this sample, [create a new issue](https://github.com/pnp/sp-dev-fx-webparts/issues/new?assignees=&labels=Needs%3A+Triage+%3Amag%3A%2Ctype%3Abug-suspected%2Csample%3A%20react-modern-version-history&template=bug-report.yml&sample=react-modern-version-history&authors=@Tanddant&title=react-modern-version-history%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-modern-version-history&template=question.yml&sample=react-modern-version-history&authors=@Tanddant&title=react-modern-version-history%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-modern-version-history&template=suggestion.yml&sample=react-modern-version-history&authors=@Tanddant&title=react-modern-version-history%20-%20).
|
||||
|
||||
## Disclaimer
|
||||
|
||||
**THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.**
|
||||
|
||||
<img src="https://m365-visitor-stats.azurewebsites.net/sp-dev-fx-webparts/samples/react-modern-version-history" />
|
Binary file not shown.
After Width: | Height: | Size: 8.2 MiB |
Binary file not shown.
After Width: | Height: | Size: 2.7 MiB |
|
@ -0,0 +1,60 @@
|
|||
[
|
||||
{
|
||||
"name": "pnp-sp-dev-spfx-web-parts-react-modern-version-history",
|
||||
"source": "pnp",
|
||||
"title": "Modern Version History",
|
||||
"shortDescription": "An extension modernizing the version history experience in SharePoint Online.",
|
||||
"url": "https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-modern-version-history",
|
||||
"downloadUrl": "https://pnp.github.io/download-partial/?url=https://github.com/pnp/sp-dev-fx-webparts/tree/main/samples/react-modern-version-history",
|
||||
"longDescription": [
|
||||
"This is an extension of the version history experience in SharePoint Online. It allows you to see the version history of a file in a modern experience, compare different versions, and restore a previous version."
|
||||
],
|
||||
"creationDateTime": "2023-09-01",
|
||||
"updateDateTime": "2023-09-01",
|
||||
"products": [
|
||||
"SharePoint"
|
||||
],
|
||||
"metadata": [
|
||||
{
|
||||
"key": "CLIENT-SIDE-DEV",
|
||||
"value": "React"
|
||||
},
|
||||
{
|
||||
"key": "SPFX-VERSION",
|
||||
"value": "1.17.4"
|
||||
}
|
||||
],
|
||||
"thumbnails": [
|
||||
{
|
||||
"type": "image",
|
||||
"order": 100,
|
||||
"url": "https://github.com/pnp/sp-dev-fx-webparts/raw/main/samples/react-modern-version-history/assets/Demo.gif",
|
||||
"alt": "Web Part Preview"
|
||||
}
|
||||
],
|
||||
"authors": [
|
||||
{
|
||||
"gitHubAccount": "Tanddant",
|
||||
"pictureUrl": "https://github.com/Tanddant.png",
|
||||
"name": "Dan Toft"
|
||||
},
|
||||
{
|
||||
"gitHubAccount": "kasuken",
|
||||
"pictureUrl": "https://github.com/kasuken.png",
|
||||
"name": "Emanuele Bartolesi"
|
||||
},
|
||||
{
|
||||
"gitHubAccount": "tmaestrini",
|
||||
"pictureUrl": "https://github.com/tmaestrini.png",
|
||||
"name": "Tobias Maestrini"
|
||||
}
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"name": "Build your first SharePoint client-side web part",
|
||||
"description": "Client-side web parts are client-side components that run in the context of a SharePoint page. Client-side web parts can be deployed to SharePoint environments that support the SharePoint Framework. You can also use modern JavaScript web frameworks, tools, and libraries to build them.",
|
||||
"url": "https://docs.microsoft.com/en-us/sharepoint/dev/spfx/web-parts/get-started/build-a-hello-world-web-part"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
|
||||
"version": "2.0",
|
||||
"bundles": {
|
||||
"better-version-history-command-set": {
|
||||
"components": [
|
||||
{
|
||||
"entrypoint": "./lib/extensions/betterVersionHistory/BetterVersionHistoryCommandSet.js",
|
||||
"manifest": "./src/extensions/betterVersionHistory/BetterVersionHistoryCommandSet.manifest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"externals": {},
|
||||
"localizedResources": {
|
||||
"BetterVersionHistoryCommandSetStrings": "lib/extensions/betterVersionHistory/loc/{locale}.js",
|
||||
"ControlStrings": "node_modules/@pnp/spfx-controls-react/lib/loc/{locale}.js"
|
||||
}
|
||||
}
|
|
@ -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": "better-version-history",
|
||||
"accessKey": "<!-- ACCESS KEY -->"
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
|
||||
"solution": {
|
||||
"name": "better-version-history-client-side-solution",
|
||||
"id": "fb423a64-9c98-42de-b873-e2fe1231e30a",
|
||||
"version": "1.0.0.0",
|
||||
"includeClientSideAssets": true,
|
||||
"skipFeatureDeployment": true,
|
||||
"isDomainIsolated": false,
|
||||
"developer": {
|
||||
"name": "",
|
||||
"websiteUrl": "",
|
||||
"privacyUrl": "",
|
||||
"termsOfUseUrl": "",
|
||||
"mpnId": "Undefined-1.17.4"
|
||||
},
|
||||
"metadata": {
|
||||
"shortDescription": {
|
||||
"default": "Better-version-history description"
|
||||
},
|
||||
"longDescription": {
|
||||
"default": "Better-version-history description"
|
||||
},
|
||||
"screenshotPaths": [],
|
||||
"videoUrl": "",
|
||||
"categories": []
|
||||
},
|
||||
"features": [
|
||||
{
|
||||
"title": "Application Extension - Deployment of custom action",
|
||||
"description": "Deploys a custom action with ClientSideComponentId association",
|
||||
"id": "8c693715-7adc-4a43-9dbd-24f386cc9b59",
|
||||
"version": "1.0.0.0",
|
||||
"assets": {
|
||||
"elementManifests": [
|
||||
"elements.xml",
|
||||
"ClientSideInstance.xml"
|
||||
]
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"paths": {
|
||||
"zippedPackage": "solution/better-version-history.sppkg"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
|
||||
}
|
|
@ -0,0 +1,27 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/spfx-serve.schema.json",
|
||||
"port": 4321,
|
||||
"https": true,
|
||||
"serveConfigurations": {
|
||||
"default": {
|
||||
"pageUrl": "https://{tenantDomain}/SitePages/myPage.aspx",
|
||||
"customActions": {
|
||||
"4dc2355b-e74a-4cac-9e4a-cf1cc28ef90c": {
|
||||
"location": "ClientSideExtension.ListViewCommandSet.ContextMenu",
|
||||
"properties": {
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"betterVersionHistory": {
|
||||
"pageUrl": "https://{tenantDomain}/SitePages/myPage.aspx",
|
||||
"customActions": {
|
||||
"4dc2355b-e74a-4cac-9e4a-cf1cc28ef90c": {
|
||||
"location": "ClientSideExtension.ListViewCommandSet.ContextMenu",
|
||||
"properties": {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
|
||||
"cdnBasePath": "<!-- PATH TO CDN -->"
|
||||
}
|
|
@ -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'));
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,45 @@
|
|||
{
|
||||
"name": "better-version-history",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"engines": {
|
||||
"node": ">=16.13.0 <17.0.0"
|
||||
},
|
||||
"main": "lib/index.js",
|
||||
"scripts": {
|
||||
"build": "gulp bundle",
|
||||
"clean": "gulp clean",
|
||||
"test": "gulp test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fluentui/react": "^7.204.0",
|
||||
"@microsoft/decorators": "1.17.4",
|
||||
"@microsoft/generator-sharepoint": "1.17.4",
|
||||
"@microsoft/sp-core-library": "1.17.4",
|
||||
"@microsoft/sp-dialog": "1.17.4",
|
||||
"@microsoft/sp-listview-extensibility": "1.17.4",
|
||||
"@pnp/graph": "^3.17.0",
|
||||
"@pnp/sp": "^3.17.0",
|
||||
"@pnp/spfx-controls-react": "3.15.0",
|
||||
"@types/react": "17.0.45",
|
||||
"@types/react-dom": "17.0.17",
|
||||
"react": "17.0.1",
|
||||
"react-dom": "17.0.1",
|
||||
"react-vertical-timeline-component": "^3.6.0",
|
||||
"tslib": "2.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@microsoft/eslint-config-spfx": "1.17.4",
|
||||
"@microsoft/eslint-plugin-spfx": "1.17.4",
|
||||
"@microsoft/rush-stack-compiler-4.5": "0.5.0",
|
||||
"@microsoft/sp-build-web": "1.17.4",
|
||||
"@microsoft/sp-module-interfaces": "1.17.4",
|
||||
"@rushstack/eslint-config": "2.5.1",
|
||||
"@types/react-vertical-timeline-component": "^3.3.3",
|
||||
"@types/webpack-env": "~1.15.2",
|
||||
"ajv": "^6.12.5",
|
||||
"eslint": "8.7.0",
|
||||
"gulp": "4.0.2",
|
||||
"typescript": "4.5.5"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
|
||||
<ClientSideComponentInstance
|
||||
Title="BetterVersionHistory"
|
||||
Location="ClientSideExtension.ListViewCommandSet.ContextMenu"
|
||||
ListTemplateId="100"
|
||||
Properties="{}"
|
||||
ComponentId="4dc2355b-e74a-4cac-9e4a-cf1cc28ef90c" />
|
||||
<ClientSideComponentInstance
|
||||
Title="BetterVersionHistory"
|
||||
Location="ClientSideExtension.ListViewCommandSet.ContextMenu"
|
||||
ListTemplateId="101"
|
||||
Properties="{}"
|
||||
ComponentId="4dc2355b-e74a-4cac-9e4a-cf1cc28ef90c" />
|
||||
</Elements>
|
|
@ -0,0 +1,19 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
|
||||
<CustomAction
|
||||
Title="BetterVersionHistory"
|
||||
RegistrationId="100"
|
||||
RegistrationType="List"
|
||||
Location="ClientSideExtension.ListViewCommandSet.ContextMenu"
|
||||
ClientSideComponentId="4dc2355b-e74a-4cac-9e4a-cf1cc28ef90c"
|
||||
ClientSideComponentProperties="{}">
|
||||
</CustomAction>
|
||||
<CustomAction
|
||||
Title="BetterVersionHistory"
|
||||
RegistrationId="101"
|
||||
RegistrationType="List"
|
||||
Location="ClientSideExtension.ListViewCommandSet.ContextMenu"
|
||||
ClientSideComponentId="4dc2355b-e74a-4cac-9e4a-cf1cc28ef90c"
|
||||
ClientSideComponentProperties="{}">
|
||||
</CustomAction>
|
||||
</Elements>
|
|
@ -0,0 +1,21 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx/command-set-extension-manifest.schema.json",
|
||||
|
||||
"id": "4dc2355b-e74a-4cac-9e4a-cf1cc28ef90c",
|
||||
"alias": "BetterVersionHistoryCommandSet",
|
||||
"componentType": "Extension",
|
||||
"extensionType": "ListViewCommandSet",
|
||||
|
||||
"version": "*",
|
||||
"manifestVersion": 2,
|
||||
|
||||
"requiresCustomScript": false,
|
||||
|
||||
"items": {
|
||||
"COMMAND_1": {
|
||||
"title": { "default": "✨ Modern version history ✨" },
|
||||
"type": "command",
|
||||
"iconImageUrl": "data:image/svg+xml,%3Csvg xmlns%3D'http%3A//www.w3.org/2000/svg' viewBox='0 0 2048 2048'%3E%3Cpath d='M896 512h128v512H896V512zM512 768H0V256h128v274q67-123 163-221t212-166T752 37t272-37q141 0 272 36t245 103 207 160 160 208 103 245 37 272h-128q0-123-32-237t-90-214-141-182-181-140-214-91-238-32q-129 0-251 36T546 267 355 428 215 640h297v128zm512 384h1024v128H1024v-128zm0 384h1024v128H1024v-128zm0 384h1024v128H1024v-128zm-863-657q36 129 105 239t166 194 214 140 250 74v130q-154-21-292-83t-250-158-193-224-123-278l123-34z' fill='%23333333'%3E%3C/path%3E%3C/svg%3E"
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,62 @@
|
|||
import { Log } from '@microsoft/sp-core-library';
|
||||
import {
|
||||
BaseListViewCommandSet,
|
||||
Command,
|
||||
IListViewCommandSetExecuteEventParameters,
|
||||
ListViewStateChangedEventArgs
|
||||
} from '@microsoft/sp-listview-extensibility';
|
||||
import { BetterVersionHistory, IBetterVersionHistoryProps } from './components/BetterVersionHistory';
|
||||
import DialogWrapper from './components/DialogWrapper';
|
||||
import * as React from 'react';
|
||||
import { getThemeColor } from './themeHelper';
|
||||
import { DataProvider } from './providers/DataProvider';
|
||||
import { SPFxContext } from './contexts/SPFxContext';
|
||||
|
||||
export interface IBetterVersionHistoryCommandSetProperties { }
|
||||
|
||||
const LOG_SOURCE: string = 'BetterVersionHistoryCommandSet';
|
||||
|
||||
export default class BetterVersionHistoryCommandSet extends BaseListViewCommandSet<IBetterVersionHistoryCommandSetProperties> {
|
||||
|
||||
public onInit(): Promise<void> {
|
||||
Log.info(LOG_SOURCE, 'Initialized BetterVersionHistoryCommandSet');
|
||||
|
||||
// initial state of the command's visibility
|
||||
const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
|
||||
compareOneCommand.visible = false;
|
||||
|
||||
const fillColor = getThemeColor("themeDarkAlt").replace('#', '%23');
|
||||
const exportSvg = `data:image/svg+xml,%3Csvg xmlns%3D'http%3A//www.w3.org/2000/svg' viewBox='0 0 2048 2048'%3E%3Cpath d='M896 512h128v512H896V512zM512 768H0V256h128v274q67-123 163-221t212-166T752 37t272-37q141 0 272 36t245 103 207 160 160 208 103 245 37 272h-128q0-123-32-237t-90-214-141-182-181-140-214-91-238-32q-129 0-251 36T546 267 355 428 215 640h297v128zm512 384h1024v128H1024v-128zm0 384h1024v128H1024v-128zm0 384h1024v128H1024v-128zm-863-657q36 129 105 239t166 194 214 140 250 74v130q-154-21-292-83t-250-158-193-224-123-278l123-34z' fill='${fillColor}'%3E%3C/path%3E%3C/svg%3E`;
|
||||
compareOneCommand.iconImageUrl = exportSvg;
|
||||
|
||||
this.context.listView.listViewStateChangedEvent.add(this, this._onListViewStateChanged);
|
||||
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
public onExecute(event: IListViewCommandSetExecuteEventParameters): void {
|
||||
switch (event.itemId) {
|
||||
case 'COMMAND_1': {
|
||||
const element = React.createElement(BetterVersionHistory, { provider: new DataProvider(this.context) } as IBetterVersionHistoryProps);
|
||||
const context = React.createElement(SPFxContext.Provider, { value: { context: this.context } }, element);
|
||||
const wrapper = new DialogWrapper(context);
|
||||
wrapper.show().catch(er => alert(er));
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw new Error('Unknown command');
|
||||
}
|
||||
}
|
||||
|
||||
private _onListViewStateChanged = (args: ListViewStateChangedEventArgs): void => {
|
||||
Log.info(LOG_SOURCE, 'List view state changed');
|
||||
|
||||
const compareOneCommand: Command = this.tryGetCommand('COMMAND_1');
|
||||
if (compareOneCommand) {
|
||||
// This command should be hidden unless exactly one row is selected.
|
||||
compareOneCommand.visible = this.context.listView.selectedRows?.length === 1;
|
||||
}
|
||||
|
||||
this.raiseOnChange();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
:root {
|
||||
div.ms-CommandBar {
|
||||
background-color: unset;
|
||||
}
|
||||
|
||||
@media screen and (min-width: 1170px) {
|
||||
.vertical-timeline {
|
||||
width: 100%;
|
||||
padding: 0;
|
||||
|
||||
.vertical-timeline-element {
|
||||
margin: 2em 0;
|
||||
}
|
||||
|
||||
.vertical-timeline-element-content {
|
||||
margin-left: 0px;
|
||||
}
|
||||
|
||||
.vertical-timeline-element-date {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.version {
|
||||
border: 1px solid lightgrey;
|
||||
width: fit-content;
|
||||
background-color: white;
|
||||
height: 26px;
|
||||
padding: 0 4px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,86 @@
|
|||
import * as React from 'react';
|
||||
import { CommandBar, DatePicker, DialogContent, PersonaSize, Spinner, SpinnerSize, Stack } from '@fluentui/react';
|
||||
import { IDataProvider } from '../providers/DataProvider';
|
||||
import { Version } from './Version';
|
||||
import useVersions from '../hooks/useVersion';
|
||||
import { IVersionsFilter } from '../models/IVersionsFilter';
|
||||
import useObject from '../hooks/useObject';
|
||||
import useFileInfo from '../hooks/useFileInfo';
|
||||
import { PeoplePicker } from './PeoplePicker';
|
||||
import { VerticalTimeline, VerticalTimelineElement } from 'react-vertical-timeline-component';
|
||||
import 'react-vertical-timeline-component/style.min.css';
|
||||
import styles from './BetterVersionHistory.module.scss';
|
||||
import { FieldUser } from './FieldUserPerson';
|
||||
|
||||
export interface IBetterVersionHistoryProps {
|
||||
provider: IDataProvider;
|
||||
}
|
||||
|
||||
export const BetterVersionHistory: React.FunctionComponent<IBetterVersionHistoryProps> = (props: React.PropsWithChildren<IBetterVersionHistoryProps>) => {
|
||||
const [filters, setFilters] = useObject<IVersionsFilter>({});
|
||||
const { versions, isLoading: isLoadingVersions } = useVersions(props.provider, filters)
|
||||
const { fileInfo } = useFileInfo(props.provider);
|
||||
const [selectedVersions, setSelectedVersions] = React.useState<number[]>([]);
|
||||
|
||||
|
||||
if (isLoadingVersions) return (<Spinner label='Loading versions...' size={SpinnerSize.large} />);
|
||||
return (
|
||||
<DialogContent styles={{ content: { maxHeight: "60vh", width: "60vw", overflowY: "scroll" } }} title={fileInfo?.Name ?? 'Modern version history'}>
|
||||
<CommandBar
|
||||
items={[
|
||||
{
|
||||
key: "ShowSelectedVersions",
|
||||
text: 'Compare selected versions',
|
||||
disabled: selectedVersions.length === 0,
|
||||
iconProps: { iconName: 'BranchCompare' },
|
||||
onClick: () => { setFilters({ VersionNumbers: selectedVersions }) }
|
||||
}, {
|
||||
key: "ClearSelectedVersions",
|
||||
text: "Clear selection",
|
||||
disabled: selectedVersions.length === 0,
|
||||
iconProps: { iconName: 'Clear' },
|
||||
onClick: () => { setSelectedVersions([]), setFilters({ VersionNumbers: [] }) }
|
||||
}
|
||||
]}
|
||||
/>
|
||||
<Stack horizontal tokens={{ childrenGap: 10 }}>
|
||||
<DatePicker label='Start date' value={filters.StartDate} onSelectDate={date => setFilters({ StartDate: date })} styles={{ root: { flexGrow: 1 } }} />
|
||||
<DatePicker label='End date' value={filters.EndDate} onSelectDate={date => setFilters({ EndDate: date })} styles={{ root: { flexGrow: 1 } }} />
|
||||
<Stack styles={{ root: { flexGrow: 1 } }}>
|
||||
<PeoplePicker versions={versions} onContributorSelected={(userPersonaProps) => setFilters({ Author: userPersonaProps })} />
|
||||
</Stack>
|
||||
</Stack>
|
||||
|
||||
<Stack>
|
||||
<VerticalTimeline layout='1-column' animate={false} lineColor='#eaeaea' className={styles['vertical-timeline']}>
|
||||
{versions.map((version) =>
|
||||
<VerticalTimelineElement
|
||||
className={styles['vertical-timeline-element']}
|
||||
contentStyle={{ background: '#eaeaea', boxShadow: 'none' }}
|
||||
contentArrowStyle={{ borderRight: '7px solid #eaeaea' }}
|
||||
iconStyle={{ background: "#eaeaea", color: "#fff" }}
|
||||
dateClassName={styles['vertical-timeline-element-date']}
|
||||
icon={<FieldUser size={PersonaSize.size40} user={version.Author} hidePersonaDetails />}
|
||||
>
|
||||
<Version
|
||||
Version={version}
|
||||
className={styles['vertical-timeline-element-content']}
|
||||
selectedVersions={selectedVersions}
|
||||
onVersionSelected={() => {
|
||||
if (selectedVersions.indexOf(version.VersionId) > -1) {
|
||||
setSelectedVersions(selectedVersions.filter(v => v !== version.VersionId));
|
||||
} else {
|
||||
setSelectedVersions([...selectedVersions, version.VersionId]);
|
||||
}
|
||||
}}
|
||||
provider={props.provider}
|
||||
reloadVersions={() => { setFilters({}) }}
|
||||
/>
|
||||
</VerticalTimelineElement>
|
||||
)}
|
||||
</VerticalTimeline>
|
||||
</Stack>
|
||||
|
||||
</DialogContent>
|
||||
);
|
||||
};
|
|
@ -0,0 +1,24 @@
|
|||
import * as React from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
import { BaseDialog } from '@microsoft/sp-dialog';
|
||||
|
||||
export default class DialogWrapper<T> extends BaseDialog {
|
||||
private element: React.FunctionComponentElement<T> = null;
|
||||
|
||||
constructor(element: React.FunctionComponentElement<T>) {
|
||||
super({ isBlocking: false });
|
||||
this.element = element;
|
||||
}
|
||||
|
||||
public render(): void {
|
||||
ReactDOM.render(this.element, this.domElement);
|
||||
}
|
||||
|
||||
protected onAfterClose(): void {
|
||||
super.onAfterClose();
|
||||
|
||||
// Clean up the element for the next dialog
|
||||
ReactDOM.unmountComponentAtNode(this.domElement);
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
import * as React from 'react';
|
||||
import { IFieldUserValue } from '../models/FieldValues';
|
||||
import { Persona, PersonaSize } from '@fluentui/react';
|
||||
import { LivePersona } from "@pnp/spfx-controls-react/lib/LivePersona";
|
||||
import { SPFxContext } from '../contexts/SPFxContext';
|
||||
|
||||
export interface IFieldUserProps {
|
||||
user: IFieldUserValue;
|
||||
size?: PersonaSize;
|
||||
hidePersonaDetails?: boolean;
|
||||
}
|
||||
|
||||
export const FieldUser: React.FunctionComponent<IFieldUserProps> = (props: React.PropsWithChildren<IFieldUserProps>) => {
|
||||
const { user, size } = props;
|
||||
const { context } = React.useContext(SPFxContext)
|
||||
|
||||
return (
|
||||
<>
|
||||
<LivePersona upn={user.Email}
|
||||
template={
|
||||
<>
|
||||
<Persona
|
||||
size={size ?? PersonaSize.size32}
|
||||
hidePersonaDetails={props.hidePersonaDetails}
|
||||
text={user.LookupValue}
|
||||
secondaryText={user.Email}
|
||||
showInitialsUntilImageLoads={true}
|
||||
imageUrl={`/_layouts/15/userphoto.aspx?Size=M&AccountName=${user.Email}`}
|
||||
/>
|
||||
</>
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
serviceScope={context.serviceScope as any}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
|
@ -0,0 +1,48 @@
|
|||
import { Stack, Label, CompactPeoplePicker, IPersonaProps, IBasePickerSuggestionsProps } from "@fluentui/react";
|
||||
import * as React from "react";
|
||||
import useFileContributors from "../hooks/useFileContributors";
|
||||
import { IVersion } from "../models/IVersion";
|
||||
|
||||
export interface IPeoplePickerProps {
|
||||
versions?: IVersion[];
|
||||
onContributorSelected: (user: IPersonaProps) => void;
|
||||
}
|
||||
|
||||
export const PeoplePicker: React.FunctionComponent<IPeoplePickerProps> = (props: React.PropsWithChildren<IPeoplePickerProps>) => {
|
||||
const [filteredContributor, setFilteredContributor] = React.useState<IPersonaProps>();
|
||||
const contributors = useFileContributors(filteredContributor, props.versions);
|
||||
|
||||
const suggestionProps: IBasePickerSuggestionsProps = {
|
||||
suggestionsHeaderText: 'Suggested People',
|
||||
mostRecentlyUsedHeaderText: 'Filter by Contacts',
|
||||
noResultsFoundText: 'No results found',
|
||||
loadingText: 'Loading',
|
||||
showRemoveButtons: true,
|
||||
suggestionsAvailableAlertText: 'People Picker Suggestions available',
|
||||
suggestionsContainerAriaLabel: 'Filter by contacts',
|
||||
};
|
||||
|
||||
return <>
|
||||
<Stack styles={{ root: { flexGrow: 1 } }}>
|
||||
<Label title='User'>Author / Editor</Label>
|
||||
<CompactPeoplePicker
|
||||
onResolveSuggestions={function (filter: string, selectedItems?: IPersonaProps[]): IPersonaProps[] | PromiseLike<IPersonaProps[]> {
|
||||
setFilteredContributor(selectedItems[0]);
|
||||
props.onContributorSelected(selectedItems[0]);
|
||||
return contributors;
|
||||
}}
|
||||
onChange={(items: IPersonaProps[]) => {
|
||||
setFilteredContributor(undefined);
|
||||
props.onContributorSelected(undefined);
|
||||
}}
|
||||
getTextFromItem={(persona: IPersonaProps): string => {
|
||||
return persona.text as string;
|
||||
}}
|
||||
itemLimit={1}
|
||||
pickerSuggestionsProps={suggestionProps}
|
||||
className={'ms-PeoplePicker'}
|
||||
resolveDelay={300}
|
||||
key={'normal'} />
|
||||
</Stack>
|
||||
</>
|
||||
}
|
|
@ -0,0 +1,122 @@
|
|||
import * as React from 'react';
|
||||
import { IVersion } from '../models/IVersion';
|
||||
import { FieldUser } from './FieldUserPerson';
|
||||
import { Icon, Text, TooltipHost, PersonaSize, Link, Checkbox, Stack, StackItem, ActionButton, IContextualMenuProps } from '@fluentui/react';
|
||||
import { FieldType } from '../models/FieldTypes';
|
||||
import { IFieldUrlValue, IFieldUserValue } from '../models/FieldValues';
|
||||
import { IDataProvider } from '../providers/DataProvider';
|
||||
import useVersionMetadata from '../hooks/useVersionMetadata';
|
||||
import styles from './BetterVersionHistory.module.scss';
|
||||
|
||||
export interface IVersionProps {
|
||||
Version: IVersion;
|
||||
className: string;
|
||||
selectedVersions?: number[];
|
||||
onVersionSelected?: () => void;
|
||||
provider: IDataProvider;
|
||||
reloadVersions: () => void;
|
||||
}
|
||||
|
||||
export const Version: React.FunctionComponent<IVersionProps> = (props: React.PropsWithChildren<IVersionProps>) => {
|
||||
const { Version, provider, reloadVersions } = props;
|
||||
const { versionMetadata } = useVersionMetadata(Version, provider);
|
||||
|
||||
const versionMenuProps: IContextualMenuProps = {
|
||||
items: [
|
||||
{
|
||||
key: 'version-view',
|
||||
text: 'View version',
|
||||
iconProps: { iconName: 'EntryView' },
|
||||
href: `${Version.VersionLink}`,
|
||||
target: '_blank',
|
||||
},
|
||||
{
|
||||
key: 'version-delete',
|
||||
text: 'Delete version',
|
||||
iconProps: { iconName: 'Delete' },
|
||||
onClick: () => {
|
||||
provider
|
||||
.DeleteVersion(Version.VersionId)
|
||||
.then(() => {
|
||||
reloadVersions();
|
||||
});
|
||||
},
|
||||
target: '_blank'
|
||||
},
|
||||
{
|
||||
key: 'version-restore',
|
||||
text: 'Restore version',
|
||||
iconProps: { iconName: 'UpdateRestore' },
|
||||
onClick: () => {
|
||||
provider
|
||||
.RestoreVersion(Version)
|
||||
.then(() => {
|
||||
reloadVersions();
|
||||
})
|
||||
},
|
||||
target: '_blank'
|
||||
},
|
||||
]
|
||||
};
|
||||
|
||||
const fileSize: number = ((versionMetadata as any)?.Size ?? 0) ? ((versionMetadata as any)?.Size ?? 0) / 1024 : Version.FileSize / 1024;
|
||||
const fileSizeText = fileSize > 10**3 ? `${(fileSize / 10**3).toFixed(2)} MB` : fileSize > 10**6 ? `${(fileSize / 10**6).toFixed(2)} GB` : `${fileSize.toFixed(2)} KB`;
|
||||
|
||||
return (
|
||||
<Stack tokens={{ childrenGap: 10 }} horizontal verticalAlign='start' >
|
||||
<StackItem
|
||||
style={{ paddingTop: '3px' }}
|
||||
children={<Checkbox checked={props.selectedVersions.indexOf(Version.VersionId) > -1} onChange={(e, checked) => props.onVersionSelected()} />} />
|
||||
<StackItem grow={1}>
|
||||
<Stack tokens={{ childrenGap: 15 }} horizontal styles={{ root: { paddingBottom: '10px' } }} verticalAlign='center'>
|
||||
<StackItem>
|
||||
<ActionButton className={styles.version} text={`Version ${Version.VersionName}`} menuProps={versionMenuProps} />
|
||||
</StackItem>
|
||||
<StackItem>
|
||||
<Text>{fileSizeText}</Text>
|
||||
</StackItem>
|
||||
{Version.Moderation &&
|
||||
<StackItem grow={2}>
|
||||
{Version.Moderation.ModerationStatus === 0 && <><Icon iconName="FileComment" style={{ color: 'darkgreen' }} title='Document approved' /> Approved</>}
|
||||
{Version.Moderation.ModerationStatus === 1 && <><Icon iconName="FileComment" style={{ color: 'darkred' }} title='Document approval rejected' /> Rejected</>}
|
||||
{Version.Moderation.ModerationStatus === 2 && <><Icon iconName="FileComment" title='Document approval pending' /> Pending</>}
|
||||
{Version.Moderation.ModerationComments && <Text variant='small'> · {Version.Moderation.ModerationComments}</Text>}
|
||||
</StackItem>
|
||||
}
|
||||
<StackItem grow={1} style={{ textAlign: 'right', lineHeight: '1em' }}>
|
||||
<Text variant='small'>{Version.Author.LookupValue}</Text><br />
|
||||
<Text variant='small'>{Version.TimeStamp.toLocaleString()}</Text>
|
||||
</StackItem>
|
||||
</Stack>
|
||||
{Version.Moderation &&
|
||||
<Stack>
|
||||
{versionMetadata?.CheckInComment &&
|
||||
<StackItem styles={{ root: { backgroundColor: 'lightgrey', borderRadius: 3, padding: '0.25em', width: '100%' } }}>
|
||||
<Icon iconName="PageCheckedin" title='Document Status Information' />
|
||||
<Text variant='medium'>{versionMetadata.CheckInComment}</Text>
|
||||
</StackItem>
|
||||
}
|
||||
</Stack>
|
||||
}
|
||||
<Stack>
|
||||
{Version.Changes && Version.Changes.map((change) => {
|
||||
switch (change.FieldType) {
|
||||
case FieldType.User:
|
||||
return <Text styles={{ root: { display: 'flex' } }}>{change.FieldName}: <FieldUser user={change.Data as IFieldUserValue} size={PersonaSize.size8} /></Text>
|
||||
case FieldType.UserMulti:
|
||||
return <Text styles={{ root: { display: 'flex' } }}>{change.FieldName}: {(change.Data as (IFieldUserValue[]) ?? []).map(user => <FieldUser user={user} size={PersonaSize.size8} />)} </Text>
|
||||
case FieldType.URL: {
|
||||
const link = change.Data as IFieldUrlValue;
|
||||
return <Text>{change.FieldName}: <Link href={link.Url} target='_blank'>{link.Description}</Link></Text>
|
||||
}
|
||||
case FieldType.Lookup:
|
||||
return <Text>{change.FieldName}: <Link href={change.Link} target='_blank'>{change.NewValue}</Link></Text>
|
||||
default:
|
||||
return <Text>{change.FieldName}: <TooltipHost content={change.OldValue}>{change.NewValue}</TooltipHost></Text>
|
||||
}
|
||||
})}
|
||||
</Stack>
|
||||
</StackItem>
|
||||
</Stack >
|
||||
);
|
||||
};
|
|
@ -0,0 +1,8 @@
|
|||
import { BaseComponentContext } from "@microsoft/sp-component-base";
|
||||
import * as React from "react";
|
||||
|
||||
export interface ISPFxContext {
|
||||
context: BaseComponentContext;
|
||||
}
|
||||
|
||||
export const SPFxContext = React.createContext<ISPFxContext>(null);
|
|
@ -0,0 +1,30 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { IVersion } from "../models/IVersion";
|
||||
import { IPersonaProps } from "@fluentui/react";
|
||||
|
||||
export default function useFileContributor(contributor: IPersonaProps, versions?: IVersion[]): IPersonaProps[] {
|
||||
const [contributors, setContributors] = useState<IPersonaProps[]>(undefined);
|
||||
|
||||
async function fetchContributors(): Promise<void> {
|
||||
let filteredContributors = versions;
|
||||
if (contributor) filteredContributors = filteredContributors
|
||||
.filter(v => v.Author.LookupValue.indexOf(contributor.text) !== -1 || v.Author.Email.indexOf(contributor.secondaryText) !== -1);
|
||||
|
||||
// Make distinct values
|
||||
const contributors = new Map<string, IPersonaProps>();
|
||||
filteredContributors.forEach(c => {
|
||||
contributors.set(c.Author.Email, { text: c.Author.LookupValue, secondaryText: c.Author.Email });
|
||||
});
|
||||
|
||||
// projection of Map to array due to missing spread operator function in current lib version
|
||||
const persona: IPersonaProps[] = [];
|
||||
contributors.forEach(c => persona.push(c));
|
||||
setContributors(persona);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchContributors();
|
||||
}, []);
|
||||
|
||||
return contributors;
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { IDataProvider } from "../providers/DataProvider";
|
||||
import { IFileInfo } from "@pnp/sp/files";
|
||||
|
||||
export default function useFileInfo(provider: IDataProvider): { fileInfo: IFileInfo } {
|
||||
const [selectedFile, setSelectedFile] = useState<IFileInfo>(undefined);
|
||||
|
||||
async function fetchFileInfo(): Promise<void> {
|
||||
const file = await provider.GetFileInfo();
|
||||
setSelectedFile(file);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchFileInfo();
|
||||
}, []);
|
||||
|
||||
return { fileInfo: selectedFile };
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
import { useState } from 'react';
|
||||
|
||||
export default function useObject<T>(initialValue: T): [T, (newValue: Partial<T>) => void] {
|
||||
const [value, setValue] = useState<T>(initialValue);
|
||||
const update: (newValue: Partial<T>) => void = (newValue: Partial<T>) => setValue({ ...value, ...newValue });
|
||||
return [value, update] as [T, (newValue: Partial<T>) => void];
|
||||
}
|
|
@ -0,0 +1,25 @@
|
|||
import { useState, useEffect } from 'react';
|
||||
import { IDataProvider } from '../providers/DataProvider';
|
||||
import { IVersion } from '../models/IVersion';
|
||||
import { IVersionsFilter } from '../models/IVersionsFilter';
|
||||
|
||||
export default function useVersions(provider: IDataProvider, filters: IVersionsFilter = {}): { versions: IVersion[], isLoading: boolean } {
|
||||
const [versions, setVersions] = useState<IVersion[]>(null);
|
||||
|
||||
async function fetchData(): Promise<void> {
|
||||
let result = await provider.GetVersions(filters);
|
||||
// as the provider does NOT filter by 'Editor' (aka Contributor) we will do this on client side
|
||||
if (filters.Author) {
|
||||
result = result.filter(v => v.Author.Email === filters.Author?.secondaryText);
|
||||
}
|
||||
setVersions(result);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [filters]);
|
||||
|
||||
return {
|
||||
versions, isLoading: versions === null,
|
||||
};
|
||||
}
|
|
@ -0,0 +1,20 @@
|
|||
import * as React from 'react';
|
||||
import { IFileInfo } from '@pnp/sp/files';
|
||||
import { IDataProvider } from '../providers/DataProvider';
|
||||
import { IVersion } from '../models/IVersion';
|
||||
|
||||
export default function useVersionMetadata(version: IVersion, provider: IDataProvider): { versionMetadata: IFileInfo } {
|
||||
const [versionMetadata, setVersionMetadata] = React.useState<IFileInfo>(undefined);
|
||||
|
||||
async function getMetadata(): Promise<void> {
|
||||
const { FileRef, VersionId } = version;
|
||||
const metadata = await provider.GetFileVersionMetadata(FileRef, VersionId);
|
||||
setVersionMetadata(metadata);
|
||||
}
|
||||
|
||||
React.useMemo(() => {
|
||||
getMetadata();
|
||||
}, [version, provider]);
|
||||
|
||||
return { versionMetadata };
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
define([], function() {
|
||||
return {
|
||||
}
|
||||
});
|
|
@ -0,0 +1,7 @@
|
|||
declare interface IBetterVersionHistoryCommandSetStrings {
|
||||
}
|
||||
|
||||
declare module 'BetterVersionHistoryCommandSetStrings' {
|
||||
const strings: IBetterVersionHistoryCommandSetStrings;
|
||||
export = strings;
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
export enum FieldType {
|
||||
Integer = "Integer",
|
||||
Text = "Text",
|
||||
Note = "Note",
|
||||
DateTime = "DateTime",
|
||||
Counter = "Counter",
|
||||
Choice = "Choice",
|
||||
Lookup = "Lookup",
|
||||
LookupMulti = "LookupMulti",
|
||||
Boolean = "Boolean",
|
||||
Number = "Number",
|
||||
URL = "URL",
|
||||
Computed = "Computed",
|
||||
Guid = "Guid",
|
||||
MultiChoice = "MultiChoice",
|
||||
User = "User",
|
||||
UserMulti = "UserMulti",
|
||||
ContentTypeId = "ContentTypeId",
|
||||
Taxonomy = "TaxonomyFieldType",
|
||||
TaxonomyMulti = "TaxonomyFieldTypeMulti",
|
||||
}
|
||||
|
||||
export enum DisplayFormat {
|
||||
DateOnly = 0,
|
||||
DateTime = 1,
|
||||
}
|
|
@ -0,0 +1,162 @@
|
|||
import { DisplayFormat, FieldType } from "./FieldTypes";
|
||||
import { IField } from "./IField";
|
||||
import { IFieldChange } from "./IVersion";
|
||||
|
||||
export interface IFieldLookupValue {
|
||||
LookupId: number;
|
||||
LookupValue: string;
|
||||
}
|
||||
|
||||
export interface IFieldUserValue extends IFieldLookupValue {
|
||||
Email: string;
|
||||
}
|
||||
|
||||
export interface IFieldUrlValue {
|
||||
Description: string;
|
||||
Url: string;
|
||||
}
|
||||
|
||||
export interface ITaxonomyFieldValue {
|
||||
Label: string
|
||||
TermGuid: string
|
||||
WssId: number
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const GetChanges: (field: IField, version: any, prevVersion: any) => IFieldChange = (field: IField, version: any, prevVersion: any) => {
|
||||
switch (field.TypeAsString) {
|
||||
case FieldType.Text:
|
||||
case FieldType.Note:
|
||||
case FieldType.Integer:
|
||||
case FieldType.Number:
|
||||
case FieldType.Choice:
|
||||
if (version[field.StaticName] !== prevVersion[field.StaticName]) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: prevVersion[field.StaticName],
|
||||
NewValue: version[field.StaticName],
|
||||
FieldType: field.TypeAsString
|
||||
};
|
||||
}
|
||||
break;
|
||||
case FieldType.Lookup:
|
||||
case FieldType.User:
|
||||
if ((version[field.StaticName] as IFieldLookupValue)?.LookupId !== (prevVersion[field.StaticName] as IFieldLookupValue)?.LookupId) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const link = new URL(window.location.protocol + "//" + window.location.host + (<any>window)._spPageContextInfo.siteServerRelativeUrl);
|
||||
link.pathname += "/_layouts/15/listform.aspx";
|
||||
link.searchParams.append("PageType", "4");
|
||||
link.searchParams.append("ListId", field.LookupList);
|
||||
link.searchParams.append("ID", (version[field.StaticName] as IFieldLookupValue)?.LookupId.toString());
|
||||
link.searchParams.append("RootFolder", "*");
|
||||
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: (prevVersion[field.StaticName] as IFieldLookupValue)?.LookupValue,
|
||||
NewValue: (version[field.StaticName] as IFieldLookupValue)?.LookupValue,
|
||||
FieldType: field.TypeAsString,
|
||||
Data: version[field.StaticName],
|
||||
Link: link.toString()
|
||||
};
|
||||
}
|
||||
break;
|
||||
case FieldType.DateTime:
|
||||
if (new Date(version[field.StaticName]).toLocaleString() !== new Date(prevVersion[field.StaticName]).toLocaleString()) {
|
||||
if (field.DisplayFormat === DisplayFormat.DateOnly) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: new Date(prevVersion[field.StaticName]).toLocaleDateString(),
|
||||
NewValue: new Date(version[field.StaticName]).toLocaleDateString(),
|
||||
FieldType: field.TypeAsString
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: new Date(prevVersion[field.StaticName]).toLocaleString(),
|
||||
NewValue: new Date(version[field.StaticName]).toLocaleString(),
|
||||
FieldType: field.TypeAsString
|
||||
};
|
||||
}
|
||||
}
|
||||
break;
|
||||
case FieldType.UserMulti:
|
||||
case FieldType.LookupMulti:
|
||||
if (JSON.stringify(version[field.StaticName]) !== JSON.stringify(prevVersion[field.StaticName])) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: (prevVersion[field.StaticName] as IFieldLookupValue[])?.map(x => x.LookupValue).join("\n"),
|
||||
NewValue: (version[field.StaticName] as IFieldLookupValue[])?.map(x => x.LookupValue).join("\n"),
|
||||
FieldType: field.TypeAsString,
|
||||
Data: version[field.StaticName]
|
||||
};
|
||||
}
|
||||
break;
|
||||
case FieldType.MultiChoice:
|
||||
if (JSON.stringify(version[field.StaticName]) !== JSON.stringify(prevVersion[field.StaticName])) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: (prevVersion[field.StaticName] as string[])?.join("\n"),
|
||||
NewValue: (version[field.StaticName] as string[])?.join("\n"),
|
||||
FieldType: field.TypeAsString,
|
||||
Data: version[field.StaticName]
|
||||
};
|
||||
}
|
||||
break;
|
||||
case FieldType.URL: {
|
||||
const BeforeUrlString = `${(prevVersion[field.StaticName] as IFieldUrlValue)?.Description} (${(prevVersion[field.StaticName] as IFieldUrlValue)?.Url})`;
|
||||
const NewUrlString = `${(version[field.StaticName] as IFieldUrlValue).Description} (${(version[field.StaticName] as IFieldUrlValue).Url})`;
|
||||
if (BeforeUrlString !== NewUrlString) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: BeforeUrlString,
|
||||
NewValue: NewUrlString,
|
||||
FieldType: field.TypeAsString,
|
||||
Data: version[field.StaticName]
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
case FieldType.Boolean:
|
||||
if (version[field.StaticName] !== prevVersion[field.StaticName]) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: prevVersion[field.StaticName] ? "Yes" : "No",
|
||||
NewValue: version[field.StaticName] ? "Yes" : "No",
|
||||
FieldType: field.TypeAsString
|
||||
};
|
||||
}
|
||||
break;
|
||||
case FieldType.Taxonomy:
|
||||
if (JSON.stringify(version[field.StaticName]) !== JSON.stringify(prevVersion[field.StaticName])) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: (prevVersion[field.StaticName] as ITaxonomyFieldValue)?.Label,
|
||||
NewValue: (version[field.StaticName] as ITaxonomyFieldValue)?.Label,
|
||||
FieldType: field.TypeAsString,
|
||||
Data: version[field.StaticName]
|
||||
};
|
||||
}
|
||||
break;
|
||||
case FieldType.TaxonomyMulti:
|
||||
if (JSON.stringify(version[field.StaticName]) !== JSON.stringify(prevVersion[field.StaticName])) {
|
||||
return {
|
||||
FieldName: field.Title,
|
||||
FieldInternalName: field.StaticName,
|
||||
OldValue: (prevVersion[field.StaticName] as ITaxonomyFieldValue[])?.map(x => x.Label).join("\n"),
|
||||
NewValue: (version[field.StaticName] as ITaxonomyFieldValue[])?.map(x => x.Label).join("\n"),
|
||||
FieldType: field.TypeAsString,
|
||||
Data: version[field.StaticName]
|
||||
};
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,66 @@
|
|||
import { DisplayFormat, FieldType } from "./FieldTypes"
|
||||
|
||||
export interface IField {
|
||||
"odata.type": string
|
||||
"odata.id": string
|
||||
"odata.editLink": string
|
||||
AutoIndexed: boolean
|
||||
CanBeDeleted: boolean
|
||||
ClientSideComponentId: string
|
||||
// ClientSideComponentProperties: any
|
||||
// ClientValidationFormula: any
|
||||
// ClientValidationMessage: any
|
||||
// CustomFormatter: any
|
||||
// DefaultFormula: any
|
||||
// DefaultValue: any
|
||||
Description: string
|
||||
Direction: string
|
||||
EnforceUniqueValues: boolean
|
||||
EntityPropertyName: string
|
||||
Filterable: boolean
|
||||
FromBaseType: boolean
|
||||
Group: string
|
||||
Hidden: boolean
|
||||
Id: string
|
||||
Indexed: boolean
|
||||
IndexStatus: number
|
||||
InternalName: string
|
||||
IsModern: boolean
|
||||
JSLink?: string
|
||||
PinnedToFiltersPane: boolean
|
||||
ReadOnlyField: boolean
|
||||
Required: boolean
|
||||
SchemaXml: string
|
||||
Scope: string
|
||||
Sealed: boolean
|
||||
ShowInFiltersPane: number
|
||||
Sortable: boolean
|
||||
StaticName: string
|
||||
Title: string
|
||||
FieldTypeKind: number
|
||||
TypeAsString: FieldType
|
||||
TypeDisplayName: string
|
||||
TypeShortDescription: string
|
||||
// ValidationFormula: any
|
||||
// ValidationMessage: any
|
||||
EnableLookup?: boolean
|
||||
MaxLength?: number
|
||||
CommaSeparator?: boolean
|
||||
// CustomUnitName: any
|
||||
CustomUnitOnRight?: boolean
|
||||
DisplayFormat?: DisplayFormat
|
||||
MaximumValue?: number
|
||||
MinimumValue?: number
|
||||
ShowAsPercentage?: boolean
|
||||
// Unit: any
|
||||
AllowMultipleValues?: boolean
|
||||
DependentLookupInternalNames?: string[]
|
||||
IsDependentLookup?: boolean
|
||||
IsRelationship?: boolean
|
||||
LookupField?: string
|
||||
LookupList?: string
|
||||
LookupWebId?: string
|
||||
PrimaryFieldId?: string
|
||||
RelationshipDeleteBehavior?: number
|
||||
UnlimitedLengthInDocumentLibrary?: boolean
|
||||
}
|
|
@ -0,0 +1,31 @@
|
|||
import { FieldType } from "./FieldTypes";
|
||||
import { IFieldUserValue } from "./FieldValues";
|
||||
|
||||
export interface IVersion {
|
||||
VersionName: string;
|
||||
Author: IFieldUserValue;
|
||||
TimeStamp: Date;
|
||||
Changes: IFieldChange[];
|
||||
VersionId: number;
|
||||
VersionLink: string;
|
||||
Moderation?: IModerationInfo;
|
||||
FileRef: string;
|
||||
FileName: string;
|
||||
FileSize: number;
|
||||
}
|
||||
|
||||
export interface IFieldChange {
|
||||
FieldName: string;
|
||||
FieldInternalName: string;
|
||||
FieldType: FieldType;
|
||||
OldValue: string;
|
||||
NewValue: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
Data?: any;
|
||||
Link?: string;
|
||||
}
|
||||
|
||||
export interface IModerationInfo {
|
||||
ModerationStatus?: number;
|
||||
ModerationComments?: string;
|
||||
}
|
|
@ -0,0 +1,8 @@
|
|||
import { IPersonaProps } from "@fluentui/react";
|
||||
|
||||
export interface IVersionsFilter {
|
||||
StartDate?: Date;
|
||||
EndDate?: Date;
|
||||
Author?: IPersonaProps;
|
||||
VersionNumbers?: number[];
|
||||
}
|
|
@ -0,0 +1,140 @@
|
|||
import { ListViewCommandSetContext } from "@microsoft/sp-listview-extensibility";
|
||||
import { SPHttpClient } from "@microsoft/sp-http";
|
||||
import { SPFx, SPFI, spfi, IFileInfo } from "@pnp/sp/presets/all";
|
||||
import { IField } from "../models/IField";
|
||||
import { IVersion } from "../models/IVersion";
|
||||
import { GetChanges } from "../models/FieldValues";
|
||||
import { IVersionsFilter } from "../models/IVersionsFilter";
|
||||
|
||||
export interface IDataProvider {
|
||||
GetVersions(filters: IVersionsFilter): Promise<IVersion[]>
|
||||
GetFileVersionMetadata(fileRef: string, versionId: number): Promise<IFileInfo>;
|
||||
GetFileInfo(): Promise<IFileInfo>;
|
||||
RestoreVersion(versionId: IVersion): Promise<void>;
|
||||
DeleteVersion(versionId: number): Promise<void>;
|
||||
}
|
||||
|
||||
export class DataProvider implements IDataProvider {
|
||||
private _context: ListViewCommandSetContext = null;
|
||||
private _SPFI: SPFI = null;
|
||||
|
||||
constructor(context: ListViewCommandSetContext) {
|
||||
this._context = context;
|
||||
}
|
||||
|
||||
private getSPFI(): SPFI {
|
||||
if (this._SPFI === null)
|
||||
this._SPFI = spfi().using(SPFx(this._context));
|
||||
return this._SPFI;
|
||||
}
|
||||
|
||||
private fieldsToSkip: string[] = ["Modified", "Created"];
|
||||
public async GetVersions(filters: IVersionsFilter): Promise<IVersion[]> {
|
||||
const fields = await this.GetFields(this._context.pageContext.list.id.toString());
|
||||
|
||||
const filterQueries: string[] = [];
|
||||
|
||||
if (filters.StartDate !== undefined)
|
||||
filterQueries.push(`Created ge datetime'${filters.StartDate.toISOString()}'`);
|
||||
|
||||
if (filters.EndDate !== undefined)
|
||||
filterQueries.push(`Created le datetime'${filters.EndDate.toISOString()}'`);
|
||||
|
||||
if (filters.VersionNumbers !== undefined && filters.VersionNumbers.length > 0)
|
||||
filterQueries.push(`(${filters.VersionNumbers.map(v => `VersionId eq ${v}`).join(" or ")})`);
|
||||
|
||||
const endpoint = this.getSPFI().web.lists.getById(this._context.pageContext.list.id.toString()).items.getById(this._context.listView.selectedRows[0].getValueByName("ID")).versions;
|
||||
if (filterQueries.length > 0)
|
||||
endpoint.filter(filterQueries.join(" and "));
|
||||
|
||||
const versions = await endpoint();
|
||||
const Changes: IVersion[] = [];
|
||||
|
||||
for (let i = versions.length; i > 0; i--) {
|
||||
const version = versions[i - 1];
|
||||
const prevVersion = versions[i] ?? {};
|
||||
|
||||
const FileLink = new URL(`${this._context.pageContext.web.absoluteUrl}/_layouts/15/versions.appx`);
|
||||
FileLink.searchParams.append("FileName", version.FileRef);
|
||||
FileLink.searchParams.append("list", this._context.pageContext.list.id.toString());
|
||||
FileLink.searchParams.append("ID", this._context.listView.selectedRows[0].getValueByName("ID"));
|
||||
FileLink.searchParams.append("col", "Number");
|
||||
//Todo: Add support
|
||||
// FileLink.searchParams.append("op", "Delete");
|
||||
// FileLink.searchParams.append("op", "Restore");
|
||||
FileLink.searchParams.append("ver", version.VersionId);
|
||||
FileLink.searchParams.append("IsDlg", "1");
|
||||
|
||||
console.log(version.VersionLabel);
|
||||
console.log(FileLink.toString());
|
||||
|
||||
// const fileVersionMetadata = (version.FSObjType && !version.IsCurrentVersion) ? await this.GetFileVersionMetadata(version.FileRef, version.VersionLabel) : undefined;
|
||||
const Version: IVersion = {
|
||||
VersionName: version.VersionLabel,
|
||||
Author: version.Editor,
|
||||
TimeStamp: new Date(`${version.Created}z`),
|
||||
Changes: [],
|
||||
VersionId: version.VersionId,
|
||||
// VersionLink: `${this._context.pageContext.list.serverRelativeUrl}/DispForm.aspx?ID=${this._context.listView.selectedRows[0].getValueByName("ID")}&VersionNo=${version.VersionId}`,
|
||||
VersionLink: version["ContentTypeId"]["StringValue"].indexOf("0x0100") > -1 ? `${this._context.pageContext.list.serverRelativeUrl}/DispForm.aspx?ID=${this._context.listView.selectedRows[0].getValueByName("ID")}&VersionNo=${version.VersionId}` : encodeURI(`${this._context.pageContext.site.absoluteUrl}` + (version.IsCurrentVersion ? version.FileRef : `/_vti_history/${version.VersionId}${version.FileRef}`)),
|
||||
FileRef: version.FileRef,
|
||||
FileName: version.FileLeafRef,
|
||||
FileSize: version.SMTotalFileStreamSize,
|
||||
Moderation: {
|
||||
ModerationStatus: (version['OData__x005f_ModerationStatus'] >= 0 ? version['OData__x005f_ModerationStatus'] : undefined),
|
||||
ModerationComments: (version['OData__x005f_ModerationStatus'] >= 0 ? version['OData__x005f_ModerationComments'] : ''),
|
||||
}
|
||||
};
|
||||
|
||||
for (const field of fields) {
|
||||
if (this.fieldsToSkip.indexOf(field.StaticName) !== -1)
|
||||
continue;
|
||||
|
||||
const change = GetChanges(field, version, prevVersion);
|
||||
if (change !== undefined)
|
||||
Version.Changes.push(change);
|
||||
}
|
||||
|
||||
Changes.push(Version);
|
||||
}
|
||||
|
||||
Changes.reverse();
|
||||
|
||||
return Changes;
|
||||
}
|
||||
|
||||
public async GetFileInfo(): Promise<IFileInfo> {
|
||||
const item = this.getSPFI().web.lists.getById(this._context.pageContext.list.id.toString()).items.getById(this._context.listView.selectedRows[0].getValueByName("ID"));
|
||||
return await item.file();
|
||||
}
|
||||
|
||||
private async GetFields(listId: string): Promise<IField[]> {
|
||||
return this.getSPFI().web.lists.getById(listId).fields.filter("Hidden eq false")();
|
||||
}
|
||||
|
||||
public async GetFileVersionMetadata(fileRef: string, versionId: number): Promise<IFileInfo> {
|
||||
const result = (await this.getSPFI().web.getFileByServerRelativePath(fileRef).versions())
|
||||
.filter(v => v.ID === versionId)[0];
|
||||
return result;
|
||||
}
|
||||
|
||||
public async DeleteVersion(versionId: number): Promise<void> {
|
||||
const item = this.getSPFI().web.lists.getById(this._context.pageContext.list.id.toString()).items.getById(this._context.listView.selectedRows[0].getValueByName("ID"));
|
||||
await item.versions.getById(versionId).delete();
|
||||
}
|
||||
|
||||
public async RestoreVersion(version: IVersion): Promise<void> {
|
||||
const FileLink = new URL(`${this._context.pageContext.web.absoluteUrl}/_layouts/15/versions.aspx`);
|
||||
FileLink.searchParams.append("FileName", version.FileRef);
|
||||
FileLink.searchParams.append("list", `{${this._context.pageContext.list.id.toString().toUpperCase()}}`);
|
||||
FileLink.searchParams.append("ID", this._context.listView.selectedRows[0].getValueByName("ID"));
|
||||
FileLink.searchParams.append("col", "Number");
|
||||
FileLink.searchParams.append("order", "d");
|
||||
FileLink.searchParams.append("op", "Restore");
|
||||
FileLink.searchParams.append("ver", version.VersionId + "");
|
||||
FileLink.searchParams.append("IsDlg", "1");
|
||||
|
||||
await this._context.spHttpClient.post(FileLink.toString(), SPHttpClient.configurations.v1, {});
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,13 @@
|
|||
import { ITheme, getTheme } from '@fluentui/react';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const ThemeState = (<any>window).__themeState__;
|
||||
|
||||
// Get theme from global UI fabric state object if exists, if not fall back to using uifabric
|
||||
export function getThemeColor(slot: string): string {
|
||||
if (ThemeState && ThemeState.theme && ThemeState.theme[slot]) {
|
||||
return ThemeState.theme[slot];
|
||||
}
|
||||
const theme = getTheme();
|
||||
return theme[slot as keyof ITheme] as string;
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
// A file is required to be in the root of the /src directory by the TypeScript compiler
|
|
@ -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"
|
||||
]
|
||||
}
|
Loading…
Reference in New Issue