react-sp-tinymce editor samples added
This commit is contained in:
parent
8665d4665a
commit
fdae09ce8f
|
@ -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: {}
|
||||
}
|
||||
]
|
||||
};
|
|
@ -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,21 @@
|
|||
{
|
||||
"@microsoft/generator-sharepoint": {
|
||||
"plusBeta": false,
|
||||
"isCreatingSolution": true,
|
||||
"nodeVersion": "16.13.0",
|
||||
"sdksVersions": {
|
||||
"@microsoft/microsoft-graph-client": "3.0.2",
|
||||
"@microsoft/teams-js": "2.9.1"
|
||||
},
|
||||
"version": "1.17.4",
|
||||
"libraryName": "oc-sp-tinymce",
|
||||
"libraryId": "3640f0cc-a41c-485c-b5e2-688975a75840",
|
||||
"environment": "spo",
|
||||
"packageManager": "npm",
|
||||
"solutionName": "oc-sp-tinymce",
|
||||
"solutionShortDescription": "oc-sp-tinymce description",
|
||||
"skipFeatureDeployment": true,
|
||||
"isDomainIsolated": false,
|
||||
"componentType": "webpart"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,101 @@
|
|||
# SharePoint List Integration with TinyMCE Editor
|
||||
|
||||
## Summary
|
||||
|
||||
An example of integrating SharePoint lists with TinyMCE editors can be found in this sample. The web part allows users to insert column data from associated SharePoint lists using a split button on the toolbar. An editor preview plugin for TinyMce was developed in order to be able to preview changes before they are saved.
|
||||
|
||||
## Demo
|
||||
|
||||
![Sample web part showing SharePoint list integration with TinyMce editor](./assets/demo.gif)
|
||||
|
||||
## Compatibility
|
||||
|
||||
| :warning: Important |
|
||||
|:---------------------------|
|
||||
| Every SPFx version is only compatible with specific version(s) of Node.js. In order to be able to build this sample, please ensure that the version of Node on your workstation matches one of the versions listed in this section. This sample will not work on a different version of Node.|
|
||||
|Refer to <https://aka.ms/spfx-matrix> for more information on SPFx compatibility. |
|
||||
|
||||
![SPFx 1.17.4](https://img.shields.io/badge/SPFx-1.17.4-green.svg)
|
||||
![Node.js v16.13.0](https://img.shields.io/badge/Node.js-v16.13.0-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")
|
||||
![Teams Incompatible](https://img.shields.io/badge/Teams-Incompatible-lightgrey.svg)
|
||||
![Local Workbench Incompatible](https://img.shields.io/badge/Local%20Workbench-Incompatible-red.svg "This solution requires access to a user's user and group ids")
|
||||
![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://aka.ms/spfx)
|
||||
- [Microsoft 365 tenant](https://learn.microsoft.com/sharepoint/dev/spfx/set-up-your-developer-tenant)
|
||||
|
||||
> Get your own free development tenant by subscribing to [Microsoft 365 developer program](http://aka.ms/m365devprogram)
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Access to a SharePoint online site with various tenant users granted access to various site resources directly, via AAD groups and via SharePoint groups.
|
||||
|
||||
## Contributors
|
||||
|
||||
* [Ejaz Hussain](https://github.com/ejazhussain)
|
||||
|
||||
## Version history
|
||||
|
||||
| Version | Date | Comments |
|
||||
| ------- | ----------------- | --------------- |
|
||||
| 1.0.0 | June 6, 2023 | Initial release |
|
||||
|
||||
## Minimal Path to Awesome
|
||||
|
||||
- Clone this repository
|
||||
- Ensure that you are at the solution folder
|
||||
- in the command-line run:
|
||||
- `npm install`
|
||||
- `gulp trust-dev-cert`
|
||||
- `gulp serve --nobrowser`
|
||||
- Open the hosted workbench on a SharePoint site - i.e. https://_tenant_.sharepoint.com/site/_sitename_/_layouts/workbench.aspx
|
||||
- Add the [OC] Tinymce Editor web part to the page.
|
||||
- In the web part properties, Add absolute URL of the site under Site URL field.
|
||||
- Select the required list from the available list under Select a list dropdown. This dropdown will be auto populated based on the Site URL property
|
||||
|
||||
- Provide list Item Id
|
||||
|
||||
- Close the web part properties pane and save and reload the page
|
||||
|
||||
## Features
|
||||
|
||||
An example of integrating SharePoint lists with TinyMCE editors can be found in this sample. The web part allows users to insert column data from associated SharePoint lists using a split button on the toolbar. An editor preview plugin for TinyMce was developed in order to be able to preview changes before they are saved.
|
||||
|
||||
## Supported list columns
|
||||
|
||||
- Text
|
||||
- DateTime
|
||||
- Number
|
||||
- Note
|
||||
- Single taxonomy
|
||||
- Multi taxonomy
|
||||
- User
|
||||
- User Multi
|
||||
- Choices
|
||||
- Hyperlink
|
||||
|
||||
|
||||
## 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.
|
||||
|
||||
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-sp-site-user-groups&template=bug-report.yml&sample=react-sp-site-user-groups&authors=@danwatford&title=react-sp-site-user-groups%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-sp-site-user-groups&template=question.yml&sample=react-sp-site-user-groups&authors=@danwatford&title=react-sp-site-user-groups%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-sp-site-user-groups&template=question.yml&sample=react-sp-site-user-groups&authors=@danwatford&title=react-sp-site-user-groups%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.**
|
||||
|
||||
|
||||
|
Binary file not shown.
After Width: | Height: | Size: 2.2 MiB |
|
@ -0,0 +1,19 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/config.2.0.schema.json",
|
||||
"version": "2.0",
|
||||
"bundles": {
|
||||
"tinymce-editor-web-part": {
|
||||
"components": [
|
||||
{
|
||||
"entrypoint": "./lib/webparts/tinymceEditor/TinymceEditorWebPart.js",
|
||||
"manifest": "./src/webparts/tinymceEditor/TinymceEditorWebPart.manifest.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"externals": {},
|
||||
"localizedResources": {
|
||||
"TinymceEditorWebPartStrings": "lib/webparts/tinymceEditor/loc/{locale}.js",
|
||||
"PropertyControlStrings": "node_modules/@pnp/spfx-property-controls/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": "oc-sp-tinymce",
|
||||
"accessKey": "<!-- ACCESS KEY -->"
|
||||
}
|
|
@ -0,0 +1,46 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/package-solution.schema.json",
|
||||
"solution": {
|
||||
"name": "OC - SP TinyMce Editor",
|
||||
"id": "3640f0cc-a41c-485c-b5e2-688975a75840",
|
||||
"version": "1.0.0.0",
|
||||
"includeClientSideAssets": true,
|
||||
"skipFeatureDeployment": true,
|
||||
"isDomainIsolated": false,
|
||||
"developer": {
|
||||
"name": "",
|
||||
"websiteUrl": "",
|
||||
"privacyUrl": "",
|
||||
"termsOfUseUrl": "",
|
||||
"mpnId": "Undefined-1.17.4"
|
||||
},
|
||||
"webApiPermissionRequests": [
|
||||
{
|
||||
"resource": "Microsoft Graph",
|
||||
"scope": "User.Read.All"
|
||||
}
|
||||
],
|
||||
"metadata": {
|
||||
"shortDescription": {
|
||||
"default": "OC - SP TinyMce Editor description"
|
||||
},
|
||||
"longDescription": {
|
||||
"default": "OC - SP TinyMce Editor description"
|
||||
},
|
||||
"screenshotPaths": [],
|
||||
"videoUrl": "",
|
||||
"categories": []
|
||||
},
|
||||
"features": [
|
||||
{
|
||||
"title": "OC - SP TinyMce Editor Feature",
|
||||
"description": "The feature that activates elements of the oc-sp-tinymce solution.",
|
||||
"id": "dfeff68c-447c-4df1-b4b5-f52243f1e30e",
|
||||
"version": "1.0.0.0"
|
||||
}
|
||||
]
|
||||
},
|
||||
"paths": {
|
||||
"zippedPackage": "solution/oc-sp-tinymce.sppkg"
|
||||
}
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/core-build/sass.schema.json"
|
||||
}
|
|
@ -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"
|
||||
}
|
|
@ -0,0 +1,4 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx-build/write-manifests.schema.json",
|
||||
"cdnBasePath": "<!-- PATH TO CDN -->"
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
'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'));
|
||||
|
||||
// add this line:
|
||||
build.lintCmd.enabled = false;
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,58 @@
|
|||
{
|
||||
"name": "oc-sp-tinymce",
|
||||
"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.199.1",
|
||||
"@microsoft/mgt": "^2.11.1",
|
||||
"@microsoft/mgt-react": "^2.11.1",
|
||||
"@microsoft/sp-component-base": "1.17.4",
|
||||
"@microsoft/sp-core-library": "1.17.4",
|
||||
"@microsoft/sp-lodash-subset": "1.17.4",
|
||||
"@microsoft/sp-office-ui-fabric-core": "1.17.4",
|
||||
"@microsoft/sp-property-pane": "1.17.4",
|
||||
"@microsoft/sp-webpart-base": "1.17.4",
|
||||
"@pnp/logging": "^1.3.11",
|
||||
"@pnp/spfx-property-controls": "^3.14.0-beta.4786980",
|
||||
"@tinymce/tinymce-react": "4.3.0",
|
||||
"antd": "^5.0.0",
|
||||
"dompurify": "^2.4.5",
|
||||
"html-react-parser": "^4.0.0",
|
||||
"office-ui-fabric-react": "^7.199.1",
|
||||
"react": "17.0.1",
|
||||
"react-dom": "17.0.1",
|
||||
"styled-components": "^6.0.0-rc.3",
|
||||
"tinymce": "^6.4.1",
|
||||
"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",
|
||||
"@rushstack/eslint-plugin": "^0.12.0",
|
||||
"@rushstack/eslint-plugin-security": "^0.6.0",
|
||||
"@types/dompurify": "^3.0.2",
|
||||
"@types/react": "17.0.45",
|
||||
"@types/react-dom": "17.0.17",
|
||||
"@types/webpack-env": "~1.15.2",
|
||||
"@typescript-eslint/eslint-plugin": "^5.60.0",
|
||||
"ajv": "^6.12.5",
|
||||
"eslint": "8.7.0",
|
||||
"eslint-plugin-promise": "^6.1.1",
|
||||
"eslint-plugin-react-hooks": "4.3.0",
|
||||
"gulp": "4.0.2",
|
||||
"typescript": "4.5.5"
|
||||
}
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
// A file is required to be in the root of the /src directory by the TypeScript compiler
|
|
@ -0,0 +1,28 @@
|
|||
{
|
||||
"$schema": "https://developer.microsoft.com/json-schemas/spfx/client-side-web-part-manifest.schema.json",
|
||||
"id": "9c9486a4-035f-4a44-ab4c-d10c415796b4",
|
||||
"alias": "TinymceEditorWebPart",
|
||||
"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": "[OC] Tinymce Editor" },
|
||||
"description": { "default": "TinymceEditor description" },
|
||||
"officeFabricIconFontName": "FullWidthEdit",
|
||||
"properties": {
|
||||
|
||||
}
|
||||
}]
|
||||
}
|
|
@ -0,0 +1,227 @@
|
|||
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 'TinymceEditorWebPartStrings';
|
||||
import { ITinymceEditorProps } from './components/ITinymceEditorProps';
|
||||
import { PropertyFieldListPicker, PropertyFieldListPickerOrderBy } from '@pnp/spfx-property-controls/lib/PropertyFieldListPicker';
|
||||
import SharePointService from './services/SharePointService';
|
||||
import { IFieldSchema } from './model/IFieldSchema';
|
||||
import { TinymceEditor } from './components/TinymceEditor';
|
||||
import { Providers, SharePointProvider } from '@microsoft/mgt';
|
||||
import { FieldType } from './model/FieldType';
|
||||
|
||||
export interface ITinymceEditorWebPartProps {
|
||||
listId: string;
|
||||
siteUrl: string;
|
||||
listItemId: string;
|
||||
listFieldsSchema: IFieldSchema[];
|
||||
editorContent: string;
|
||||
}
|
||||
|
||||
export default class TinymceEditorWebPart extends BaseClientSideWebPart<ITinymceEditorWebPartProps> {
|
||||
|
||||
private _isDarkTheme: boolean = false;
|
||||
private _environmentMessage: string = '';
|
||||
|
||||
public render(): void {
|
||||
const element: React.ReactElement<ITinymceEditorProps> = React.createElement(
|
||||
TinymceEditor,
|
||||
{
|
||||
isDarkTheme: this._isDarkTheme,
|
||||
environmentMessage: this._environmentMessage,
|
||||
hasTeamsContext: !!this.context.sdks.microsoftTeams,
|
||||
userDisplayName: this.context.pageContext.user.displayName,
|
||||
siteUrl: this.properties.siteUrl,
|
||||
listId: this.properties.listId,
|
||||
listItemId: this.properties.listItemId,
|
||||
listFieldsSchema: this.properties.listFieldsSchema,
|
||||
context: this.context,
|
||||
displayMode: this.displayMode,
|
||||
editorContent: this.properties.editorContent,
|
||||
onContentUpdate: this.onContentUpdate.bind(this)
|
||||
}
|
||||
);
|
||||
|
||||
ReactDom.render(element, this.domElement);
|
||||
}
|
||||
|
||||
protected onInit(): Promise<void> {
|
||||
|
||||
//Init SharePoint Service
|
||||
SharePointService.Init(this.context.spHttpClient);
|
||||
|
||||
//Init MGT SharePoint Provider
|
||||
Providers.globalProvider = new SharePointProvider(this.context);
|
||||
|
||||
return this._getEnvironmentMessage().then(message => {
|
||||
this._environmentMessage = message;
|
||||
});
|
||||
|
||||
return super.onInit();
|
||||
}
|
||||
|
||||
|
||||
|
||||
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('siteUrl', {
|
||||
label: "Site URL"
|
||||
}),
|
||||
PropertyFieldListPicker('listId', {
|
||||
label: 'Select a list',
|
||||
selectedList: this.properties.listId,
|
||||
includeHidden: false,
|
||||
multiSelect: false,
|
||||
orderBy: PropertyFieldListPickerOrderBy.Title,
|
||||
disabled: false,
|
||||
onPropertyChange: this.onPropertyPaneFieldChanged.bind(this),
|
||||
properties: this.properties,
|
||||
context: this.context as any,
|
||||
deferredValidationTime: 0,
|
||||
key: 'listPickerFieldId',
|
||||
webAbsoluteUrl: this.properties.siteUrl
|
||||
}),
|
||||
PropertyPaneTextField('listItemId', {
|
||||
label: "List Item Id"
|
||||
}),
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
protected async onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any): Promise<void> {
|
||||
if (propertyPath === 'listId' && newValue) {
|
||||
// push new list value
|
||||
super.onPropertyPaneFieldChanged(propertyPath, oldValue, newValue);
|
||||
|
||||
//Get list fields
|
||||
this.loadListFields(this.properties.siteUrl, newValue);
|
||||
|
||||
// refresh the item selector control by repainting the property pane
|
||||
this.context.propertyPane.refresh();
|
||||
// re-render the web part as clearing the loading indicator removes the web part body
|
||||
this.render();
|
||||
}
|
||||
else {
|
||||
super.onPropertyPaneFieldChanged(propertyPath, oldValue, oldValue);
|
||||
}
|
||||
}
|
||||
|
||||
private async loadListFields(siteUrl: string, listGuid: string): Promise<void> {
|
||||
|
||||
this.properties.listFieldsSchema = [];
|
||||
const listUrl = await SharePointService.getListUrl(siteUrl, listGuid);
|
||||
const hostUrl = `${window.location.protocol}//${window.location.hostname}`;
|
||||
const siteRelativeUrl = siteUrl.substring(hostUrl.length);
|
||||
const listRelativeUrl = listUrl.substring(siteRelativeUrl.length);
|
||||
const listFieldsResponse: any[] = await SharePointService.getListFieldsAsDataStream(siteRelativeUrl, listRelativeUrl);
|
||||
let fields: IFieldSchema[] = listFieldsResponse.map((field: any) => {
|
||||
return {
|
||||
id: field.Id,
|
||||
title: field.Title,
|
||||
staticName: field.StaticName || field.InternalName,
|
||||
required: field.Required ?? false,
|
||||
fieldType: field.FieldType || field.TypeAsString,
|
||||
typeAsString: field.TypeAsString,
|
||||
description: field.Description,
|
||||
choices: field.Choices,
|
||||
multiChoices: field.MultiChoices,
|
||||
displayFormat: field.DisplayFormat,
|
||||
firstDayOfWeek: field.FirstDayOfWeek,
|
||||
localeId: field.LocaleId,
|
||||
termSetId: field.TermSetId
|
||||
} as IFieldSchema;
|
||||
});
|
||||
|
||||
if (fields.length > 0) {
|
||||
fields = fields.filter(f => f.staticName &&
|
||||
f.fieldType !== FieldType.Thumbnail &&
|
||||
f.fieldType !== FieldType.Lookup &&
|
||||
f.fieldType !== FieldType.LookupMulti &&
|
||||
f.fieldType !== FieldType.Attachments &&
|
||||
f.fieldType !== FieldType.Location &&
|
||||
f.staticName !== 'Target_x0020_Audiences' &&
|
||||
f.staticName !== '_ModernAudienceTargetUserField');
|
||||
}
|
||||
|
||||
// this.properties.listFields = [...fields.map(field => ({ key: field.staticName, text: field.title }))];
|
||||
this.properties.listFieldsSchema = fields;
|
||||
// refresh the item selector control by repainting the property pane
|
||||
this.context.propertyPane.refresh();
|
||||
// re-render the web part as clearing the loading indicator removes the web part body
|
||||
this.render();
|
||||
}
|
||||
private onContentUpdate(content: string): void {
|
||||
this.properties.editorContent = content;
|
||||
}
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
After Width: | Height: | Size: 12 KiB |
|
@ -0,0 +1,20 @@
|
|||
import { WebPartContext } from "@microsoft/sp-webpart-base";
|
||||
import { IFieldSchema } from "../model/IFieldSchema";
|
||||
import { DisplayMode } from "@microsoft/sp-core-library";
|
||||
|
||||
export interface ITinymceEditorProps {
|
||||
isDarkTheme: boolean;
|
||||
environmentMessage: string;
|
||||
hasTeamsContext: boolean;
|
||||
userDisplayName: string;
|
||||
listId: string;
|
||||
siteUrl: string;
|
||||
listItemId:string;
|
||||
listFieldsSchema: IFieldSchema[];
|
||||
userId?: string;
|
||||
context: WebPartContext;
|
||||
onContentUpdate: (content: string) => Promise<void>
|
||||
editorContent: string;
|
||||
displayMode: DisplayMode;
|
||||
|
||||
}
|
|
@ -0,0 +1,38 @@
|
|||
import * as React from 'react';
|
||||
import { Person, PersonCardInteraction, PersonViewType } from '@microsoft/mgt-react';
|
||||
import styles from '../TinymceEditor.module.scss';
|
||||
|
||||
export interface IPeopleCardProps {
|
||||
users: any[];
|
||||
}
|
||||
|
||||
const PeopleCard: React.FunctionComponent<IPeopleCardProps> = ({ users }) => {
|
||||
|
||||
if (!users || users.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
return (
|
||||
<React.Suspense fallback={<div style={{ display: 'none' }} />}>
|
||||
<div style={{ display: 'grid', gridGap: '1rem', gridTemplateColumns: false ? 'none' : 'repeat(auto-fit, minmax(250px, 1fr))' }}>
|
||||
{
|
||||
users.map((user, index) => {
|
||||
return <div key={index} className={styles.personContainer}>
|
||||
<Person
|
||||
personQuery={user.email}
|
||||
view={PersonViewType.twolines}
|
||||
personCardInteraction={PersonCardInteraction.hover}
|
||||
/>
|
||||
</div>;
|
||||
})
|
||||
}
|
||||
</div>
|
||||
</React.Suspense>
|
||||
);
|
||||
|
||||
|
||||
|
||||
};
|
||||
|
||||
export default PeopleCard;
|
|
@ -0,0 +1,12 @@
|
|||
|
||||
|
||||
import { WebPartContext } from "@microsoft/sp-webpart-base";
|
||||
import { IFieldSchema } from "../../model/IFieldSchema";
|
||||
|
||||
export interface IRenderContentEditProps {
|
||||
context: WebPartContext;
|
||||
listFieldsSchema: IFieldSchema[];
|
||||
onContentUpdate: (content: string) => Promise<void>;
|
||||
editorContent: string;
|
||||
listData: any;
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
|
||||
|
||||
export interface IRenderContentEditState {
|
||||
editorContent: string;
|
||||
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
body {
|
||||
color: red !important
|
||||
}
|
|
@ -0,0 +1,57 @@
|
|||
@import "ThemeColours.module";
|
||||
|
||||
// override font-family for tinymce editor UI
|
||||
.renderContent {
|
||||
:global {
|
||||
.tox.tox-tinymce,
|
||||
.tox.tox-tinymce :not(svg) {
|
||||
font-family: "Segoe UI Web (West European)", Segoe UI, -apple-system, BlinkMacSystemFont, Roboto, Helvetica Neue,
|
||||
sans-serif;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// override font and primary colour for editor dialogs
|
||||
:global {
|
||||
.tox.tox-tinymce-aux .tox-dialog-wrap {
|
||||
font-family: "Segoe UI Web (West European)", Segoe UI, -apple-system, BlinkMacSystemFont, Roboto, Helvetica Neue,
|
||||
sans-serif;
|
||||
|
||||
.tox-dialog__body-nav-item--active {
|
||||
border-bottom-color: $themePrimary;
|
||||
color: $themePrimary;
|
||||
}
|
||||
|
||||
.tox-button:not(.tox-button--secondary):not(.tox-button--icon):not(.tox-button--naked) {
|
||||
border-color: $themePrimary;
|
||||
background-color: $themePrimary;
|
||||
}
|
||||
|
||||
textarea.tox-textarea:focus,
|
||||
input.tox-textfield:focus,
|
||||
.tox-selectfield select:focus {
|
||||
border-color: $themePrimary;
|
||||
}
|
||||
|
||||
input.tox-textfield,
|
||||
.tox-selectfield select,
|
||||
textarea.tox-textarea {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
textarea.tox-textarea {
|
||||
min-height: 8em;
|
||||
}
|
||||
|
||||
label {
|
||||
margin-bottom: 0.5em;
|
||||
color: #666;
|
||||
}
|
||||
}
|
||||
// .tox-dialog__content-js .tox-dialog__body .tox-dialog__body-content .tox-form .tox-form__group {
|
||||
// color: red !important;
|
||||
// }
|
||||
// .tox-dialog__content-js .tox-dialog__body .tox-dialog__body-content .tox-form .tox-form__group .panel-styles p {
|
||||
// font-weight: bold !important;
|
||||
// }
|
||||
}
|
|
@ -0,0 +1,212 @@
|
|||
import * as React from 'react';
|
||||
import { Editor } from '@tinymce/tinymce-react';
|
||||
import { IRenderContentEditProps } from './IRenderContentEditProps';
|
||||
import * as FieldPicker from '../TinyMCEPlugins/TinyMCE.FieldPicker';
|
||||
import { IRenderContentEditState as IRenderContentEditState } from './IRenderContentEditState';
|
||||
import Styles from './RenderContentEdit.module.scss';
|
||||
import { decode, encode } from '../../utils/EncodingUtils';
|
||||
|
||||
require('tinymce/tinymce');
|
||||
|
||||
const plugins = [
|
||||
'anchor',
|
||||
'autolink',
|
||||
'code',
|
||||
'directionality',
|
||||
'insertdatetime',
|
||||
'fullscreen',
|
||||
'link',
|
||||
'lists',
|
||||
'media',
|
||||
'preview',
|
||||
'searchreplace',
|
||||
'table',
|
||||
'media',
|
||||
'image'
|
||||
];
|
||||
const models = ['dom'];
|
||||
const themes = ['silver'];
|
||||
const icons = ['default'];
|
||||
|
||||
const tinyMceStart = () => {
|
||||
plugins.forEach(plugin => require(`tinymce/plugins/${plugin}`));
|
||||
models.forEach(model => require(`tinymce/models/${model}`));
|
||||
themes.forEach(theme => require(`tinymce/themes/${theme}`));
|
||||
icons.forEach(icon => require(`tinymce/icons/${icon}`));
|
||||
|
||||
require(`tinymce/skins/ui/oxide/skin.min.css`);
|
||||
require(`tinymce/skins/ui/oxide/content.min.css`);
|
||||
require(`tinymce/skins/content/default/content.css`);
|
||||
};
|
||||
|
||||
|
||||
export class RenderContentEdit extends React.Component<IRenderContentEditProps, IRenderContentEditState> {
|
||||
|
||||
private initOptions: Record<string, any>;
|
||||
//private editorRef = null;
|
||||
|
||||
|
||||
constructor(props: IRenderContentEditProps) {
|
||||
super(props);
|
||||
|
||||
|
||||
this.handleEditorChange = this.handleEditorChange.bind(this);
|
||||
|
||||
this.initTinyMCE();
|
||||
|
||||
this.state = {
|
||||
editorContent: this.props.editorContent ? this.props.editorContent : ""
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private initTinyMCE() {
|
||||
tinyMceStart();
|
||||
const menu = this.getMenuItems();
|
||||
const color_map = this.getColourMap();
|
||||
this.initOptions = {
|
||||
selector: "textarea#tinymce",
|
||||
height: 600,
|
||||
plugins,
|
||||
menu,
|
||||
menubar: 'edit view insert format table',
|
||||
toolbar: this.getToolbarItems(),
|
||||
content_style: `body#tinymce.mce-content-body {
|
||||
font-family: 'Segoe UI Web (West European)',Segoe UI,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif;
|
||||
}`,
|
||||
skin: false,
|
||||
color_map,
|
||||
color_cols: 8,
|
||||
block_formats: 'Paragraph=p;Heading 1=h2;Heading 2=h3;Heading 3=h4',
|
||||
setup: this.setupContentEditor.bind(this),
|
||||
images_upload_url: 'custom',
|
||||
image_uploadtab: false,
|
||||
target_list: false,
|
||||
keep_styles: false,
|
||||
paste_block_drop: false,
|
||||
paste_data_images: true,
|
||||
paste_as_text: true,
|
||||
promotion: false,
|
||||
browser_spellcheck: true,
|
||||
contextmenu: false,
|
||||
popup_css: "./RenderContentEdit.TinyMCE.css"
|
||||
};
|
||||
}
|
||||
|
||||
private handleEditorChange(content: string, editor: any): void {
|
||||
this.setState({
|
||||
editorContent: encode(content)
|
||||
}, () => {
|
||||
this.props.onContentUpdate(encode(content));
|
||||
});
|
||||
}
|
||||
|
||||
private setupContentEditor(editor: any): void {
|
||||
|
||||
debugger;
|
||||
// To add a enhanced preview icon:
|
||||
editor.ui.registry.addIcon('enchancedpreview', '<svg width="24" height="24" fill="none" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M12 9.005a4 4 0 1 1 0 8 4 4 0 0 1 0-8ZM12 5.5c4.613 0 8.596 3.15 9.701 7.564a.75.75 0 1 1-1.455.365 8.503 8.503 0 0 0-16.493.004.75.75 0 0 1-1.455-.363A10.003 10.003 0 0 1 12 5.5Z" fill="#212121"/></svg>');
|
||||
|
||||
FieldPicker.addToolbarButton(editor, this.props.context, this.props.listFieldsSchema, this.props.listData);
|
||||
FieldPicker.addEnhancedPreviewToolbarButton(editor, this.props.context, this.props.listFieldsSchema, this.props.listData);
|
||||
|
||||
|
||||
editor.ui.registry.addButton('externalimage', {
|
||||
icon: 'image',
|
||||
tooltip: 'Insert external picture',
|
||||
disabled: true,
|
||||
onAction: (_: any) => {
|
||||
editor.execCommand('mceImage');
|
||||
}
|
||||
});
|
||||
|
||||
editor.ui.registry.addMenuItem('externalimage', {
|
||||
text: 'External image',
|
||||
tooltip: 'Insert external picture',
|
||||
icon: 'image',
|
||||
onAction: (_: any) => {
|
||||
editor.execCommand('mceImage');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private getMenuItems(): object {
|
||||
return {
|
||||
edit: { title: 'Edit', items: 'undo redo | selectall | searchreplace | directionality' },
|
||||
view: { title: 'View', items: 'visualaid | fullscreen | preview' },
|
||||
insert: { title: 'Insert', items: 'link unlink | externalimage picturepicker | anchor | media ' },
|
||||
format: { title: 'Format', items: 'bold italic underline strikethrough superscript subscript forecolor backcolor | blockformats | removeformat unlink' },
|
||||
table: { title: 'Table', items: 'inserttable tableprops deletetable | row column cell' }
|
||||
};
|
||||
}
|
||||
|
||||
private getToolbarItems(): string {
|
||||
return [
|
||||
`undo redo`,
|
||||
`formatselect`,
|
||||
`alignleft aligncenter alignright`,
|
||||
`bullist numlist indent outdent`,
|
||||
`bold italic underline strikethrough forecolor backcolor removeformat`,
|
||||
`link unlink externalimage picturepicker media fieldpicker enchancedpreview`,
|
||||
`table`,
|
||||
`fullscreen`
|
||||
].join('|');
|
||||
}
|
||||
|
||||
private startsWith(value: string, matches: string[]): boolean {
|
||||
const startsWith = matches.filter(match => {
|
||||
return value.match(new RegExp(`^${match}`, 'i')) !== null;
|
||||
});
|
||||
|
||||
return startsWith.length > 0;
|
||||
}
|
||||
|
||||
private getColourMap(): any {
|
||||
const __themeState__ = (window as any)['__themeState__'];
|
||||
|
||||
if (!__themeState__ || !__themeState__.theme) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { startsWith } = this;
|
||||
|
||||
let color_map: any[] = [];
|
||||
Object.keys(__themeState__.theme)
|
||||
.filter(key => __themeState__.theme[key][0] === '#')
|
||||
.filter(key => startsWith(key, ['neutral', 'black', 'white', 'theme']))
|
||||
.forEach(key => {
|
||||
let colour = __themeState__.theme[key].substr(1);
|
||||
if (startsWith(key, ['black'])) {
|
||||
colour = '000000';
|
||||
}
|
||||
|
||||
if (color_map.indexOf(colour) === -1) {
|
||||
color_map.push(colour);
|
||||
color_map.push(key);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
return color_map;
|
||||
|
||||
}
|
||||
|
||||
|
||||
public render(): React.ReactElement<IRenderContentEditProps> {
|
||||
|
||||
return (
|
||||
<div className={Styles.renderContent}>
|
||||
<Editor
|
||||
value={decode(this.state.editorContent)}
|
||||
//initialValue={decode(this.state.editorContent)}
|
||||
init={this.initOptions}
|
||||
onEditorChange={(content: string, editor: any) =>
|
||||
this.handleEditorChange(content, editor)
|
||||
}
|
||||
/>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
$themePrimary: "[theme: themePrimary, default: #666666]";
|
||||
$themeSecondary: "[theme: themeSecondary, default: #999999]";
|
|
@ -0,0 +1,70 @@
|
|||
import * as React from 'react';
|
||||
import * as createDOMPurify from 'dompurify';
|
||||
import * as DataHelper from '../../helpers/DataHelper';
|
||||
import parse from 'html-react-parser';
|
||||
import { IFieldSchema } from '../../model/IFieldSchema';
|
||||
import { decode } from '../../utils/EncodingUtils';
|
||||
|
||||
|
||||
export interface IRenderContentViewProps {
|
||||
listData: any;
|
||||
editorContent: string;
|
||||
listFieldsSchema: IFieldSchema[];
|
||||
}
|
||||
|
||||
export interface IRenderContentViewState { }
|
||||
|
||||
export class RenderContentView extends React.PureComponent<
|
||||
IRenderContentViewProps,
|
||||
IRenderContentViewState
|
||||
> {
|
||||
private DOMPurify: any;
|
||||
private editorRef = null;
|
||||
|
||||
constructor(props: IRenderContentViewProps) {
|
||||
super(props);
|
||||
this.DOMPurify = createDOMPurify(window);
|
||||
this.state = {};
|
||||
}
|
||||
|
||||
|
||||
public render(): React.ReactElement<IRenderContentViewProps> {
|
||||
const sanitisedHTML: string = this.DOMPurify.sanitize(decode(this.props.editorContent), {
|
||||
ADD_ATTR: ['target', 'frameborder', 'allowfullscreen', 'tabindex'],
|
||||
ADD_TAGS: ['iframe'],
|
||||
});
|
||||
|
||||
const result: string | JSX.Element | JSX.Element[] = sanitisedHTML ? this.reactify(sanitisedHTML) : <span></span>;
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
ref={this.editorRef}
|
||||
className='editor-styles'
|
||||
data-sp-feature-tag='Rich Text Editor'
|
||||
>
|
||||
{result}
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
private reactify(sanitisedHTML: string): string | JSX.Element | JSX.Element[] {
|
||||
const parser = (input: string) => parse(input, {
|
||||
replace: (domNode: any) => {
|
||||
if (domNode && domNode.type === 'text' && typeof domNode.data !== 'undefined') {
|
||||
const regex = new RegExp("{{(.*?)}}", "g");
|
||||
const match = regex.exec(domNode.data);
|
||||
if (match) {
|
||||
const column = match[1];
|
||||
const data = DataHelper.renderData(this.props.listData, column, this.props.listFieldsSchema);
|
||||
return data;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const parsedData = parser(sanitisedHTML);
|
||||
return parsedData;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
.tagsList {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.tag {
|
||||
margin: 0 0 0 5px;
|
||||
padding: 5px;
|
||||
background-color: #eee;
|
||||
border-radius: 5px;
|
||||
border: 1px solid;
|
||||
border-radius: 12px;
|
||||
height: 22px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
background-color: #fff;
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
import * as React from 'react';
|
||||
//import styles from './Tags.module.scss';
|
||||
import { Space, Tag } from 'antd';
|
||||
|
||||
export interface ITagsProps {
|
||||
keywords: string[];
|
||||
}
|
||||
|
||||
const Tags: React.FunctionComponent<ITagsProps> = ({ keywords }) => {
|
||||
|
||||
if (!keywords || keywords.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Space size={[0, 8]} wrap>
|
||||
{keywords.map((keyword: any, i) =>
|
||||
<Tag color="#108ee9">{keyword}</Tag>
|
||||
)}
|
||||
</Space>
|
||||
);
|
||||
};
|
||||
export default Tags;
|
|
@ -0,0 +1,88 @@
|
|||
import { WebPartContext } from '@microsoft/sp-webpart-base';
|
||||
import * as React from 'react';
|
||||
import { RenderContentView } from '../RenderContentView/RenderContentView';
|
||||
|
||||
import { createGlobalStyle } from 'styled-components';
|
||||
import { IFieldSchema } from '../../model/IFieldSchema';
|
||||
|
||||
export interface IPropertyFieldEnhancedPreviewHostProps {
|
||||
listData: any;
|
||||
editorContent: string;
|
||||
listFieldsSchema: IFieldSchema[];
|
||||
openPanel?: boolean;
|
||||
editor: any;
|
||||
context: WebPartContext;
|
||||
}
|
||||
|
||||
|
||||
export interface IPropertyFieldFieldPickerHostStats {
|
||||
|
||||
}
|
||||
|
||||
const GlobalStyle = createGlobalStyle`
|
||||
.panel-styles p em {
|
||||
font-style: italic !important;
|
||||
}
|
||||
.panel-styles p strong {
|
||||
font-weight: bold !important;
|
||||
}
|
||||
.panel-styles div[class^="ant-space"] {
|
||||
flex-wrap: wrap;
|
||||
gap: 8px 0px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,'Noto Sans',sans-serif,'Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol','Noto Color Emoji';
|
||||
font-size: 14px;
|
||||
box-sizing: border-box;
|
||||
|
||||
.ant-space-item {
|
||||
|
||||
span[class^="ant-tag"]
|
||||
{
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
font-size: 12px;
|
||||
line-height: 20px;
|
||||
list-style: none;
|
||||
font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,'Noto Sans',sans-serif,'Apple Color Emoji','Segoe UI Emoji','Segoe UI Symbol','Noto Color Emoji';
|
||||
display: inline-block;
|
||||
height: auto;
|
||||
margin-inline-end: 8px;
|
||||
padding-inline: 7px;
|
||||
white-space: nowrap;
|
||||
background: rgba(0, 0, 0, 0.02);
|
||||
border: 1px solid #d9d9d9;
|
||||
border-radius: 4px;
|
||||
opacity: 1;
|
||||
transition: all 0.2s;
|
||||
text-align: start;
|
||||
color: #fff;
|
||||
}
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
export class EnchancedPreviewHost extends React.Component<IPropertyFieldEnhancedPreviewHostProps, IPropertyFieldFieldPickerHostStats> {
|
||||
|
||||
|
||||
constructor(props: IPropertyFieldEnhancedPreviewHostProps) {
|
||||
super(props);
|
||||
}
|
||||
|
||||
public render(): React.ReactElement<IPropertyFieldEnhancedPreviewHostProps> {
|
||||
|
||||
|
||||
return (
|
||||
<div>
|
||||
<GlobalStyle />
|
||||
<RenderContentView
|
||||
listData={this.props.listData}
|
||||
editorContent={this.props.editorContent}
|
||||
listFieldsSchema={this.props.listFieldsSchema}
|
||||
/>
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,143 @@
|
|||
import * as React from 'react';
|
||||
import { WebPartContext } from '@microsoft/sp-webpart-base';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
|
||||
|
||||
import { EnchancedPreviewHost, IPropertyFieldEnhancedPreviewHostProps } from './TinyMCE.EnchancedPreviewHost';
|
||||
import { encode } from '../../utils/EncodingUtils';
|
||||
import { IFieldSchema } from '../../model/IFieldSchema';
|
||||
|
||||
export function getEnhancedPreviewDialog(editor: any, error: boolean, context: WebPartContext): any {
|
||||
const controls: any[] = [{
|
||||
type: 'htmlpanel',
|
||||
html: "<div class='panel-styles'><div id='enchancedPreviewContainer'>Loading</div><div>"
|
||||
}];
|
||||
|
||||
const dialogConfig = {
|
||||
title: 'Enhanced preview',
|
||||
size: 'large',
|
||||
body: {
|
||||
type: 'panel',
|
||||
items: controls
|
||||
},
|
||||
buttons: [
|
||||
{
|
||||
type: 'cancel',
|
||||
name: 'close',
|
||||
text: 'Close',
|
||||
primary: true
|
||||
}
|
||||
],
|
||||
initialData: {
|
||||
|
||||
},
|
||||
onSubmit: (api: any) => {
|
||||
//const data = api.getData();
|
||||
}
|
||||
};
|
||||
|
||||
return dialogConfig;
|
||||
}
|
||||
|
||||
export function showEnhancedPreviewDialog(editor: any, context: WebPartContext, listFieldsSchema: IFieldSchema[], listData: any, editorContent: string): void {
|
||||
|
||||
const dialogConfig = getEnhancedPreviewDialog(editor, false, context);
|
||||
editor.windowManager.open(dialogConfig);
|
||||
|
||||
const pickerProps: IPropertyFieldEnhancedPreviewHostProps = {
|
||||
listData: listData,
|
||||
editorContent: editorContent,
|
||||
listFieldsSchema: listFieldsSchema,
|
||||
openPanel: true,
|
||||
editor: editor,
|
||||
context: context
|
||||
};
|
||||
|
||||
const enchancedPreviewElement = React.createElement(EnchancedPreviewHost, pickerProps);
|
||||
ReactDOM.render(enchancedPreviewElement, document.getElementById('enchancedPreviewContainer'));
|
||||
}
|
||||
|
||||
export function addToolbarButton(editor: any, context: WebPartContext, listFieldsSchema: IFieldSchema[], listData: any): void {
|
||||
|
||||
console.log(listFieldsSchema);
|
||||
|
||||
editor.ui.registry.addSplitButton('fieldpicker', {
|
||||
icon: 'plus',
|
||||
tooltip: 'Insert field from SharePoint list',
|
||||
disabled: false,
|
||||
onAction: (_: any) => {
|
||||
},
|
||||
onItemAction: function (buttonApi: any, value: any) {
|
||||
editor.insertContent(value);
|
||||
},
|
||||
fetch: function (callback: any) {
|
||||
const items = listFieldsSchema.map(f => {
|
||||
return {
|
||||
type: 'choiceitem',
|
||||
text: f.title,
|
||||
value: `{{${f.staticName}}}`
|
||||
}
|
||||
})
|
||||
|
||||
callback(items);
|
||||
},
|
||||
onSetup: (buttonApi: any) => {
|
||||
const editorEventCallback = (eventApi: any) => {
|
||||
const nodeName = eventApi.element.nodeName.toLowerCase();
|
||||
switch (nodeName) {
|
||||
case 'div':
|
||||
case 'iframe':
|
||||
case 'img':
|
||||
case 'a':
|
||||
buttonApi.setEnabled(true);
|
||||
break;
|
||||
default:
|
||||
buttonApi.setEnabled(true);
|
||||
}
|
||||
};
|
||||
editor.on('NodeChange', editorEventCallback);
|
||||
return (buttonApi2: any) => {
|
||||
editor.off('NodeChange', editorEventCallback);
|
||||
};
|
||||
}
|
||||
})
|
||||
}
|
||||
export function addEnhancedPreviewToolbarButton(editor: any, context: WebPartContext, listFieldsSchema: IFieldSchema[], listData: any): void {
|
||||
|
||||
editor.ui.registry.addButton('enchancedpreview', {
|
||||
icon: 'enchancedpreview',
|
||||
tooltip: 'Enhanced preview',
|
||||
disabled: true,
|
||||
onAction: (_: any) => {
|
||||
const content = encode(editor.getContent());
|
||||
showEnhancedPreviewDialog(editor, context, listFieldsSchema, listData, content);
|
||||
},
|
||||
onSetup: (buttonApi: any) => {
|
||||
const editorEventCallback = (eventApi: any) => {
|
||||
const nodeName = eventApi.element.nodeName.toLowerCase();
|
||||
switch (nodeName) {
|
||||
case 'div':
|
||||
case 'iframe':
|
||||
case 'img':
|
||||
case 'a':
|
||||
buttonApi.setEnabled(false);
|
||||
break;
|
||||
default:
|
||||
buttonApi.setEnabled(true);
|
||||
}
|
||||
};
|
||||
editor.on('NodeChange', editorEventCallback);
|
||||
return (buttonApi2: any) => {
|
||||
editor.off('NodeChange', editorEventCallback);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
@import '~@fluentui/react/dist/sass/References.scss';
|
||||
|
||||
.tinymceEditor {
|
||||
overflow: hidden;
|
||||
padding: 1em;
|
||||
color: "[theme:bodyText, default: #323130]";
|
||||
color: var(--bodyText);
|
||||
&.teams {
|
||||
font-family: $ms-font-family-fallbacks;
|
||||
}
|
||||
}
|
||||
|
||||
.welcome {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.welcomeImage {
|
||||
width: 100%;
|
||||
max-width: 420px;
|
||||
}
|
||||
|
||||
.links {
|
||||
a {
|
||||
text-decoration: none;
|
||||
color: "[theme:link, default:#03787c]";
|
||||
color: var(--link); // note: CSS Custom Properties support is limited to modern browsers only
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
color: "[theme:linkHovered, default: #014446]";
|
||||
color: var(--linkHovered); // note: CSS Custom Properties support is limited to modern browsers only
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.person {
|
||||
max-width: 100%;
|
||||
min-height: 51px;
|
||||
--avatar-size: 51px; //three lines of text
|
||||
--line3-color: $ms-color-black;
|
||||
--line3-color: $ms-color-black;
|
||||
--line3-color: $ms-color-black;
|
||||
|
||||
&.picture {
|
||||
min-height: 120px;
|
||||
--avatar-size: 120px;
|
||||
}
|
||||
|
||||
&.bold {
|
||||
min-height: 60px;
|
||||
--avatar-size: 60px;
|
||||
--font-size: 16px;
|
||||
--font-weight: 600;
|
||||
--line2-font-size: 14px;
|
||||
--line3-font-size: 14px;
|
||||
}
|
||||
}
|
||||
|
||||
.personContainer {
|
||||
position: relative;
|
||||
|
||||
&.badged {
|
||||
> i {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
color: gold;
|
||||
font-size: 15px;
|
||||
z-index: 1;
|
||||
text-shadow: 1px 1px 3px #666;
|
||||
animation: pulse 4s infinite;
|
||||
animation-delay: 2s;
|
||||
border-radius: 50%;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,135 @@
|
|||
import * as React from 'react';
|
||||
import styles from './TinymceEditor.module.scss';
|
||||
import { ITinymceEditorProps } from './ITinymceEditorProps';
|
||||
import { useEffect } from 'react';
|
||||
import { RequestStatus } from '../model/IRequestStatus';
|
||||
import { DisplayMode, Text } from '@microsoft/sp-core-library';
|
||||
import SharePointService from '../services/SharePointService';
|
||||
import { RenderContentView } from './RenderContentView/RenderContentView';
|
||||
import { RenderContentEdit } from './RenderContentEdit/RenderContentEdit';
|
||||
|
||||
export const TinymceEditor: React.FunctionComponent<ITinymceEditorProps> = (
|
||||
{ hasTeamsContext, siteUrl, listId, listFieldsSchema, listItemId, userId, context, onContentUpdate, editorContent, displayMode }) => {
|
||||
|
||||
const [status, setStatus] = React.useState(RequestStatus.idle);
|
||||
const [errorMessage, setErrorMessage] = React.useState('');
|
||||
const [formData, setFormData] = React.useState(null);
|
||||
|
||||
console.log(status);
|
||||
console.log(errorMessage);
|
||||
|
||||
const loadListItem = async () => {
|
||||
|
||||
try {
|
||||
setStatus(RequestStatus.loading);
|
||||
setErrorMessage('');
|
||||
|
||||
const dataCacheKey = `OC_TinymceEditor_${listId}_${listItemId}`;
|
||||
const cachedData: any = window.localStorage.getItem(dataCacheKey);
|
||||
|
||||
|
||||
if (cachedData !== null) {
|
||||
setFormData(JSON.parse(cachedData));
|
||||
setStatus(RequestStatus.loaded);
|
||||
}
|
||||
else {
|
||||
|
||||
const response: any[] = await getListItem();
|
||||
if (response.length > 0) {
|
||||
const [data] = response;
|
||||
setFormData(data);
|
||||
window.localStorage.setItem(dataCacheKey, JSON.stringify(data));
|
||||
setStatus(RequestStatus.loaded);
|
||||
}
|
||||
else {
|
||||
setStatus(RequestStatus.empty);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
} catch (error) {
|
||||
setStatus(RequestStatus.error);
|
||||
setErrorMessage('Error in getting data');
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (listId && listItemId) {
|
||||
loadListItem();
|
||||
}
|
||||
}, [listId, listItemId]);
|
||||
|
||||
return (
|
||||
<section className={`${styles.tinymceEditor} ${hasTeamsContext ? styles.teams : ''}`}>
|
||||
|
||||
|
||||
{/* {listFieldsSchema && <pre>{JSON.stringify(listFieldsSchema, null, 4)}</pre>} */}
|
||||
{formData ?
|
||||
displayMode === DisplayMode.Read ?
|
||||
<RenderContentView
|
||||
listData={formData}
|
||||
editorContent={editorContent}
|
||||
listFieldsSchema={listFieldsSchema}
|
||||
|
||||
/> :
|
||||
<RenderContentEdit
|
||||
listData={formData}
|
||||
context={context}
|
||||
editorContent={editorContent}
|
||||
onContentUpdate={onContentUpdate}
|
||||
listFieldsSchema={listFieldsSchema}
|
||||
/>
|
||||
: null
|
||||
|
||||
}
|
||||
</section>
|
||||
);
|
||||
|
||||
|
||||
|
||||
async function getListItem(): Promise<any[]> {
|
||||
|
||||
try {
|
||||
let endpoint = Text.format("{0}/_api/web/lists(guid'{1}')/RenderListDataAsStream", siteUrl, listId);
|
||||
const rowLimitXml = `<RowLimit Paged="True">${1}</RowLimit>`;
|
||||
const queryXml = `
|
||||
<Query>
|
||||
<Where>
|
||||
<And>
|
||||
<IsNotNull>
|
||||
<FieldRef Name='ID' />
|
||||
</IsNotNull>
|
||||
<Eq>
|
||||
<FieldRef Name='ID' />
|
||||
<Value Type='Counter'>${listItemId}</Value>
|
||||
</Eq>
|
||||
</And>
|
||||
</Where>
|
||||
</Query>`;
|
||||
|
||||
const payload = {
|
||||
parameters: {
|
||||
ViewXml: `<View>${rowLimitXml}${queryXml}</View>`,
|
||||
RenderOptions: 2,
|
||||
DatesInUtc: true,
|
||||
ReplaceGroup: true
|
||||
}
|
||||
};
|
||||
const response = await SharePointService.postData(endpoint, payload);
|
||||
const result = response.Row || response;
|
||||
return result;
|
||||
}
|
||||
catch (er) {
|
||||
er.json().then((error: any) => {
|
||||
console.log(error);
|
||||
});
|
||||
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
|
@ -0,0 +1,65 @@
|
|||
import * as React from 'react';
|
||||
import { get } from "@microsoft/sp-lodash-subset";
|
||||
import { Link } from '@fluentui/react/lib/Link';
|
||||
import PeopleCard from '../components/PeopleCards/PeopleCards';
|
||||
import { IFieldSchema } from '../model/IFieldSchema';
|
||||
import { FieldType } from '../model/FieldType';
|
||||
import { toLocaleDateString, parseDateSafely } from '../utils/DateUtils';
|
||||
import Tags from '../components/Tags/Tags';
|
||||
|
||||
|
||||
|
||||
export function renderData(listData: any, selectedColumn: string, listFieldsSchema: IFieldSchema[]): JSX.Element {
|
||||
|
||||
if (!listData) {
|
||||
return <span></span>;
|
||||
}
|
||||
const column: any = listFieldsSchema.find(c => c.staticName === selectedColumn);
|
||||
const data = get(listData, column.staticName);
|
||||
|
||||
if (data === undefined || data === null) {
|
||||
return <span></span>;
|
||||
}
|
||||
else {
|
||||
switch (column.fieldType) {
|
||||
case FieldType.Choice:
|
||||
case FieldType.MultiChoice:
|
||||
if (data && Array.isArray(data) && data.length) {
|
||||
return (
|
||||
<div>
|
||||
<Tags keywords={data} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return <span>{data}</span>;
|
||||
case FieldType.Note:
|
||||
return <span dangerouslySetInnerHTML={{ __html: data.replace(/\n/g, '<br />') }} />;
|
||||
case FieldType.DateTime:
|
||||
const date = data instanceof Date ? data : parseDateSafely(data);
|
||||
return <span>{toLocaleDateString(date)}</span>;
|
||||
case FieldType.Number:
|
||||
return <span>{data === 0 ? '0' : data}</span>;
|
||||
case FieldType.TaxonomyFieldType:
|
||||
const keyword = data.Label ? [data.Label] : [];
|
||||
return data ? <Tags keywords={keyword} /> : <span> </span>;
|
||||
case FieldType.TaxonomyFieldTypeMulti:
|
||||
const keywords = data.map((item: any) => item.Label);
|
||||
return keywords ? <Tags keywords={keywords} /> : <span> </span>;
|
||||
case FieldType.URL:
|
||||
const descriptionData = get(data, `${column.staticName}.desc`);
|
||||
const description = descriptionData ? descriptionData : data;
|
||||
return data ? <Link target={'_blank'} href={data} underline={false} data-interception="off">{description}</Link> : <span> </span>;
|
||||
case FieldType.User:
|
||||
case FieldType.UserMulti:
|
||||
return <PeopleCard users={Array.isArray(data) ? data : []} />;
|
||||
case FieldType.Boolean:
|
||||
return <span>{data ? 'Yes' : 'No'}</span>;
|
||||
default:
|
||||
return <span>{data}</span>;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
import { Logger, LogLevel } from "@pnp/logging";
|
||||
|
||||
export class LogHelper {
|
||||
|
||||
public static verbose(className: string, methodName: string, message: string):void {
|
||||
message = this._formatMessage(className, methodName, message);
|
||||
Logger.write(message, LogLevel.Verbose);
|
||||
}
|
||||
|
||||
public static info(className: string, methodName: string, message: string):void {
|
||||
message = this._formatMessage(className, methodName, message);
|
||||
Logger.write(message, LogLevel.Info);
|
||||
}
|
||||
|
||||
public static warning(className: string, methodName: string, message: string):void {
|
||||
message = this._formatMessage(className, methodName, message);
|
||||
Logger.write(message, LogLevel.Warning);
|
||||
}
|
||||
|
||||
public static error(className: string, methodName: string, message: string):void {
|
||||
message = this._formatMessage(className, methodName, message);
|
||||
Logger.write(message, LogLevel.Error);
|
||||
}
|
||||
|
||||
public static exception(className: string, methodName: string, error: Error):void {
|
||||
error.message = this._formatMessage(className, methodName, error.message);
|
||||
Logger.error(error);
|
||||
}
|
||||
|
||||
private static _formatMessage(className: string, methodName: string, message: string): string {
|
||||
const d:Date = new Date();
|
||||
const dateStr:string = d.getDate() + '-' + (d.getMonth() + 1) + '-' + d.getFullYear() + ' ' +
|
||||
d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() + '.' + d.getMilliseconds();
|
||||
return `${dateStr} ${className} > ${methodName} > ${message}`;
|
||||
}
|
||||
}
|
|
@ -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"
|
||||
}
|
||||
});
|
|
@ -0,0 +1,18 @@
|
|||
declare interface ITinymceEditorWebPartStrings {
|
||||
PropertyPaneDescription: string;
|
||||
BasicGroupName: string;
|
||||
DescriptionFieldLabel: string;
|
||||
AppLocalEnvironmentSharePoint: string;
|
||||
AppLocalEnvironmentTeams: string;
|
||||
AppLocalEnvironmentOffice: string;
|
||||
AppLocalEnvironmentOutlook: string;
|
||||
AppSharePointEnvironment: string;
|
||||
AppTeamsTabEnvironment: string;
|
||||
AppOfficeEnvironment: string;
|
||||
AppOutlookEnvironment: string;
|
||||
}
|
||||
|
||||
declare module 'TinymceEditorWebPartStrings' {
|
||||
const strings: ITinymceEditorWebPartStrings;
|
||||
export = strings;
|
||||
}
|
|
@ -0,0 +1,23 @@
|
|||
export enum FieldType {
|
||||
Text = 'Text',
|
||||
Note = 'Note',
|
||||
Lookup = 'Lookup',
|
||||
LookupMulti = 'LookupMulti',
|
||||
Choice = 'Choice',
|
||||
MultiChoice = 'MultiChoice',
|
||||
Number = 'Number',
|
||||
Currency = 'Currency',
|
||||
DateTime = 'DateTime',
|
||||
Boolean = 'Boolean',
|
||||
User = 'User',
|
||||
UserMulti = 'UserMulti',
|
||||
URL = 'URL',
|
||||
File = 'File',
|
||||
Computed = 'Computed',
|
||||
TaxonomyFieldType = 'TaxonomyFieldType',
|
||||
TaxonomyFieldTypeMulti = 'TaxonomyFieldTypeMulti',
|
||||
Location = 'Location',
|
||||
Thumbnail = 'Thumbnail',
|
||||
Attachments = 'Attachments',
|
||||
AllDayEvent = 'AllDayEvent'
|
||||
}
|
|
@ -0,0 +1,15 @@
|
|||
export interface IFieldSchema {
|
||||
title: string;
|
||||
staticName: string;
|
||||
required: boolean;
|
||||
fieldType: string;
|
||||
typeAsString: string;
|
||||
description: string;
|
||||
choices?: any[];
|
||||
multiChoices?: string[];
|
||||
displayFormat?: number;
|
||||
firstDayOfWeek?: number;
|
||||
localeId?: string;
|
||||
termSetId?: string;
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
export enum RequestStatus {
|
||||
idle = 1,
|
||||
error,
|
||||
loading,
|
||||
empty,
|
||||
loaded,
|
||||
}
|
|
@ -0,0 +1,236 @@
|
|||
import { Text } from '@microsoft/sp-core-library';
|
||||
import { SPHttpClient, ISPHttpClientOptions, SPHttpClientResponse } from '@microsoft/sp-http';
|
||||
|
||||
import { endsWith } from '../utils/StringUtils';
|
||||
import { LogHelper } from '../helpers/LogHelper';
|
||||
|
||||
class SharePointService {
|
||||
|
||||
/***************************************************************************
|
||||
* The spHttpClient object used for performing REST calls to SharePoint
|
||||
***************************************************************************/
|
||||
private static spHttpClient: SPHttpClient;
|
||||
|
||||
|
||||
/**************************************************************************************************
|
||||
* Init
|
||||
* @param httpClient : The spHttpClient required to perform REST calls against SharePoint
|
||||
**************************************************************************************************/
|
||||
|
||||
public static Init(spHttpClient: SPHttpClient): void {
|
||||
this.spHttpClient = spHttpClient;
|
||||
LogHelper.info('SharePointService', 'Init', 'spHttpClient initialised');
|
||||
}
|
||||
|
||||
|
||||
/**************************************************************************************************
|
||||
* Performs a CAML query against the specified list and returns the resulting items
|
||||
* @param webUrl : The url of the web which contains the specified list
|
||||
* @param listId : The id of the list which contains the elements to query
|
||||
* @param camlQuery : The CAML query to perform on the specified list
|
||||
**************************************************************************************************/
|
||||
public static getListItemsByQuery(webUrl: string, listId: string, camlQuery: string): Promise<any> {
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
let endpoint = Text.format("{0}/_api/web/lists(guid'{1}')/GetItems?$expand=FieldValuesAsText,FieldValuesAsHtml", webUrl, listId);
|
||||
|
||||
let data: any = {
|
||||
query: {
|
||||
__metadata: { type: "SP.CamlQuery" },
|
||||
ViewXml: camlQuery
|
||||
}
|
||||
};
|
||||
let options: ISPHttpClientOptions = { headers: { 'odata-version': '3.0' }, body: JSON.stringify(data) };
|
||||
|
||||
this.spHttpClient.post(endpoint, SPHttpClient.configurations.v1, options)
|
||||
.then((postResponse: SPHttpClientResponse) => {
|
||||
if (postResponse.ok) {
|
||||
resolve(postResponse.json());
|
||||
}
|
||||
else {
|
||||
reject(postResponse);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**************************************************************************************************
|
||||
* Performs a CAML query against the specified list and returns the resulting items
|
||||
* @param webUrl : The url of the web which contains the specified list
|
||||
* @param listId : The id of the list which contains the elements to query
|
||||
* @param camlQuery : The CAML query to perform on the specified list
|
||||
**************************************************************************************************/
|
||||
public static getListItemsByQueryStream(webUrl: string, listId: string, camlQuery: string): Promise<any> {
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
|
||||
console.log(camlQuery);
|
||||
let endpoint = Text.format("{0}/_api/web/lists(guid'{1}')/RenderListDataAsStream", webUrl, listId);
|
||||
const searchFilter = `<View><Query><Where><Contains><FieldRef Name="Title" /><Value Type="Text">VPN</Value></Contains></Where></Query></View>`;
|
||||
|
||||
const data = {
|
||||
parameters: {
|
||||
ViewXml: camlQuery,
|
||||
OverrideViewXml: searchFilter,
|
||||
RenderOptions: 2,
|
||||
DatesInUtc: true,
|
||||
ReplaceGroup: true
|
||||
}
|
||||
};
|
||||
let options: ISPHttpClientOptions = { headers: { 'odata-version': '3.0' }, body: JSON.stringify(data) };
|
||||
|
||||
this.spHttpClient.post(endpoint, SPHttpClient.configurations.v1, options)
|
||||
.then((postResponse: SPHttpClientResponse) => {
|
||||
if (postResponse.ok) {
|
||||
resolve(postResponse.json());
|
||||
}
|
||||
else {
|
||||
reject(postResponse);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public static postData(endpoint: string, payload: any): Promise<any> {
|
||||
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
|
||||
let options: ISPHttpClientOptions = { headers: { 'odata-version': '3.0' }, body: JSON.stringify(payload) };
|
||||
|
||||
this.spHttpClient.post(endpoint, SPHttpClient.configurations.v1, options)
|
||||
.then((postResponse: SPHttpClientResponse) => {
|
||||
if (postResponse.ok) {
|
||||
resolve(postResponse.json());
|
||||
}
|
||||
else {
|
||||
reject(postResponse);
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**************************************************************************************************
|
||||
* Returns a sorted array of all available list titles for the specified web
|
||||
* @param webUrl : The web URL from which the list titles must be taken from
|
||||
**************************************************************************************************/
|
||||
public static getListTitlesFromWeb(webUrl: string): Promise<IListTitle[]> {
|
||||
return new Promise<IListTitle[]>((resolve, reject) => {
|
||||
let endpoint = Text.format("{0}/_api/web/lists?$select=Id,Title&$filter=(IsPrivate eq false) and (IsCatalog eq false) and (Hidden eq false)", webUrl);
|
||||
this.spHttpClient.get(endpoint, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
|
||||
if (response.ok) {
|
||||
response.json().then((data: any) => {
|
||||
let listTitles: IListTitle[] = data.value.map((list: any) => { return { id: list.Id, title: list.Title }; });
|
||||
resolve(listTitles.sort((a, b) => { return Number(a.title > b.title); }));
|
||||
})
|
||||
.catch((error) => { reject(error); });
|
||||
}
|
||||
else {
|
||||
reject(response);
|
||||
}
|
||||
})
|
||||
.catch((error) => { reject(error); });
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public static getListUrl(siteUrl: string, listId: string): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
let endpoint = Text.format("{0}/_api/web/lists(guid'{1}')/DefaultView?$select=ServerRelativePath", siteUrl, listId);
|
||||
this.spHttpClient.get(endpoint, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
|
||||
if (response.ok) {
|
||||
response.json().then((data: any) => {
|
||||
if (data.ServerRelativePath) {
|
||||
resolve(data.ServerRelativePath.DecodedUrl)
|
||||
}
|
||||
else {
|
||||
reject("");
|
||||
}
|
||||
|
||||
})
|
||||
.catch((error) => { reject(error); });
|
||||
}
|
||||
else {
|
||||
reject(response);
|
||||
}
|
||||
})
|
||||
.catch((error) => { reject(error); });
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**************************************************************************************************
|
||||
* Returns the available fields for the specified list id
|
||||
* @param webUrl : The web URL from which the specified list is located
|
||||
* @param listId : The id of the list from which to load the fields
|
||||
* @param selectProperties : Optionnaly, the select properties to narrow down the query size
|
||||
* @param orderBy : Optionnaly, the by which the results needs to be ordered
|
||||
**************************************************************************************************/
|
||||
public static getListFields(webUrl: string, listId: string, selectProperties?: string[], orderBy?: string): Promise<any> {
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
let selectProps = selectProperties ? selectProperties.join(',') : '';
|
||||
let order = orderBy ? orderBy : 'InternalName';
|
||||
let endpoint = Text.format("{0}/_api/web/lists(guid'{1}')/Fields?$select={2}&$orderby={3}", webUrl, listId, selectProps, order);
|
||||
this.spHttpClient.get(endpoint, SPHttpClient.configurations.v1).then((response: SPHttpClientResponse) => {
|
||||
if (response.ok) {
|
||||
resolve(response.json());
|
||||
}
|
||||
else {
|
||||
reject(response);
|
||||
}
|
||||
})
|
||||
.catch((error) => { reject(error); });
|
||||
});
|
||||
}
|
||||
public static getListFieldsAsDataStream(siteRelativeUrl: string, listRelativeUrl: string, selectProperties?: string[], orderBy?: string): Promise<any> {
|
||||
|
||||
//clean the slash if we are in the root site
|
||||
siteRelativeUrl = siteRelativeUrl === '/' ? '' : siteRelativeUrl;
|
||||
siteRelativeUrl = endsWith(siteRelativeUrl, "/") ? siteRelativeUrl : siteRelativeUrl + '/';
|
||||
|
||||
return new Promise<any>((resolve, reject) => {
|
||||
let endpoint = `${siteRelativeUrl}_api/web/getlist('${siteRelativeUrl}${listRelativeUrl}')/RenderListDataAsStream`;
|
||||
|
||||
const data = {
|
||||
parameters: {
|
||||
ViewXml: '<View><ViewFields><FieldRef Name="ID"/></ViewFields></View>',
|
||||
RenderOptions: 64,
|
||||
DatesInUtc: true,
|
||||
ReplaceGroup: true
|
||||
}
|
||||
};
|
||||
|
||||
let options: ISPHttpClientOptions = { headers: { 'odata-version': '3.0' }, body: JSON.stringify(data) };
|
||||
|
||||
this.spHttpClient.post(endpoint, SPHttpClient.configurations.v1, options)
|
||||
.then((postResponse: SPHttpClientResponse) => {
|
||||
return postResponse.json();
|
||||
})
|
||||
.then((data) => {
|
||||
const form = data.ClientForms.Edit;
|
||||
resolve(form[Object.keys(form)[0]]);
|
||||
})
|
||||
.catch((error) => {
|
||||
reject(error);
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
export default SharePointService;
|
||||
|
||||
export interface IListTitle {
|
||||
id: string;
|
||||
title: string;
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
export function toLocaleDateString(date: Date | null): string {
|
||||
if (!date) {
|
||||
return '';
|
||||
}
|
||||
const defaultOptions: Intl.DateTimeFormatOptions = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour12: false };
|
||||
|
||||
return date.toLocaleString("en-GB", defaultOptions);
|
||||
}
|
||||
|
||||
export function parseDateSafely(dateString:string) {
|
||||
try {
|
||||
return new Date(dateString);
|
||||
} catch (error) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
export function encode(rawString: string): string {
|
||||
return window.btoa(unescape(encodeURIComponent(rawString)));
|
||||
}
|
||||
|
||||
export function decode(encodedString: string): string {
|
||||
try {
|
||||
return decodeURIComponent(escape(window.atob(encodedString)));
|
||||
}
|
||||
catch (e) {
|
||||
console.error(e, encodedString);
|
||||
return encodedString;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,6 @@
|
|||
export function isNullOrEmpty(value: string): boolean {
|
||||
return value === undefined || value === null || typeof value.trim !== "function" || value.trim() === "";
|
||||
}
|
||||
export function endsWith(str:string, suffix:string) {
|
||||
return str.substring(-suffix.length) === suffix;
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 10 KiB |
Binary file not shown.
After Width: | Height: | Size: 542 B |
|
@ -0,0 +1,35 @@
|
|||
{
|
||||
"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,
|
||||
"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